text:
Q: Multiple WCF named pipe clients connecting without repeatedly invoking the endpoint's constructor? I've got a WCF server/client setup using named pipes, and my client connects to the host process (already running) as follows:
var pipeFactory = new DuplexChannelFactory<IArbiter>(this, new NetNamedPipeBinding(), new EndpointAddress(new Uri("net.pipe://localhost/IArbiter")));
arbiter = pipeFactory.CreateChannel();

This is fine for the first client connecting, but when the second client connects, a new instance of the IArbiter implementation is created (the arbiter's constructor is called every time a connection happens).
Is there a way to find the "existing" instance of that arbiter at the endpoint address?

A: Figured it out, just need to set this above my class implementation:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]


text:
Q: $\ker A \subset \ker A^2$? or backwards? $Im~ A \subset Im~ A^2$? or backwards? Be $n \in \mathbb{N}$. Which of the following statements are true?
(i) $\ker A \subset \ker A^2 ~~ \forall A\in \mathbb{R}^{n \times n}$
(ii) $\ker A \supset \ker A^2 ~~ \forall A\in \mathbb{R}^{n \times n}$
(iii) $Im~ A \subset Im~ A^2 ~~ \forall A\in \mathbb{R}^{n \times n}$
(iv) $Im~ A \supset Im~ A^2 ~~ \forall A\in \mathbb{R}^{n \times n}$
My ideas so far:
(i) Is true,  $Ax=0 \Rightarrow A^2x=0$ by multiplying $A$
(ii) Is also true, $A^2x=0\Rightarrow Ax=0$ by multiplying $A^{-1}$
Is my solution so far correct? How to go on with $Im$?

A: You're correct only for $i.$ and for $ii.$  $A$ may be singular! Of course if $A$ is invertible then $\ker A=\{0\}=\ker A^2$.
For the image we have $\operatorname{im}(A^2)\subset  \operatorname{im}(A)$: in fact if $y=A^2x\in \operatorname{im}(A^2)$ the $z=Ax\in \operatorname{im}(A)$.
To prove that the inclusion is strict in general in the two cases consider
$$A=\begin{pmatrix}0&1\\0&0\end{pmatrix}$$

A: Hints:
$$Ax=0\implies A^2x=A(Ax)=A(0)=0$$
$$x=A^2y\;,\;\;Ay=z\implies x=Az=A(Ay)$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to recode data frame columns depending on maximum values? I have a dataframe with dozens of columns and a few thousand rows. I would like to recode the numeric columns that have a maximum value of 8 in such a way that 8 becomes NA, and recode the numeric columns that have a maximum value of 9 in such a way that 8 becomes NA and 9 becomes 9999. For example,
mydf <- data.frame(a = c(1, 2, 8, 9), b = c(7, 8, 9, 10), c = c(4, 5, 6, 9), d = c(5, 6, 7, 8), e = c("a", "b", "c", "d"))

> mydf
  a  b c d e
1 1  7 4 5 a
2 2  8 5 6 b
3 8  9 6 7 c
4 9 10 9 8 d

would become:
> mydf
     a  b    c  d e
1    1  7    4  5 a
2    2  8    5  6 b
3   NA  9    6  7 c
4 9999 10 9999 NA d

I thought of doing this:
mydf1 <- mydf[,sapply(mydf, max) == 8]
mydf2 <- mydf[,sapply(mydf, max) == 9]
mydf1[mydf1 == 8] <- NA
mydf2[mydf2 == 8] <- NA
mydf2[mydf2 == 9] <- 9999

but I don't know how to bring the recoded variables from the new data frames back into the original data frame -- and I'm sure there are much more efficient solutions anyways.

A: You can check max value for each column using lapply and recode if it is either 8 or 9.
mydf[] <- lapply(mydf, function(x) {
  if(max(x) %in%  c(8, 9)) {
    x[x == 8] <- NA
    x[x == 9] <- 9999
  }
  x
})
mydf

#     a  b    c  d e
#1    1  7    4  5 a
#2    2  8    5  6 b
#3   NA  9    6  7 c
#4 9999 10 9999 NA d

A: We can use tidyverse approaches to dynamically check if the column is numeric, then loop across those columns, check if 8 or 9 are %in% the max value, then use na_if to replace 8 to NA and replace to change the 9 to 9999
library(dplyr)
mydf %>%
    mutate(across(where(is.numeric), ~
   if(any(c(8, 9) %in% max(., na.rm = TRUE))) replace(na_if(., 8), .==9, 9999)))
#     a    c  d e
#1    1    4  5 a
#2    2    5  6 b
#3   NA    6  7 c
#4 9999 9999 NA d


text:
Q: Bypassing iframe sandbox? Someone iframing my website, using
<iframe src="http://example.org" sandbox=""></iframe>

This way, the sandbox attribute prevents my site to use iframe blocker on it. And it can be easily iframed.
Frame buster on my website:
if (window.top !== window.self) window.top.location.replace(window.self.location.href);

Is there a programmatic way to redirect to my site when its being iframed when used with sandbox attribute ?

A: I think the best thing you can do is show your own message with a target="top" link. The whole concept of the sandbox attribute is to disallow redirects. There is no way to bypass that and if you ever find one browser makers will probably find a way to stop it. It's clearly their intention.
This is just how the web works. You can't do whatever you want when it comes to browsers.

A: Iframing can be protected through the X-Frame-Options response header, set either X-Frame-Options value="DENY" or X-Frame-Options value="SAMEORIGIN". Through this response header settings you can protect your website against IFraming or clickjack attack.
Once X-Frame-Options response header is set, browser receives a standard message like "This content cannot be displayed in a frame".

A: The sandbox attribute is turning off all javascript, amongst other things.  This is why your frame buster will not be working, nor any other javascript people have provided.
W3 say of a sandbox:

*

*scripts are disallowed/disabled within the iframe

*links to other browsing contexts are disallowed/disabled within the iframe

A test shows that the attribute also disables meta redirects and any standard link which breaks out of the iframe.
With this strictness, I'd be very surprised if a redirect is possible, since that would defeat the point of the sandbox.
The best I can suggest would be to use the noscript tag to display a message to users seeing the page in a sandboxed iframe. You could style that so people can't see your content.
(If it is just one site being a problem, then blocking them with htaccess would probably be a better approach)

A: @SudiptaKumarMaiti's answer of X-Frame-Options works, but is being superseded by Content Security Policy (CSP) Level 2 - specifically the frame-ancestors directive.
To disallow framing completely (similar to X-Frame-Options: DENY), use this HTTP header:
Content-Security-Policy: frame-ancestors 'none';


text:
Q: Using Jenkins with .NET Project in C# I am trying to use Jenkins for my CI/CD but it is not working well for me. Jenkins trys to find the msbuild.exe. But Jenkins can not find it somehow. I always get an error in every build. Jenkins says he can not find msbuild.exe.
I already set the path of the msbuild.exe in the jenkins properties. Bit I still get an error.
I also installed the msbuild plugin.
I am using C# 7.0 with Visual Studio 2017 Professional.
My project is just a simple WinForm to test if Jenkins is working well for me or not.
My Jenkins version is 2.107.2
I am using Jenkins with a BitBucket Repo.
My Operating System is Windows 10.
My git version is 2.15.1.windows.2.
Can someone help?

A: If you use Jekins pipelines with generic batch files and not specific plug-ins this should work:
node {
    def YOUR_SOLUTION_CHECKOUT_PATH = "XXXX"
    def YOUR_OUTPUT_PATH = "YYYY"
    def msbuild = "C:\\Program Files (x86)\\MSBuild\\14.0\\Bin"
    stage('Build') {
        bat """chcp 65001
        \"${msbuild}\\msbuild.exe\" /t:Clean,Build \"${YOUR_SOLUTION_CHECKOUT_PATH}\" /p:OutputPath=\"${YOUR_OUTPUT_PATH}\""""
    }
}

Something around these lines should be enough for you to test if the build is working or not.


text:
Q: Flushing rewrite rules in wordpress I am trying to programmatically add a rewrite rule in wordpress using their rewrite functions. Typically it looks like this is used in conjunction with a plugin init or activate function so that the rewrite rules flush is only called once.
I'm not doing this in conjunction with a new plugin install, so where should I put these functions and calls so that I can call them once?
I'm going to add a rewrite rule as described here: http://codex.wordpress.org/Custom_Queries#Permalinks_for_Custom_Archives
Just not sure where to put this code.
Any help would be great. Thanks in advance.

A: If you are coding a custom theme you can put all your code in functions.php. Nevertheless, what is stopping you from creating a plugin for your own use?


text:
Q: Kivy: pass latency and drop-on-latency arguments to GstPlayer video streaming widget I am looking to extend the functionality of Kivy's Video widget.
When playing an RTSP video stream using the following Kivy code, there is latency of a few seconds. I would like to reduce the latency to around 100ms.
videostreaming.py:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import os.path

path_to_kv = os.path.join(os.path.dirname(__file__), 'videostreaming.kv')
Builder.load_file(path_to_kv)

class VideoStreaming(BoxLayout):
    pass

class TestApp(App):
    def build(self):
        root_widg = VideoStreaming()
        return root_widg

if __name__ == '__main__':
    TestApp().run()

videostreaming.kv:
<VideoStreaming>
    orientation: 'vertical'
    Video:
        source: "rtsp://192.168.1.88:554"
        state: 'play'

The low latency required can be achieved in Command Prompt by running:
$ .\gst-launch-1.0 -v playbin uri=rtsp://192.168.1.88:554 drop-on-latency=true latency=100

I would like to modify the behavior of the GstPlayer video module in Kivy to allow the "drop-on-latency=true" and "latency=100" arguments to be passed in.
The relevant Kivy source code is here:
https://github.com/kivy/kivy/blame/master/kivy/lib/gstplayer/_gstplayer.pyx#L237-L256
Q1. How can I subclass the GstPlayer Cython module to include access to the latency and drop-on-latency arguments?
I think that the subclass should override the load() method as follows:
# import GstPlayer module to be subclassed
from kivy.lib.gstplayer cimport GstPlayer

# define subclass
cdef class LowLatencyGst(GstPlayer):

    #override load() method
    def load(self):
        # run parent's load() method
        super(LowLatencyGst, self).load()

        # set required attributes: latency = 100, drop-on-latency = True
        # Unconfirmed whether these commands are correctly named
        g_object_set_int(self.appsink, 'latency', 100)
        g_object_set_int(self.appsink, 'drop-on-latency', 1)

Note: Trying to compile the above code is unsuccessful. It is pseudocode.
Q2. How can I integrate the above subclass as the CoreVideo provider for a Video widget?

A: The following commit provides a hardcoded solution to specifying latency and drop-on-latency values:
https://github.com/sabarlow/kivy/commit/846e3147db4ac784c1aa4d02f47666716fb57644
Added following lines of code to \kivy\lib\gstplayer_gstplayer.pyx:265
g_object_set_int(self.pipeline, 'drop-on-latency', self.drop_on_latency)
g_object_set_int(self.pipeline, 'latency', self.latency)

Setup with \kivy\lib\gstplayer_gstplayer.pyx:184
cdef int latency, drop_on_latency

And in same file:
def __init__(self, uri, sample_cb=None, eos_cb=None, message_cb=None, latency=500, drop_on_latency=1):
        super(GstPlayer, self).__init__()
        self.uri = uri
        self.sample_cb = sample_cb
        self.eos_cb = eos_cb
        self.message_cb = message_cb
        self.latency = latency
        self.drop_on_latency = drop_on_latency

Then Kivy is recompiled.
This does not allow values for latency and drop-on-latency to be passed in from Kivy's Video widget. Can anyone suggest how to make this work?


text:
Q: ScrollView Zooming problem In TapToZoom sample(apple code), If i pinch(inwards) the image becomes smaller than the window size(If i remove fingers it will fit correctly to window). How to fix the image to the window if the content size of scroll view is less than window size. I spent a day to fix this problem but of no use...
I am attaching the snap..

The black color is my window of size(320*480) if i pinch the image has gone smaller than the window size(highlighted image) If i stop pinching at this time It will fit correctly to window. But i don't want my imageView to become smaller than window while pinching how to accomplish this?
Thanks,

A: You may want to look at the minimumZoomScale and maximumZoomScale properties of UIScrollView (Reference here)

A: I adding these condintions in my delegate to fix the problem...
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView.zoomScale < minimumScale)
    {
        [scrollView setZoomScale:minimumScale];
    }
    else if(scrollView.zoomScale > 1)
    {
        [scrollView setZoomScale:1];
    }
}


text:
Q: ng-repeat filter by function I'm trying to use a filter on my ng-repeat that is a function that has a parameter passed in, however the filter doesn't seem to work.
This is the filter function that i am using. It compares 2 arrays to see what matches in each then should return true or false.
$scope.ifinfav1 = function(f){
  return e.indexOf(f) !== -1;
};

This is my HTML where the filter is being used.
<ion-view view-title="Favourites">
    <ion-content>
        <ion-list>
        <ion-item id="fav" class="item-icon-right" collection-repeat="office in offices|filter:ifinfav1(office.id)" ng-controller="ModalCtrl" ng-click="openModal(office.id); lastview(office.id);">

{{office.id}}

{{office.LocAddressLine1 + ", " + office.LocAddressLine2 + ", " + office.LocCity + ", " + office.LocCountryDescription + ", " + office.LocZipPostalCode}}

        </ion-item>
        </ion-list>
    </ion-content>
</ion-view>

A: You can not choose what arguments are passed to the function you use as a predicate to your filter.
That is, you can not do:

You can only specify the function itself, not the arguments that are gonna be passed to it when invoked. Thus, only the following is valid:

As specified in AngularJS's documentation for filter (link):

The function is called for each element of the array, with the element, its index, and the entire array itself as arguments.

What's interesting here for you is the element itself, the first argument your function is being passed. You simply have to update it to work with your office objects instead of their ids.
For example:
$scope.ifinfav1 = function(office){
  return e.indexOf(office.id) !== -1;
};

... would do wonders!
Here's a link to a working JSFiddle illustrating my suggestion with sample data.


text:
Q: Using range slider to change div height Seen examples using the range input to control rotation of a div with javascript, but cant see how to change it to other properties such as height and opacity. Here is an example:
function rotate(value)
{
x=document.getElementById('div1')
x.style.webkitTransform="rotate(" + value + "deg)";
}

<input type="range" min="0" max="360" value="0" onchange="rotate(this.value)">

Thanks for any help.

A:

<input type="range" min="0" value="0" onchange="divHeight(this.value)">

A: For a more generalized solution, you can create a generic setStyleOn method. jsFiddle
JS:
function setStyleOn(rule, targetId, value) {
    x = document.getElementById(targetId);
    x.style[rule] = value;
}

HTML:
Rotation
<input type="range" min="0" max="360" value="0"
    onchange="setStyleOn('webkitTransform', 'div1', 'rotate(' + this.value + 'deg')">
Opacity
<input type='range' min='0' max='1.0' value='1.0' step='0.1'
    onchange="setStyleOn('opacity', 'div1', this.value)" />
Height
<input type='range' min='0' max='100' value='10' step='1'
    onchange="setStyleOn('height', 'div1', this.value + 'em')" />
Width
<input type='range' min='0' max='100' value='10' step='1'
    onchange="setStyleOn('width', 'div1', this.value + 'em')" />

A: There are many functions explained for example on this site.
For changing height: you can use scale(), for moving position: translate(), for skewing shape: skew() etc...
For opacity, use opacity property.


text:
Q: Apply a function of a column in dataframe that uses the values of each row as input I am trying to apply a function that returns as input a list of the businesstypes from api.gov. To build the url it uses the duns number from a pandas dataframe.
import pandas as pd
from requests.compat import urljoin, quote_plus

def get_business_types(c):
    base_url = 'https://api.data.gov/sam/v1/registrations/'
    duns = c['duns_normal']
    final_url = base_url + duns + '0000'
    request = requests.get(final_url, params=params)
    data = request.json()
    result  = data['sam_data']['registration']['businessTypes']
    return result

duns['business_types'] =duns['duns_normal'].apply(get_business_types)

I am kind of unclear on the line duns = c['duns_normal'] is this correct? How do I get the duns number so I can build the url?

A: when you are using apply on a column, it passes one value at a time. So the below would suffice.
import pandas as pd
from requests.compat import urljoin, quote_plus

def get_business_types(c):
    print(c)
    base_url = 'https://api.data.gov/sam/v1/registrations/'
    #duns = c['duns_normal']
    final_url = base_url + str(c) + '0000'
    request = requests.get(final_url, params=params)
    data = request.json()
    result  = data['sam_data']['registration']['businessTypes']
    return result

duns['business_types'] =duns['duns_normal'].apply(get_business_types)


text:
Q: Invoke a command on AWS EC2 instance via Google Sheets I currently use a great Node package called gsheets to convert Google Sheets to JSON. This is done via the Amazon CLI using a command like below:
gsheets --key=1iOqNjB-mI15ZLly_9lqn1hCa6MinqPc_71RoKVyCFZs

The problem being I have to go into Amazon EC2 CLI every time to get the latest feed to my app after changes to the spreadsheet.
How can I invoke a CLI command from within Google Sheets, perhaps via a webhook within a Google App Script or triggering a Lambda function?
Struggling to find a solution to this


text:
Q: How to get file extension from a uri of Drupal 7 I have file uri {s3://video-seven-test/file_name.mp4} how do I get the extension from this uri?

A: See http://php.net/manual/en/function.parse-url.php to parse the URL to get the proper path and http://php.net/pathinfo to get the extension from the path

A: $file = file_load($fid);
$path = drupal_realpath($file->uri);
$parts = pathinfo($path);
$extension = $parts['extension'];

thanks to nmc


text:
Q: Linq Join Null Reference My query is as follows:
(from c in countries
 join r in Db.PaymentRates_VisaImmigrationPermit on c.CountryId equals r.HomeCountryId into countryRates
 from legalRate in countryRates.DefaultIfEmpty()
 join hostC in Db.Countries on legalRate.HostCountryId equals hostC.Id
 select new [...]

I get a null reference exception on this line:
join hostC in Db.Countries on legalRate.HostCountryId equals hostC.Id

... Which is obviously caused by this line:
from legalRate in countryRates.DefaultIfEmpty()

How can I do the join only if the legalRate isn't null; so as to get the data I want without incurring a null reference exception?
Similar question: Error in LINQ Left JOIN

A: You can set the default value of your legalRate using the DefaultIfEmpty constructor:
 from legalRate in
     countryRates.DefaultIfEmpty(new CountryRate { HostCountryId = int.MaxValue })


text:
Q: Add a line break after each element is cloned $('.footnote').clone().appendTo('#allfootnotes').append('
');

I have a bunch of .footnote elements all through the page, at the bottom of the page I want to list all of the footnotes on the page. So each footnote will be cloned to #allfootnotes. I'm trying to place a line break after each .footnote in the #allfootnotes element, so they're not all jumbled together.
How would I apply the line break after each .footnote once it's been cloned to #allfootnotes?
And is this the best way to do it? In each .footnote there's 2 span tags, one for the title, and one for the footnote content(don't know if that matters or not).

A: It sounds like you could use CSS to do this
#allfootnotes .footnote {
  margin-bottom: 10px;
}

Depending on your situation you may need to make .footnote a block level element with display: block;

A: DEMO
$('.footnote').clone().appendTo('#allfootnotes').after('
');

If you use XHTML than it should be

A: var allFootNotes = $('#allfootnotes');
$('.footnote').each(function(){
     $(this).clone().add('
').appendTo(allFootNotes);
});

If there are as many foot notes as you say cacheing your $('#allfootnotes') will decrease load on the browser.
Hope this helps

A: $('.footnote').each(function() {
    $(this).clone().add('
').appendTo('#allfootnotes');
});

EDIT Please see roXon's answer. It's way cleaner than iterating over footnotes yourself.


text:
Q: Change version of product I have a very basic project setup without sub-modules or anything. Just a pom.xml with nothing fancy:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.acme.product</groupId>
    <artifactId>org.acme.product</artifactId>
    <version>0.0.9</version>
    <packaging>eclipse-repository</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.eclipse.tycho</groupId>
                <artifactId>tycho-maven-plugin</artifactId>
                <version>0.26.0</version>
                <extensions>true</extensions>
            </plugin>

            <plugin>
                <groupId>org.eclipse.tycho</groupId>
                <artifactId>target-platform-configuration</artifactId>
                <version>0.26.0</version>
                <configuration>
                    <resolver>p2</resolver>
                    <target>
                        <artifact>
                            <groupId>org.acme.product</groupId>
                            <artifactId>org.acme.product</artifactId>
                            <version>${project.version}</version>
                            <classifier>platform</classifier>
                        </artifact>
                    </target>
                    <ignoreTychoRepositories>true</ignoreTychoRepositories>
                    <environments>
                        <environment>
                            <os>win32</os>
                            <ws>win32</ws>
                            <arch>x86</arch>
                        </environment>
                    </environments>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Of course there is a target platform named platform.target with the feature org.eclipse.equinox.executable.feature.group. Finally there is a (empty) product with the same ID and version.
Now I want to use Tycho to update this version. It's only two files, I know. Still.
mvn org.eclipse.tycho:tycho-versions-plugin:set-version -DnewVersion=1.0.0

The pom.xml will get updated, but the product not. The same thing works with plug-ins and features, I can't figure out why it won't work with products, too.
Can somebody help to change the product's version?

A: Check if your pom.xml version and product version are the same.

The versions-plugin will only update the versions in product files if the old version matches the version in the eclipse-repository POM.
  Product files whose versions are (intentionally) different from the POM version are not updated. This is the same as with modules: modules which don't have the same version as the root POM are not updated.

Refer to this bug report


text:
Q: Injecting variables into a url I'm using make.com to create a url that will pass a number of variables to a airtable form. An example url looks like
https://airtable.com/shrMOfdfsldWOX6FOpphJ?prefill_ContactID={{1.id}}&prefill_Startup={{6.`Company Name`}}&prefill_Areas+of+Focus={{15.array[].Name}}
Depending on the person in the DB, a contact may have a different number of areas of focus.
I'm not sure how to construct a mechanism to go through the array and add "&prefill_areas+of+focus=" before each area the contact has.
Any help would be greatly appreciated.


text:
Q: Discord.JS | function or way to delete an embed from a user message? So I am making a bot using the Discord.JS API. The bot basically plays the audio of a given youtube link (ytdl-core). Every time I type a link of what I want to play, the embed of the youtube link shows up. I know there are ways to disable embeds on the text channels, but I don't want to have to do that. Is there a way to delete just the embed?

A: There is actually. If you wrap your link in less than and greater than signs (<>), an embed won't appear.


text:
Q: How to interpret results from the sp_spaceused command with regards to indexes If I need to review indexes of more than 2000 tables, where do I start given the information from the sp_spaceused command?
I'm investigating Indexes on tables, but am not quite sure what to make of the results for the IndexSize when I exec the sp_spaceused stored procedure in SQL.
Firstly, can I use the ratio between IndexSize and DataSize to make a call on wheter or not the indexes are optimal? For example, if my DataSize for a table is 31 261 768KB and the IndexSize is 41 682 120KB, I divide indexSize/DataSize *100 and get a ratio of 133.  Is what I'm doing correct?
If it is correct, is an IndexSize-ratio of more than 100% bad?
What would a good ratio then be?
Thanks,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I  need to add a bit more information.
The application is Microsoft Dynamics Ax 4.0.  Although developers can add new indexes, system indexes can't be deleted.
We are currently in a situation where there are allot of custom-indexes which does not add any value (indexes on blank fields, indexes on amount fields, etc.). I am investigating those as part of a code cleanup process.
But because there are thousands of tables to work through I need a starting point.  My first concern is identifying the custom-indexes that does not add value, and for this I thought about using the sp_spaceused procedure.

A: Checking the ratio of index size to data size is a terrible metric to use for this.
The only thing that should drive index creation or modification is performance.  This will depend in large part on the activity in the table (a lot of SELECTs, a lot of INSERTS/UPDATEs, some combination?) and the makeup of the table.
Unfortunately there is no easy answer to this.  Indexing is one of the most complicated aspects of DB design.
I recommend you do some reading on this.
Check out Kimberly Tripp's blog here.
She worked for MS for quite a while and her husband (Paul Randall) wrote the DBCC procedures in SQL Server 2005.
Gail Shaw also has some good articles in her blog.

A: Performance Analyzer for Microsoft Dynamics can be used to analyze expensive and long running queries, missing clustered indexes, incorrect and missing indexes, hidden clustered index scans, etc. in AX DB.
A way to eliminate the amount of unnecessary indexes is to search for indexes that are a left key subset of another index on the same table. Unless the subset key is unique, its usefulness is subsumed of the superset key. To get a list of such indexes you can run the following query:
SELECT *
FROM INDEX_STATS_CURR_VW O
WHERE INDEX_DESCRIPTION NOT LIKE '%UNIQUE%'
AND EXISTS
(
    SELECT * FROM INDEX_STATS_VW I
    WHERE I.RUN_NAME = O.RUN_NAME
    AND I.TABLE_NAME = O.TABLE_NAME
    AND I.INDEX_KEYS <> O.INDEX_KEYS
    AND I.INDEX_KEYS LIKE O.INDEX_KEYS + ',%'
    AND O.USER_SEEKS = 0
)
ORDER BY TABLE_NAME, INDEX_KEYS

To get an overview of all indexes that haven't been used during the complete monitoring period you could run the following query:
SELECT TABLE_NAME,
    INDEX_NAME,
    INDEX_DESCRIPTION,
    INDEX_KEYS,
    INCLUDED_COLUMNS,
    SUM(USER_SEEKS) AS USER_SEEKS,
    SUM(USER_SCANS) AS USER_SCANS,
    SUM(USER_LOOKUPS) AS USER_LOOKUPS,
    SUM(USER_UPDATES) AS USER_UPDATES
FROM INDEX_STATS_VW
WHERE INDEX_DESCRIPTION NOT LIKE '%UNIQUE%'
GROUP BY TABLE_NAME, INDEX_NAME, INDEX_DESCRIPTION, INDEX_KEYS, INCLUDED_COLUMNS
HAVING SUM(USER_SEEKS) = 0
AND SUM(USER_SCANS) = 0
AND SUM(USER_LOOKUPS) = 0
ORDER BY 9 DESC

You could also identify queries that use an index seek to filter data:
SELECT TOP 100 * FROM HIDDEN_SCANS_CURR_VW
ORDER BY TOTAL_ELAPSED_TIME DESC

The following would display 10 most expensive queries ordered by average logical reads from a SQL Server DMV perspective:
SELECT TOP 10
    SQL_TEXT,
    QUERY_PLAN,
    TOTAL_ELAPSED_TIME,
    AVG_ELAPSED_TIME,
    MAX_ELAPSED_TIME,
    AVG_LOGICAL_READS,
    EXECUTION_COUNT
FROM QUERY_STATS_CURR_VW
ORDER BY AVG_LOGICAL_READS DESC

You'd also need to have a look at other parameters like execution count (how many times queries were executed).
If you wanted to have an overview of the AX queries running longer than 1000 ms you could run the following query:
SELECT CONVERT(nvarchar,CREATED_DATETIME,101) AS CREATED_DATE,
    DATEPART (hh, CREATED_DATETIME) AS HOUR_OF_DAY,
    COUNT (CREATED_DATETIME) AS EXECUTION_COUNT,
    SUM (SQL_DURATION) AS TOTAL_DURATION,
    AVG (SQL_DURATION) AS AVERAGE_DURATION
FROM AX_SQLTRACE_VW
WHERE SQL_DURATION > 1000 and CREATED_DATETIME > '04/01/2011'
GROUP BY CONVERT(nvarchar, CREATED_DATETIME, 101), DATEPART (hh, CREATED_DATETIME)
ORDER BY CREATED_DATE, HOUR_OF_DAY

Hope that helps.

A: I'm not sure what you are trying to achieve. You would optimise a query, not an index. But too many indexes can hinder write performance. I recommend that you look at the DMV (Dynamic Managment Views) that are provided in 2005.
For example select * from sys.dm_index_usage_stats will help identify indexes which are not used.
There are a list of DMVs which are related to indexes on BOL.
http://msdn.microsoft.com/en-us/library/ms187974%28v=SQL.90%29.aspx


text:
Q: strcmp() returning -1 for different strings <?php
$html = file_get_contents("https://www.casa.gov.au/rpa-operator-certificate-holders");
$pokemon_doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html)){

    $pokemon_doc->loadHTML($html);
    libxml_clear_errors();
    $pokemon_xpath  = new DOMXPath($pokemon_doc);
    $pokemon_row    = $pokemon_xpath->query('//tr');

    if($pokemon_row->length > 0){
        $s4 = "4 ONE 4 REAL ESTATE PTY LTD ";
        $s5 = ($pokemon_row[2]->firstChild->nodeValue);
        echo strcmp($s4,$s5);
    }

}
?>

From the above code I am  trying to compare string from the table of this site("https://www.casa.gov.au/rpa-operator-certificate-holders") but I didn't get output as 0 when I am using strcmp(), instead I am getting output as -1

A: The problem is the extra whitespace around the strings you are comparing.  If you add
echo ">".$s4."<>".$s5."<";

you get
>4 ONE 4 REAL ESTATE PTY LTD <>
            4 ONE 4 REAL ESTATE PTY LTD          <

You could easily change the compare to...
echo strcmp(trim($s4),trim($s5));


text:
Q: Preferred recoverable method to store passwords in database I want to store some passwords on my database at server.
The passwords should be recoverable, since I want to use them for a third-party api which needs the password. (So I can't use one-way methods like md5...)
What is the best method to save passwords in database? Isn't there any better way than storing plain text?

A: AES is cryptographically sound and probably the most common encryption (as opposed to hashing) mechanism selected for new applications.
Take care to generate a random initialization vector (IV) for each password that you encrypt, and store the Key and the IV separately from the encrypted password bytes.
To understand differences between AES and Rijndael check out
http://blogs.msdn.com/b/shawnfa/archive/2006/10/09/the-differences-between-rijndael-and-aes.aspx

there are some differences between Rijndael and the official FIPS-197 specification for AES

You should use a unique IV per user. However, storing the key-per-user makes for a complex key management scenario. I would suggest one key for the application and an IV per user.
The IV can be saved alongside the ciphertext. The key should be stored outside of the database.
You could store the key, encrypted, in web.config. See this.


text:
Q: python subprocess with failed command return code 0 I execute the following code in both windows cmd and ubuntu bash:
python -c "import xxx"

Error messages output. And when I run:
echo $? / echo %errorlevel%

The value is 1.
When I do the same task in python script with subprocess as follows:
cmdlst = ['python', '-c', '"import xxx"']
proc = subprocess.Popen(cmdlst)
retcode = proc.wait()

The retcode is 0.
What is the problem and how can I get the correct return code of the command
run within a subprocess.
Thanks in advance.

A: Running the shell command (equivalent to your given subprocess.Popen() call if we disregard the use of "smart quotes")
'python' '-c' '"import xxx"'

correctly exits with status 0, whether or not a module named xxx exists.
This is because "import xxx" is a string, and evaluating a string does not throw an exception. You'd get the exact same behavior from python -c '"hello world"', or any other string.

If you really want to try executing the code import xxx, then you need to remove the extra quotes:
subprocess.Popen(['python', '-c', 'import xxx']).wait()

...will properly return 1 (if no xxx module exists).


text:
Q: How do I wrap this code as a method? public class CustomFont
{
    public string ChangeFont(string font, string target)
    {
        PrivateFontCollection pfc = new PrivateFontCollection();
        int fontLength = Properties.Resources.font.Length;
        byte[] fontdata = Properties.Resources.font;
        System.IntPtr data = Marshal.AllocCoTaskMem(fontLength);
        Marshal.Copy(fontdata, 0, data, fontLength);
        pfc.AddMemoryFont(data, fontLength);
        target.Font = new Font(pfc.Families[0], target.Font.Size);
    }
}

I tried this but errors were shown that 'App.Properties.Resources' does not contain a definition for 'font'.

Okay so I edited the code following everybody's answers and it is almost working now. The problem is, what method should I use for byte[]?
public void ChangeFont(string font, TextBox target)
        {
            PrivateFontCollection pfc = new PrivateFontCollection();
            int fontLength = Properties.Resources.ResourceManager.GetString(font).Length;
            byte[] fontdata = Properties.Resources.font;
            System.IntPtr data = Marshal.AllocCoTaskMem(fontLength);
            Marshal.Copy(fontdata, 0, data, fontLength);
            pfc.AddMemoryFont(data, fontLength);
            target.Font = new Font(pfc.Families[0], target.Font.Size);
        }

A: You are trying to get a string from your resources by name.
You can't write it like
Properties.Resources.font;

You have to use the ResourceManager
string myString = Properties.Resources.ResourceManager.GetString(font);

And then you can do whatever you want with that string.
But your method has a lot of other things why you will get following problems; for example no return value.


text:
Q: Two by two matching between dataframes in r I need to combine two data frames (df1 and df2) by matching up two site columns of each data frame to produce a third data frame (df3).
df1 = data.frame(Site.1=c("A","A","B"),
                 Site.2=c("B","C","C"),
                 Score1=c(60,70,80))
df1

 Site.1 Site.2 Score1
1      A      B     60
2      A      C     70
3      B      C     80

df2 = data.frame(Site.1=c("B","A","A"),
                 Site.2=c("C","B","C"),
                 Score2=c(10,20,30))
df2

  Site.1 Site.2 Score2
1      B      C     10
2      A      B     20
3      A      C     30

df3 = data.frame(Site.1=c("A","A","B"),
                 Site.2=c("B","C","C"),
                 Score1=c(60,70,80),
                 Score2=c(20,30,10))
df3

  Site.1 Site.2 Score1 Score2
1      A      B     60     20
2      A      C     70     30
3      B      C     80     10

A: You want the merge function.  Since your column names that you want to match on already have the same name you don't even need to do anything special.  If that wasn't the case you would want to look into the by.x and by.y parameters that merge takes.
df1 = data.frame(Site.1=c("A","A","B"),Site.2=c("B","C","C"),Score1=c(60,70,80))
df2 = data.frame(Site.1=c("B","A","A"),Site.2=c("C","B","C"), Score2=c(10,20,30))
df3 = data.frame(Site.1=c("A","A","B"),Site.2=c("B","C","C"), Score1=c(60,70,80),Score2=c(20,30,10))
df3

# Merge gives you what you want
merge(df1, df2)

A: dplyr may be helpful here.
library(dplyr)

df1 = data.frame(Site.1 = c("A", "A", "B"),
                 Site.2 = c("B", "C", "C"),
                 Score1 = c(60, 70, 80))

df2 = data.frame(Site.1 = c("B", "A", "A"),
                 Site.2 = c("C", "B", "C"),
                 Score2 = c(10, 20, 30))

inner_join(df1, df2)


text:
Q: Urgent !!! Formulae unable to run I am trying to add the formula in the workflow mentioned below:
AND( ISCHANGED (Account.Name),OR( ( Account.Type  =  'Client')))

But it shows this error:

The ISCHANGED function cannot reference the Account.Name field

Basically I trying to do here is when I change the Account Name field on Contact and Account Type field on account is "Client", the Contact Owner should get an email alert.

The account name is a lookup value here. Can you suggest me a correct formula?

A: the reason this isn't working on a contact workflow is because the changed fields live on another object - the account.
the workaround would be to have a text field, that would be hidden, on the contact record for the account name that would be updated by workflow every time the record is edited.  mark this field update to trigger other workflow rules.  then you can create the workflow you're trying to make with the ISCHANGED() and PRIORVALUE() functions on a field on the contact record.


text:
Q: Modifying contents of a list inside a dictionary I have a list of "prof" objects called profList and then a dictionary (called collabDict) looks like this:
{17 : ['john', 'jim', 'fred'], 18 : ['tim', 'will', 'alex']}

I want to go through collabDict and change certain names from strings to the afore-mentioned "Prof" objects in profList, but only if a condition is met. The following code is my attempt but it does not change the values as intended
for a in profList :
    for key in collabDict :
        for b in collabDict.get(key,None) :
            if (some condition) :
                b = a

Any insight would be very helpful, thanks!

A: Having your dictionary:
>>> dct = {17 : ['john', 'jim', 'fred'], 18 : ['tim', 'will', 'alex']}

we define function, testing, if given name is in category of "prof" or not:
>>> isProf = lambda name: "i" in name

and using dict comprehension (available since Python 2.7) we change the names, if they are elegible
to being "Prof":
>>> {key: ["Prof" + name if isProf(name) else name for name in names] for key, names in dct.items()}
{17: ['john', 'Profjim', 'fred'], 18: ['Proftim', 'Profwill', 'alex']}

Disadvantage of this solution is, it rebuilds complete dictionary for each run. You shall know, if
this is acceptable or not.
Other solutions can change just the names which are to be changed this way:
isProf = lambda name: "i" in name
dct = {17 : ['john', 'jim', 'fred'], 18 : ['tim', 'will', 'alex']}
for num in dct:
    for i, name in enumerate(dct[num]):
        if isProf(name):
            dct[num][i] += "Prof"
print dct

A: You need to set the new value by using the dict:
`collabDict[key] = a`

You are just setting b = a, that is not setting the value in collabDict
If you want a value in the list changed:
collabDict={17 : ['john', 'jim', 'fred'], 18 : ['tim', 'will', 'alex']}
ind = collabDict[17].index("john")
collabDict[17][ind]="b"

In your code something like:
for a in profList :
    for key in collabDict :
        for ind,b in enumerate(collabDict[key]) :
            if (some condition) :
                collabDict[key][ind] = a # change element at index to a


text:
Q: How to stream video frames in C# I have got some event where I am getting bitmap of webcam.
How do I can stream it to some local port in a simplest way?
using WpfMultimedia;
using WpfMultimedia.Webcam;

var _webCam = new VideoCapture(DeviceManager.GetVideoInputDevices().First(), null);
_webCam.CaptureFrame += OnFrameCaptured;
_webCam.Start();

...

private void OnFrameCaptured(object sender, CaptureFrameEventArgs e)
{
    //latest BitmapImage from camera is in e.Frame
    BitmapImage _currentFrame = e.Frame
    .... Stream it to http://localhost:9797 ?
}

A: Maybe you can start by converting the BitmapImage to a "stremeable" type of data.
byte[] Data;
JpegBitmapEncoder Encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream MemStream = new MemoryStream())
{
Encoder.Save(ms);
Data = MemStream.ToArray();
}

Maybe you can use a different encoder for performance.
Then you should use UDP (TCP if the data is small enough, and speed is not a requirement) to send this frames and decode them, there you can create a video.
But probably there are some libraries already created for video streaming and you don't have to code that yourself.


text:
Q: jquery post file and button value and get response from script I am trying to post file and button value and process it in php.
Issue is in my php script ha2e.php condition if (isset($_FILES['file'])) {} always goes false
html:

  Arabic to English HTML

            <form method="post" enctype="multipart/form-data" target="iframe4" id = "htmla2e">
            *.XLSX <input type="file" name="file"  />  <input type="submit" id="submit4" name="submit4" value="HTML Arabic to English" />
            </form>

jquery:
$(document).ready(function() {

   var extra_data = "This is more stuff to send";
   var Bvalue = $(this).attr("value");

   $('#submit4').click(function() {
  $.ajax({
     type: "POST",
     url: "he2a.php",
     data: {'form': $("#htmla2e").serialize(), 'other': extra_data, 'submit4': Bvalue},
     success: function(msg) {
        alert("Form Submitted: " + msg);
     }
  });

   });

});

php:
    <?php

        if (isset($_FILES['file'])) {
            header('Content-Type: text/html; charset=UTF-8');
            echo '<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />';
            require_once "simplexlsx.class.php";
            require '../../Arabic.php';
            $Arabic = new I18N_Arabic('Transliteration');
            $xlsx = new SimpleXLSX( $_FILES['file']['tmp_name'] );
            echo "df";
            echo '
';
            $eng = array();
            list($cols,) = $xlsx->dimension();
            foreach( $xlsx->rows() as $k => $r) {
        //      if ($k == 0) continue; // skip first row
                echo '
';
                for( $i = 0; $i < $cols; $i++)
                {
                    if ($_POST['submit3'] == 'HTML English to Arabic')
                    {
                        $temp =  $Arabic->en2ar($r[$i]);
                }
                    else if ($_POST['submit4'] == 'HTML Arabic to Englis')
                    {
                        $temp =  $Arabic->ar2en($r[$i]);
                    }
                    else
                        continue;
                    echo ''.( (isset($r[$i])) ? $temp : ' ' ).'	';
                }
                echo '
';
            }
            echo '
';
        }
        ?>

A: when you use the ajax request, of course you the $_FILES is empty.
$('#submit4').click(function() {
  $.ajax({
     type: "POST",
     url: "he2a.php",
     data: {'form': $("#htmla2e").serialize(), 'other': extra_data, 'submit4': Bvalue},
     success: function(msg) {
        alert("Form Submitted: " + msg);
     }
 });

you should assgin the form action to the url you want post data to, for eample ha2e.php, fllow is the code.
<form method="post" enctype="multipart/form-data" target="iframe4" id = "htmla2e" action="ha2e.php">
    *.XLSX <input type="file" name="file"  />  <input type="submit" id="submit4" name="submit4" value="HTML Arabic to English" />
</form>

at last we use chrome developer tools we will see we post the file to the action ha2e.php, if action is empty, the default current url page.

A: You may want to see the answers on this post or on this - uploading files with AJAX is not working with the generic method you are using.


text:
Q: Unknown class in Interface Builder file I created a fairly simple iPhone app.  Then figured I'd create an iPad version (Universal) of the app.  Tried using the 'upgrade' option and that didn't work-out.  So I created a separate universal app and copied the xib files into my project.  That didn't work out either, so I deleted the xib files (and their associated .m & .h files.
Now, when I run the iPhone version it gives me the Unknown class iPadSample1AppDelegate in Interface Builder file. error and UISplitViewController is only supported when running under UIUserInterfaceIdiomPad and then it exits.  So, I restored to the snap-shot I took before embarking on the iPad adventure... I get the same error.  I've tried the XCode search and Spotlight search.  There is no reference to that class or the UISplitViewController anywhere in my project, but for some reason XCode thinks that there is.
Is there some way to remove a reference that doesn't exist? LOL
Update:
It may have something to do with my XCode environment being jacked.  After finding a few other posts on here, I tried a Clean All / Build / Touch and when I did the touch, I got the following error in XCode:

Uncaught Exception:
-[XCBuildLogWarningMessage setFileLocations:]: unrecognized selector sent to instance 0x2014dd0a0

Anyway to reinstall XCode without messing up everything else?

A: I did some research and found out that
for my case
I just need to right click to complaining file in the Project Navigator.
Choose View/Utilities/Show File Inspector. And for some reason the Target Membership was not selected.
That's why the linker says that it doesn't know the existence of the class.
I just ticked to choose it and everything works like a charm.

A: Right click on Storyboard --> Open As --> Source Code
Find your unknown class name in the storyboard source file.  It may be because you have accidentally assigned a custom class name for one of your UIView subclass'.

A: It turns out the bits on the iPhone simulator were out of sync with XCode.  I did a 'Reset Content and Settings' and everything works :)  Who knew?

A: If you go to Build Phases within your targets you will see Compile Sources. Make sure each of the m files you need are listed. If not, just add it here and the warning should go away.

A: I had this same problem but it was not solved by the solution above. I ended up getting it working by removing the "Main storyboard file base name (iPad)" entry from my info.plist file.

A: what fixed it for me was t smply "delete" the ap in the simulator, and rebuild again.
Probably this class was still rerenced in local settings in the iphone simulator.

A: In my case this error appeared after refactoring class name. Somehow the classname not changed in the .xib file. I opened this xib-file in Textedit and replace all OldClassVC to NewClassVC. Then I saved xib-file and Cleaned project before new build. Project runs well.

A: In case you are using Cocoa pods, drag the .framework/.a files to your projects' "link binary with libraries" section.


text:
Q: ¿Cómo puedo pasar a un jPanel datos de un JSON en java y que este panel se vaya repitiendo con cada dato? Tengo el siguiente archivo json atreves de una API
{
    "count": 51,
    "next": "https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4&page=2",
    "previous": null,
    "results": [
        {
            "id": 4,
            "name": "PC",
            "slug": "pc",
            "games_count": 446264,
            "image_background": "https://media.rawg.io/media/games/328/3283617cb7d75d67257fc58339188742.jpg",
            "image": null,
            "year_start": null,
            "year_end": null,
            "games": [
                {
                    "id": 3498,
                    "slug": "grand-theft-auto-v",
                    "name": "Grand Theft Auto V",
                    "added": 17411
                },
                {
                    "id": 3328,
                    "slug": "the-witcher-3-wild-hunt",
                    "name": "The Witcher 3: Wild Hunt",
                    "added": 16147
                },
                {
                    "id": 4200,
                    "slug": "portal-2",
                    "name": "Portal 2",
                    "added": 15234
                },
                {
                    "id": 5286,
                    "slug": "tomb-raider",
                    "name": "Tomb Raider (2013)",
                    "added": 13638
                },
                {
                    "id": 5679,
                    "slug": "the-elder-scrolls-v-skyrim",
                    "name": "The Elder Scrolls V: Skyrim",
                    "added": 13213
                },
                {
                    "id": 4291,
                    "slug": "counter-strike-global-offensive",
                    "name": "Counter-Strike: Global Offensive",
                    "added": 13123
                }
            ]
        },
        {
            "id": 187,
            "name": "PlayStation 5",
            "slug": "playstation5",
            "games_count": 567,
            "image_background": "https://media.rawg.io/media/games/f87/f87457e8347484033cb34cde6101d08d.jpg",
            "image": null,
            "year_start": 2020,
            "year_end": null,
            "games": [
                {
                    "id": 3498,
                    "slug": "grand-theft-auto-v",
                    "name": "Grand Theft Auto V",
                    "added": 17411
                },
                {
                    "id": 3328,
                    "slug": "the-witcher-3-wild-hunt",
                    "name": "The Witcher 3: Wild Hunt",
                    "added": 16147
                },
                {
                    "id": 32,
                    "slug": "destiny-2",
                    "name": "Destiny 2",
                    "added": 10789
                },
                {
                    "id": 58175,
                    "slug": "god-of-war-2",
                    "name": "God of War",
                    "added": 10552
                },
                {
                    "id": 766,
                    "slug": "warframe",
                    "name": "Warframe",
                    "added": 9746
                },
                {
                    "id": 41494,
                    "slug": "cyberpunk-2077",
                    "name": "Cyberpunk 2077",
                    "added": 9197
                }
            ]
        }

El caso es que quiero que me muestre dentro de un jscrollpanel, unos paneles en los que me diga el name de si es PC o PlayStation 5 y el name del juego que sea, esto que se vaya rapitiendo en el scrollpanel y que muestre un panel para cada uno.
Aquí tengo el método en el que lo hice con una conexion a base de datos, creandole su constructor, el caso es que usando JSON no lo logro sacar:
Método con el que hacia que se repitieran los paneles con distintos dato:
      public ArrayList<Motos>coger_datosmotos(){
         ArrayList<Motos> listaMotos = new ArrayList<>();
           try {
             //Conexion con=new Conexion();

             Connection conn=openConnection();
             PreparedStatement stmt=openConnection().prepareStatement("SELECT * FROM motos");
             ResultSet rs= stmt.executeQuery();
             while(rs.next()){
                 Motos motos= new Motos();
                 motos.setCodigo(rs.getInt("id"));
                 motos.setNombre(rs.getString("nombre"));
                 motos.setMarca(rs.getString("marca"));
                 motos.setCilindrada(rs.getInt("cilindrada"));
                 motos.setPeso(rs.getInt("peso"));
                 motos.setPrecio_moto(rs.getInt("precio_moto"));
                 listaMotos.add(motos);
             }
             closeConnection(conn);

         } catch (SQLException ex) {
             Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
         }
         return listaMotos;
      }


text:
Q: Can't connect to MongoDB remotely (even though bindIp is not set) I'm trying to solve this one for few hours now and I have no idea why it's not working. I set up mongod with
mongod --dbpath /some/path

so that bind_ip is not set (mongod is listening on all interfaces).
I set all iptables' policies to ACCEPT and flushed all rules (so I can be sure that iptables doesn't block anything) - iptables -S:
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N DOCKER
-N DOCKER-ISOLATION
-N FORWARD_IN_ZONES
-N FORWARD_IN_ZONES_SOURCE
-N FORWARD_OUT_ZONES
-N FORWARD_OUT_ZONES_SOURCE
-N FORWARD_direct
-N FWDI_public
-N FWDI_public_allow
-N FWDI_public_deny
-N FWDI_public_log
-N FWDO_public
-N FWDO_public_allow
-N FWDO_public_deny
-N FWDO_public_log
-N INPUT_ZONES
-N INPUT_ZONES_SOURCE
-N INPUT_direct
-N IN_public
-N IN_public_allow
-N IN_public_deny
-N IN_public_log
-N OUTPUT_direct

I double and triple checked my server's public ip and it's 100% correct. But no matter what I do, when I try to connect to mongo from my local machine with:
mongo <servers_ip>

I get
MongoDB shell version: 2.6.11
connecting to: servers_ip/test
2017-08-08T18:18:30.689+0200 warning: Failed to connect to servers_ip:27017, reason: errno:113 No route to host
2017-08-08T18:18:30.690+0200 Error: couldn't connect to server servers_ip:27017 (servers_ip), connection attempt failed at src/mongo/shell/mongo.js:148
exception: connect failed

Does anyone have any idea what else can I do to make this work?
EDIT:
Output of netstat -tanp | grep mongod:
tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      4302/mongod

A: Ok, so it seems like from my side everything was fine. It was my VPS provider - OVH - who blocked the port and I couldn't do anything about this, but change the mongod port to some lower value. Thanks @nadavvadan for the suggestion.

A: *

*Set up your user

you need to set a user and password for your database to get access
use your_db
  db.createUser({ user: 'user', pwd: 'password', roles: [{ role: 'readWrite', db:'yourdb'}] })

*Enable auth and open MongoDB access up to all IPs

sudo nano /etc/mongod.conf
`# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0
security:
  authorization: 'enabled'`

*Open port 27017
Make a new Custom TCP on port 27017, Source: Anywhere, 0.0.0.0/0

*Last step: restart mongo daemon (mongod)
sudo service mongod restart

*Logging in using the mongo shell on your laptop
mongo -u user -p password serverip/your_db


text:
Q: Copy all files of a particular extension into a separate folder, retaining folder structure (recursive) Simple task: I have a nested folder of arbitrary code, containing CSS files in any particular folder. I want a command that copies over those files (and only those files) into a new folder, reproducing the same folder structure that they were in.
Either a shell command or node command would be fine.
e.g. given this:
src/folder1/file1.css
src/folder1/... other files...
src/folder2/subfolder/file2.css
src/folder2/subfolder/X/Y/Z/file.css
src/folder3/whatever.html
src/folder4/blah.html

the command would generate the following:
dist/folder1/file1.css
dist/folder2/subfolder/file2.css
dist/folder2/subfolder/X/Y/Z/file.css

Any idea?

A: I hope that this helps you.
cd src && find . -name \*\.css -or -name \*\.html | while read src; do srcdir=$(echo "$src" | rev | cut -d'/' -f2- | rev); dstdir="../dist/$srcdir"; [ -d "$dstdir" ] || mkdir -p "$dstdir"; cp "$src" "../dist/$src"; done

A: You can use rsync:
rsync -avm --include '*/' --include '*.css' --exclude '*' src/ dist

*

*-a is archive mode: recurse, preserve attributes, permissions etc

*-m is prune: remove directories not required for a .css path

*-v is verbose logging


text:
Q: Why do I have many more jobs `started` than running or suspended? According to the bqueues manual page:
STARTED
         Number of job slots used by running or
         suspended jobs owned by users or user groups in
         the queue.

According to bqueues, I have 369 jobs started:
$ bqueues -r lotus | egrep '(STARTED|gholl)'
 USER/GROUP   SHARES  PRIORITY  STARTED  RESERVED  CPU_TIME  RUN_TIME   ADJUST
gholl          10       0.006    369        0   2334366.5   723589       0.000

But when I run bjobs, it only shows 24 jobs that are running or suspended:
$ bjobs | egrep '(RUN|SUSP)' | wc -l
24

What explains the discrepancy between 24 jobs running and 369 jobs started?

A: The number in STARTED refers to the number of slots.  One job may take up more than one slot if it uses multiple threads.  For example, if a job is submitted using bsubs with the flag -n 16, then each job will use 16 jobs.  23×16+1=368, so in the example above, user gholl has 23 jobs using 16 slots and 1 job using 1 slot.


text:
Q: C++ Error checking before constructor delegation I have a constructor that creates a matrix from size_t dimensions, I want to add support for int dimensions. However, before passing the ints to the size_t constructor I would like to make sure that they are positive.
 Matrix(vector<double> vals, int rows, int cols )
 \\throw something if rows<= 0 || cols<= 0
:Matrix(vals,static_cast<size_t>(rows), static_cast<size_t>(cols))

Is something like this possible?

A: Pass them through a function,
int enforce_positive(int x)
{
    if (x <= 0) {
        throw something;
    }
    return x;
}

Matrix(vector<double> vals, int rows, int cols )
  : Matrix(vals,
           static_cast<size_t>(enforce_positive(rows)),
           static_cast<size_t>(enforce_positive(cols)))

You can make this a template, of course.
You could also use a "proof type" and make the condition explicit in the prototype. Something like
temolate<typename T>
class Positive
{
public:
    explicit Positive(T x): val(x)
    {
        if (val <= 0) {
            throw something;
        }
    }
    operator T() const { return val; }
private:
    T val;
};

Matrix(const vector<double>& vals,
       Positive<int> rows,
       Positive<int> cols )
  : Matrix(vals,
           static_cast<size_t>(rows),
           static_cast<size_t>(cols))

//...
int x = ...;
int y = ...;
Matrix m(stuff, Positive(x), Positive(y));


text:
Q: Calculating Excel sheets without opening them (openpyxl or xlwt) I made a script that opens a .xls file, writes a few new values in it, then saves the file.
Later, the script opens it again, and wants to find the answers in some cells which contain formulas.
If I call that cell with openpyxl, I get the formula (ie: "=A1*B1").
And if I activate data_only, I get nothing.
Is there a way to let Python calculate the .xls file? (or should I try PyXll?)

A: I realize this question is old, but I ran into the same problem and extensive searching didn't produce an answer.
The solution is in fact quite simple so I will post it here for posterity.
Let's assume you have an xlsx file that you have modified with openpyxl. As Charlie Clark mentioned openpyxl will not calculate the formulas, but if you were to open the file in excel the formulas would be automatically calculated. So all you need to do is open the file and then save it using excel.
To do this you can use the win32com module.
import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Open(r'absolute/path/to/your/file')
# this must be the absolute path (r'C:/abc/def/ghi')
workbook.Save()
workbook.Close()
excel.Quit()

That's it. I've seen all these suggestions to use Pycel or Koala, but that seems like a bit of overkill if all you need to do is tell excel to open and save.
Granted this solution is only for windows.

A: There is actually a project that takes Excel formulas and evaluates them using Python:  Pycel.  Pycel uses Excel itself (via COM) to extract the formulas, so in your case you would skip that part.  The project probably has something useful that you can use, but I can't vouch for its maturity or completeness.  It was not really developed for the general public.
There is also a newer project called Koala which builds on both Pycel and OpenPyXL.
Another approach, if you can't use Excel but you can calculate the results of the formulas yourself (in your Python code), is to write both the value and the formula into a cell (so that when you read the file, you can just pull the value, and not worry about the formula at all).  As of this writing, I haven't found a way to do it in OpenPyXL, but XlsxWriter can do it.  From the documentation:

XlsxWriter doesn't calculate the value of a formula and instead stores the value 0 as the formula result. It then sets a global flag in the XLSX file to say that all formulas and functions should be recalculated when the file is opened. This is the method recommended in the Excel documentation and in general it works fine with spreadsheet applications. However, applications that don't have a facility to calculate formulas, such as Excel Viewer, or some mobile applications will only display the 0 results.

If required, it is also possible to specify the calculated result of the formula using the options value parameter. This is occasionally necessary when working with non-Excel applications that don't calculate the value of the formula. The calculated value is added at the end of the argument list:

worksheet.write_formula('A1', '=2+2', num_format, 4)

With this approach, when it's time to read the value, you would use OpenPyXL's data_only option. (For other people reading this answer: If you use xlrd, then only the value is available anyway.)
Finally, if you do have Excel, then perhaps the most straightforward and reliable thing you can do is automate the opening and resaving of your file in Excel (so that it will calculate and write the values of the formulas for you). xlwings is an easy way to do this from either Windows or Mac.

A: The formula module works for me. For detail please refer to https://pypi.org/project/formulas/
from openpyxl import load_workbook
import formulas

#The variable spreadsheet provides the full path with filename to the excel spreadsheet with unevaluated formulae
fpath = path.basename(spreadsheet)
dirname = path.dirname(spreadsheet)
xl_model = formulas.ExcelModel().loads(fpath).finish()
xl_model.calculate()
xl_model.write(dirpath=dirname)
#Use openpyxl to open the updated excel spreadsheet now
wb = load_workbook(filename=spreadsheet,data_only=True)
ws = wb.active

A: I run into the same problem, and after some time researching I ended up using pyoo ( https://pypi.org/project/pyoo/ ) which is for openoffice/libreoffice so available in all platforms and is more straightforward since communicates natively and doesn't require to save/close the file . I tried several other libraries but found the following problems

*

*xlswings: Only works if you have Excel installed and Windows/MacOS so I couldn't evaluate

*koala : Seems that it's broken, after networkx 2.4 update.

*openpyxl: As pointed out by others, it isn't able to calculate formulas so I was looking into combining it with pycel to get values. I didn 't finally tried because I found pyoo . Openpyxl+pycel might not work as of now, since pycel is also relying on networkx library.

A: No, and in openpyxl there will never be. I think there is a Python library that purports to implements an engine for such formualae which you can use.

A: xlcalculator can do this job. https://github.com/bradbase/xlcalculator
from xlcalculator import ModelCompiler
from xlcalculator import Model
from xlcalculator import Evaluator

filename = r'use_case_01.xlsm'
compiler = ModelCompiler()
new_model = compiler.read_and_parse_archive(filename)
evaluator = Evaluator(new_model)

# First!A2
# value is 0.1
#
# Fourth!A2
# formula is =SUM(First!A2+1)

val1 = evaluator.evaluate('Fourth!A2')
print("value 'evaluated' for Fourth!A2:", val1)

evaluator.set_cell_value('First!A2', 88)
# now First!A2 value is 88
val2 = evaluator.evaluate('Fourth!A2')
print("New value for Fourth!A2 is", val2)

Which results in the following output;
file_name use_case_01.xlsm ignore_sheets []
value 'evaluated' for Fourth!A2: 1.1
New value for Fourth!A2 is 89


text:
Q: EF Core, when updating database I get: "System.Collections.Generic.KeyNotFoundException: The given key '17736' was not present in the dictionary" I am fairly new to .NET and Entity Framework Core, and I am trying to build a simple backend with REST endpoints for querying some items.
I am currently stock with an error that I haven't been able to solve after doing quite some research:
System.Collections.Generic.KeyNotFoundException: The given key '17736' was not present in the dictionary.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at MySql.Data.MySqlClient.MySqlField.SetFieldEncoding()
   at MySql.Data.MySqlClient.MySqlField.set_CharacterSetIndex(Int32 value)
   at MySql.Data.MySqlClient.NativeDriver.GetColumnData(MySqlField field)
   at MySql.Data.MySqlClient.NativeDriver.GetColumnsData(MySqlField[] columns)
   at MySql.Data.MySqlClient.Driver.GetColumns(Int32 count)
   at MySql.Data.MySqlClient.ResultSet.LoadColumns(Int32 numCols)
   at MySql.Data.MySqlClient.ResultSet..ctor(Driver d, Int32 statementId, Int32 numCols)
   at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
   at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
   at MySql.Data.MySqlClient.MySqlDataReader.Close()
   at MySql.Data.MySqlClient.MySqlCommand.ResetReader()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteScalar()
   at MySql.Data.EntityFrameworkCore.MySQLDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at MySql.Data.EntityFrameworkCore.Storage.Internal.MySQLExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation)
   at MySql.Data.EntityFrameworkCore.MySQLDatabaseCreator.Exists(Boolean retryOnNotExists)
   at MySql.Data.EntityFrameworkCore.MySQLDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

The error occurred after trying to reset my migrations, which I did by deleting the tables generated by EF Core, deleting the __EFMigrationsHistory  table, and deleting the migrations folder in my code.
After that I re-ran:
dotnet ef migrations add addItemTable
dotnet ef database update

The error log above came from the latter command.
I am not sure how to fix this. I even tried to delete the full database and re-running the commands.
If anyone has an idea of how to fix this please let me know.
EDIT:
For reference here is my .csproj with dependencies:
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>disable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <GenerateRuntimeConfigurationFiles>True</GenerateRuntimeConfigurationFiles>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3"/>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.10"/>
    <PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.22"/>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.10"/>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.10"/>
  </ItemGroup>
</Project>


text:
Q: How to fit a Gaussian distribution with outlier data points? I have a data set which consists of large number of data points. However, there are some outlier points that can be considered be noise. If I include all data points to approximate the Gaussian distribution, the standard deviation is apparently larger than expected. How can I fit this data set with a Gaussian distribution and get accurate mean and standard deviation ignoring these noise points.
Thanks

A: Try https//mycurvefit.com.  It's an online tool that will fit a curve to your data.  (AFAIK its free for smaller data sets but there might be a charge for large data sets).  With the tools just enter your data, select the fit.  You can also mark points as outliers by clicking to "flag" then remove those outliers and recalculate the new curve, e.g.


text:
Q: Kubernetes - Nginx Ingress SSL Termination I'm following this documentation and have successfully setup SSL termination on the NLB ingress. But the login page keeps asking for credentials and doesn't complete the login process.
Chrome shows that after entering the credentials it requests a http page (Internal Redirect) and then a redirect happens to https.
The pod is listening on port 8080. I think it tries to switch to https to complete the login, not sure.
100.96.xx.xx - - [05/Aug/2022:07:16:47 +0000] "GET /packs/bg-login.png HTTP/1.1" 404 728
100.96.xx.xx - - [05/Aug/2022:07:16:47 +0000] "GET /assets/favicon-6ca95f7b93eeb006088db7dd238353e62eb9ad976446654600ad6d42e2d62ae2.ico HTTP/1.1" 200 24838
100.96.xx.xx - - [05/Aug/2022:07:16:58 +0000] "POST /dashboard/authenticate?button=login HTTP/1.1" 200 61
100.96.xx.xx - - [05/Aug/2022:07:16:59 +0000] "GET /ems_infra/show_list HTTP/1.1" 302 113
100.96.xx.xx - - [05/Aug/2022:07:16:59 +0000] "GET /?timeout=false HTTP/1.1" 304 -
100.96.xx.xx - - [05/Aug/2022:07:17:00 +0000] "GET /packs/runtime-17e6ab38b1094a13ecb4.js.map HTTP/1.1" 200 8275

Any idea if something wrong with Ingress service?


text:
Q: Tesseract ios with trained data Is there any way to include trained data into the tesseract ios library ?
following this guide
http://michaeljaylissner.com/posts/2012/02/11/adding-new-fonts-to-tesseract-3-ocr-engine/
doesn't lead to anywhere with the repo I'm currently using
https://github.com/gali8/Tesseract-OCR-iOS
I need to know how to include the trained data into the above ios repo..
Thanks

A: Download tessdata as a zip from github . For example if you are trying english or France use this one: https://github.com/tesseract-ocr/tessdata
Then unzip it in your local. Drag and drop the "tessdata" folder from your local onto the XCode project. Make sure to to check "Copy Items if needed" and check "Create folder references" when you drag. Build and test.
For those who want to install from scratch. Follow this tutorial:
https://www.raywenderlich.com/163445/tesseract-ocr-tutorial-ios


text:
Q: Flask/JavaScript Error: Method Not Allowed The method is not allowed for the requested URL I'm getting this error: Method Not Allowed. The method is not allowed for the requested URL.
The relevant code is:
base.html:
<form class="form-inline" method="POST">
    <input id="nav_logout" type="submit" class="btn btn-default" value="Logout">
</form>

main.js:
function logout(e) {
    console.log('in logout');
    e.preventDefault();

    //posting our data to /api/v1/user
    qwest.post("/api/v1/logout")
        // then runs on success
     .then(function(xhr, response) {
        console.log("logged out user");
        console.log(response);
     })
        // catch runs on fail
     .catch(function(e, xhr, response) {
        console.log('in error');
        console.log(e);
     })
    console.log("completed logout")
}

var logout_button = document.getElementById('nav_logout');
logout_button.addEventListener('click', logout);

api.py:
@api.route('/api/v1/logout', methods=['POST'])
def logout_route():
    session.clear()
    return redirect(url_for('main.main_route'))

I have very similar code working in other places. I've read many similar StackOverflow articles with this same error; many say that the flask code didn't have the right POST/GET methods, but adding GET to my api route didn't help.
Thanks for your help!


text:
Q: The function (.).(.) in haskell I am trying to find the type of (.).(.) in Haskell, manually.
My attempt was the following:
(.).(.) = \x -> (.).(.) x

(.)     :: (     b   ->             c         )  ->  ((     a    ->           b        ) -> (a -> c))
(.)     :: (d -> e)  ->  ((f -> d) -> (g -> e))
(.)     ::                                              (h -> i) -> (j -> h) -> (h -> k)

-----------------------------------------------------------------------------------------------------
b ~ (d -> e) ~ (j -> h) -> (h -> k)
c ~ ((f -> d) -> (g -> e))
a ~ (h -> i)
d ~ h
e ~ i

so (a->c)~     (h->i) -> ((f -> h) -> (g -> i))

What is wrong in my way of thinking? The actual type is
(.).(.) :: (b -> c) -> (a1 -> a2 -> b) -> a1 -> a2 -> c

A: Let's look at the equivalent (.) (.) (.)
The first dot type:
(b -> c) -> (a -> b) -> a -> c
Second:
(e -> f) -> (d -> e) -> d -> f
Hence:
b is the same as e -> f
c is the same as (d -> e) -> d -> f
Third:
(h -> i) -> (g -> h) -> g -> i
Hence:
a is the same as h -> i
b is the same as (g -> h) -> g -> i
e -> f is (g -> h) -> g -> i
e is g -> h
f is g -> i
Since (.) (.) (.) :: a -> c from the first dot type, we have:
a -> c is (h -> i) -> (d -> e) -> d -> f
substituting e and f:
(h -> i) -> (d -> g -> h) -> d -> g -> I
Answering your question, I think that what is wrong with your thinking are last two lines e.g.:
d ~ h,
e ~ i

A: Your derivation should have been :
(.).(.) = (.) (.) (.)

(.) :: (   b      ->           c          )  ->  (   a      ->           b          ) -> (a -> c)
(.) ::  (d -> e)  ->  (f -> d) -> (g -> e)   -- WRONG
(.) ::                                            (h -> i)  ->  (j -> h) -> (h -> k)  -- WRONG
(.) ::  (d -> e)  ->  (f -> d) -> (f -> e)   -- correct
(.) ::                                            (h -> i)  ->  (j -> h) -> (j -> i)  -- correct

Thus the overall type is
(.) (.) (.) ::   a    ->                c                   ,   b ~ b
            ~  (h->i) ->  (f ->   d   ) -> (f ->   e   )    ,   (j -> h) -> (j -> i) ~
                                                               (   d     ->    e    )
             --------------------------------------------
               (h->i) ->  (f -> j -> h) -> (f -> j -> i)

Or,
               (                     h             -> i)
                      ->  (f -> j -> h)
             --------------------------------------------
                                        -> (f -> j -> i)

The types of such composition chains are often easier to follow with (>>>) = flip (.):
(.) . (.) = comp2  .  comp1
          = comp1 >>> comp2    where   comp1 = (.) ; comp2 = (.)

(>>>)    ::   (  a    ->         b         ) ->
                        (        b           ->         c         )  ->  (a -> c)
comp1    ::    (e->f) -> ((d->e) -> (d->f))
comp2    ::              (  h    ->   i   )  -> ((g->h) -> (g->i))
-------------------------------------------------------------------------
               (e->f)                        -> ((g->h) -> (g->i))
                         h~(d->e)   i~(d->f)
-------------------------------------------------------------------------
               (e->f) -> (g->d->e) -> (g->d->f)

Thus, again,
((.) . (.)) :: (c->r) -> (a->b->c) -> (a->b->r)
((.) . (.)) f g a b = f (g a b)

Indeed,
((.) . (.)) f g a b = ((.) . (.)) f  g  a  b
                    =  (.) ( (.)  f) g  a  b
                    =      ((f .)  . g) a  b     -- NB
                    =       (f .)  ( g  a) b
                    =       (f .     g  a) b

                    =        f (     g  a  b)

NB:

*

*Why function composition sometimes requires two "." 's to combine two functions

You can also verify that
((.) . (.) . (.)) :: (d->r) -> (a->b->c->d) -> (a->b->c->r)
((.) . (.) . (.)) f g a b c = f (g a b c)

Why? (.) is fmap for functions, and so we can re-write the above as
(fmap . fmap . fmap) f g a b c =
   fmap (fmap (fmap f)) g a b c =
   (do { x <- g ; return $ fmap (fmap f) x }) a b c =
   (do { x <- g ; return $ do { y <- x ; return $ fmap f y } }) a b c =
   (do { x <- g ; return $ do { y <- x ; return $ do { z <- y ; return $ f z } } }) a b c =
   let x=g a in (const $ do { y <- x ; return $ do { z <- y ; return $ f z } }) a b c =
   let x=g a in (do { y <- x ; return $ do { z <- y ; return $ f z } }) b c =
   let x=g a in let y=x b in (const $ do { z <- y ; return $ f z }) b c =
   let x=g a in let y=x b in (do { z <- y ; return $ f z }) c =
   let x=g a in let y=x b in let z=y c in const (f z) c =
   let x=g a in let y=x b in f (y c) =
   let x=g a in f (x b c) =
   f (g a b c)

This obviously works for any number of the chained compositions of fmaps that way.

A: The simple definition of compose is:
compose f h x = f (h x)

and its type:
compose :: (t1 -> t2) -> (t3 -> t1) -> t3 -> t2

the type variable name changes because I defined manually. So, if you want to compose the compose function, you will need an extra argument, because compose takes a function that takes one argument, so, compose of compose will need an extra argument. The definition of compose of compose could be simple as:
composeOfCompose f h x y = f (h x y)

and its type, as you could figure is:
composeOfCompose :: (t1 -> t2) -> (t3 -> t4 -> t1) -> t3 -> t4 -> t2

why is that? well, follow the application of functions:
x :: t3
y :: t4
h :: t3 -> t4 -> t1
f :: t1 -> t2
composeOfCompose f h :: t3 -> t4 -> t2

if you think it like this is a little simpler, I guess, at least for me.
To add a little more info about it with the question in the comment of D. W.:
compose :: (t1 -> t2) -> (t3 -> t1) -> t3 -> t2
compose f h x = f (h x)

composeOfCompose :: (t1 -> t2) -> (t4 -> t5 -> t1) -> t4 -> t5 -> t2
composeOfCompose  = compose compose compose

If the first compose is compose' and the second compose is compose''
compose' (f' :: (t1 -> t2))
         (h' :: (**t3** -> t1)) (x' :: **t3**) = f' (h' x')

and the second should have:
compose'' (f'' :: (t4 -> t5))
          (h'' :: (t6 -> t4)) (x'' :: t6) = f'' (h'' x'')

so...
**t3** ~ (t4 -> t5)
meaning h :: t4 -> t5 -> t1

translating in place, the middle compose::
compose f h x = f :: t1 -> t2
                (h :: t4 -> t5 -> t1)
                    (x :: t4 -> t5)) :: t1

A simple example:
:t (.) . (.)
(.) . (.) :: (b -> c) -> (a1 -> a2 -> b) -> a1 -> a2 -> c

lets create a function for that:
composeOfCompose  = (.) . (.)

data A1 = A | B deriving Show
data A2 = C | D deriving Show
data B  = E | F deriving Show
data C  = G | H deriving Show

transform :: A1 -> A2 -> B
transform A C = E
transform B C = E
transform _ _ = F

finalTrans :: B -> C
finalTrans E = G
finalTrans F = H

main = do
  putStrLn $ show $ (composeOfCompose finalTrans transform) A D

$> H


text:
Q: $⟨v, w⟩_1 = 0$ if and only if $⟨v, w⟩_2 = 0$. Prove that $⟨v, w⟩_1 = c⟨v, w⟩_2$, infinite-dimensional case? Suppose $⟨·, ·⟩_1$ and $⟨·, ·⟩_2$ are inner products on $V$ such that $⟨v, w⟩_1 = 0$ if and only if $⟨v, w⟩_2 = 0$. Prove that there is a positive number $c$ such that $⟨v, w⟩_1 = c⟨v, w⟩_2$ for every $v, w ∈ V$.
It is the Exercise6.B.11 from Linear Algebra Done Right. I've proved the finite-dimensional case. The "existence of orthonormal basis" theorem can only apply to finite-dimensional inner product space. So how to prove it when it is infinite-dimensional?

A: Here's a proof that works over $\mathbb{R}$.  I am not too used to inner products over $\mathbb{C}$ (as opposed to Hermitian inner products over $\mathbb{C}$), so I am not sure how much of this applies over $\mathbb{C}$.
Pick a non-zero $w\in V$ and define $c:= \frac{\langle w,w\rangle_1}{\langle w,w\rangle_2} = \frac{|w|_1^2}{|w|_2^2}$.  Note that $c$ is positive as it is a ratio of positive real numbers.
Lemma 1:  If $u\in V$ with $|u|_1 = |w|_1$, then $\langle u,u\rangle_1 = c\langle u,u\rangle_2$.
Proof:  Consider the two vectors $u+w$ and $u-w$.  Then $$\langle u+v, u-v\rangle_1 = \langle u,u\rangle_1 - \langle u,w\rangle_1 + \langle w,u\rangle_1 - \langle w,w\rangle_1 = 0.$$
So, $\langle u+w, u-w\rangle_1 = 0$.  Thus, $\langle u+w, u-w\rangle_2 = 0$.  Expanding this gives $|u|_2^2 - |w|_2^2 = 0$, so $|u|_2^2 = |w|_2^2 = c |w|_1^2 = c|u|_1^2$ $\square$
Lemma 2:  If $u\in V$, then $\langle u,u\rangle_1 = c\langle u,u\rangle_2$.
Proof:  If $u = 0$, the the result is obviously true.  If $u\neq 0$, then the element $\frac{|w|_1}{|u|_1} u$ has the same length (with respect to $\langle \cdot, \cdot\rangle_1$) as $w$.  By Lemma 1, $\left\langle\frac{|w|_1}{|u|_1} u,\frac{|w|_1}{|u|_1} u \right\rangle_1 = c\left\langle\frac{|w|_1}{|u|_1} u,\frac{|w|_1}{|u|_1} u \right\rangle_2$.  Pulling out the factors of $\frac{|w|_1}{|u|_1}$ and canceling gives the result for $u$.  $\square$
Lemma 3:  If $u,v\in V$, then $\langle u,v\rangle_1 = c\langle u,v\rangle_2$.
Proof:  From Lemma 2, $\langle u+v, u+v\rangle_1 = c\langle u +v, u+v\rangle_2$.  Expanding both sides gives and using Lemma 2 to cancel $|u|_1^2$ with $c|u|_2^2$ and similarly for $|v|_1^2$ and $c|v|_2^2$, we get $2\langle u,v\rangle_1 = 2c\langle u,v \rangle_2$.


text:
Q: Suppose $x, y, z$ are positive real number such that $x + 2y + 3z = 1$. Find the maximum value of $xyz^2$ I'm trying to solve this problem using Lagrange's multiplier method but I'm unable to get the value of lambda and also $z.$ kindly help  me out with this problem.
I'm getting $x = 2y$
I'm stuck somewhere between the steps

A: Alt. hint (no calculus):   the following inequality holds by AM-GM, with equality iff $\displaystyle x = 2y = \frac{3}{2}z\,$:
$$
\frac{\sqrt{3}}{\sqrt[4]{2}} \cdot \sqrt[4]{xyz^2} = \sqrt[4]{x \cdot 2y \cdot \frac{3}{2}z \cdot \frac{3}{2}z} \;\le\; \frac{x+2y+3z}{4} = \frac{1}{4} \;\;\iff\;\;xyz^2 \le \frac{2}{3^2 \cdot 4^4} = \frac{1}{1152}
$$

A: By definition, $\lambda$ is a constant, and we don't even really care what $\lambda$ is. It is always linear and factored from the gradient, so instead of finding $\lambda$, use it to jump from one equation to another.
$\lambda=yz^2$
$\lambda=\frac{xz^2}{2}$
$\lambda=\frac{2xyz}{3}$

A: Hint: prove that $$xyz^2\le \frac{1}{1152}$$ and the equal sign holds if $$x=\frac{1}{4},y=\frac{1}{8},z=\frac{1}{6}$$

A: You can also convert $xyz^2$ into a function of two variables $f(y,z)=(1-2y-3z)yz^2$ and use this test to conclude that the maxima occurs at $(\frac{1}{4},\frac{1}{8}, \frac{1}{6})$ and is $1152.$ You can ignore the other critical points since all of them have at least one $0$ entry while $x,y$ and $z$ are given positive.


text:
Q: extract all the strings between two characters powershell Following are the two characters.
 1. {{
 2. }}
I'm trying to find all the strings between these characters in the following file.
    <add key="CSDFG_SqlServerFailOverInterval" value="{{environment}}"/>
    <add key="CSDFG_JobResetInterval" value="600000"/>
    <add key="FileTypeFilter" value="{{filetype}}"/>

and I'm using following powershell commands,
$x = C:\app.config
$s = Get-Content $x
$prog = [regex]::match($s,'{{([^/)]+)}}').Groups[1].Value
write-host $prog

and my output is just one string. it is not pulling all the strings. Can someone please suggest me how to get the all the strings. Thanks in advance.

A: [regex]::Match() only returns the first match. Use [regex]::Matches() to capture all matches:
$s = Get-Content 'C:\app.config'
[regex]::Matches($s, '{{([^/)]+)}}') |ForEach-Object { $_.Groups[1].Value }


text:
Q: Gridview Row select and Delete I have a Gridview which shows id and name. I just want to delete the selected row in gridview and in database also by clicking on a button(on click event). There is a single delete button outside the gridview.
Your help would be appreciated.

A: Simply
GrdView.Rows.RemoveAt(GrdView.SelectedRows[0].Index);

if multiple rows selection enabled then
if (GrdView.SelectedRows.Count > 0)
{
    foreach (DataGridViewRow ro in GrdView.SelectedRows)
    {
        try
        {
            GrdView.Rows.Remove(ro);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Not Allowed...");
        }
    }
}

A: In the Submit_Click :
for (int i = 0; i < GV.Rows.Count; i++)
{
    GridViewRow row = GV.Rows[i];
    isChecked = ((CheckBox)row.FindControl("chkDelItem")).Checked;

    if (isChecked)
    {
        // delete
    }
}


text:
Q: C++: Get char after space character instead or return carriage Okay this is similar to my last question but what I ended up doing was way too complex for something as simple as this.  I simply need to get a single character or number (I will know which of these I am receiving) from the console after I press space, instead of pressing enter.  I'm sure there must be a way to have the terminal read input after a space instead of a '\n'.  I need to read inputs from the console in which the succeeding data types will vary depending on what the first input is, and I think reading the entire line, parsing it into strings, then parsing some of those into ints is a bit unnecessary.
So Is this actually not possible in C++ or have I just not found it yet?
EDIT:
For anyone who has had this problem I'm posting my solution, because I feel like an idiot now.
#include <iostream>

using namespace std;

int main() {

    int command = 0, x = 0, y = 0, z = 0;
    char c;

    do {
        cin >> command;
        switch(command) {
            case 1:
                cin >> c >> x;
                cout << c << " " << x << endl;
                break;
            case 2:
                cin >> x >> y >> z;
                    cout << x << " " << y << " " << z << endl;
                    break;
        }
    } while (command); //Exits when command = 0;

    return 0;

}

The following cin's inside the switch statement will read from the same buffer as the first cin, so there is no need to read what the command is beforehand anyway.  As you can see this works fine for different types and amounts of inputs after the first cin, so there's no need to use any other solution.
Just posting this for anyone else who may have the same problem, and not a great understanding of the way cin works.

A: Just issue multiple calls to getchar() (or getch()) in a loop and check the input every iteration.
Something like this (untested but should work):
int loop = 1
int spacehit = 0
char last_c = 0;
while(loop)
{
    char c = getchar();
    switch(c)
    {
        case ' ':
            spacehit = 1;
            printf("hit '%c' before 'space'!\n", last_c);
            break;
        case 'x':
            printf("hit 'x' after 'space'!\n");
            spacehit = 0;
            break;
        case 27: // escape
            loop = 0;
            break;
        default:
            // do something, e.g. append the key in c to a string
            break;
    }
    last_c = c;
}

Edit: Added some code to print the char before hitting space in case that's what you were looking for.


text:
Q: Selecting with sub queries in MySQL I have two sql queries. I want to know how to combine both queries into one.
// query #1 - Using this query return totalpoints of specific user  ex :userId   (10234324234)
SELECT SUM(points) AS totalPoints FROM users_points WHERE user_fb_id =10234324234 AND match_id >= 2

//query #2 - Using this query will return all the records on specific condition
SELECT users_points.*, user_points.totalPoints, user.user_firstName FROM users_points INNER JOIN user ON users_points.user_fb_id = user.user_fb_id WHERE users_points.match_id >= '$matchId'

I want to get records, all the users records with totalPoints of each user's using one query.

A: Just do this...
SELECT * FROM (SELECT * FROM B WHERE my_condition = something) WHERE my_second_condition = something_else

If I got the order right yours should look something like this
SELECT SUM(points) AS totalPoints FROM (SELECT users_points.*, user_points.totalPoints, user.user_firstName FROM users_points INNER JOIN user ON users_points.user_fb_id = user.user_fb_id WHERE users_points.match_id >= '$matchId') WHERE user_fb_id =10234324234 AND match_id >= 2


text:
Q: Combining tactics a certain number of times in Isabelle I find myself solving a goal that with safe splits to 32 subgoals. It is a quite algebraic goal so overall I need to use argo, algebra and auto. I was wondering if there is a way to specify that auto should be applied say 2 times, then algebra 10 times etc. Where should I look for this syntax in the future? Is it part of eisbach?

A: There is the REPEAT_DETERM_N tactical in $ISABELLE_HOME/src/Pure/tactical.ML I never used it so I'm not 100% sure it's what you need.
Alternatively your functionality can be done somewhat like that:
theory NTimes
imports
Main
"~~/src/HOL/Eisbach/Eisbach"
begin

ML ‹

infixr 2 TIMES

fun 0 TIMES _ = all_tac
  | n TIMES tac = tac THEN (n - 1) TIMES tac
›

notepad
begin
  fix A B C D
  have test1: "A ∧ B ∧ C ∧ D ⟹ True"
    apply (tactic ‹3 TIMES eresolve_tac @{context} [@{thm conjE}] 1›)
    apply (rule TrueI)
    done
  fix E
  have test2: "A ∧ B ∧ C ∧ D ∧ E ⟹ True"
    apply (tactic ‹2 TIMES 2 TIMES eresolve_tac @{context} [@{thm conjE}] 1›)
    apply (rule TrueI)
    done

end

(* For good examples for working
with higher order methods in ML see $ISABELLE_HOME/src/HOL/Eisbach/Eisbach.thy *)

method_setup ntimes = ‹
  Scan.lift Parse.nat -- Method.text_closure >>
  (fn (n, closure) => fn ctxt => fn facts =>
    let
      val tac = method_evaluate closure ctxt facts
    in
     SIMPLE_METHOD (n TIMES tac) facts
    end)
›

notepad
begin
  fix A B C D
  have test1: "A ∧ B ∧ C ∧ D ⟹ True"
    apply (ntimes 3 ‹erule conjE›)
    apply (rule TrueI)
    done
  fix E
  have test2: "A ∧ B ∧ C ∧ D ∧ E ⟹ True"
    apply (ntimes 2 ‹ntimes 2 ‹erule conjE››)
    apply (rule TrueI)
    done
  have test3: "A ∧ B ∧ C ∧ D ∧ E ⟹ True"
    apply (ntimes 3 ‹erule conjE›)
    apply (rule TrueI)
    done
  have test4: "A = A" "B = B" "C = C"
    apply -
    apply (ntimes 2 ‹fastforce›)
    apply (rule refl)
    done
(* in some examples one can instead use subgoal ranges *)
  have test5: "A = A" "B = B" "C = C"
    apply -
    apply (fastforce+)[2]
    apply (rule refl)
    done

end

end

I'm not an expert in Isabelle/ML Programming so this code is likely of low quality, but I hope it's a good starting point for you!


text:
Q: How to disable Android emulator animations in Travis? I am running Espresso tests in the Travis CI. When I run my tests in my device, I normally disable all my animations so I don't have to use Thread.sleep all the time.
But I really don't know how to do this in the Travis CI, so my tests fail without the Thread.sleep. I looked over the internet... but I didn't find any tutorial about how to do disable the animations in the emulator
I could use idling resource in Espresso, I know. But some times I would prefer not to.

A: If you try @azizbekian's path, I wrote about this here, created new test rules here and tested it here
I confirm @Testujaca Malpeczka path works on Travis-ci for Android APIs 17-22 as discussed here
If you are looking for a solution for latest Android APIs and tools, work in progress here and here
before_script:
  # Wait for emulator fully-booted and disable animations
  - android-wait-for-emulator
  - adb shell settings put global window_animation_scale 0 &
  - adb shell settings put global transition_animation_scale 0 &
  - adb shell settings put global animator_duration_scale 0 &
  - adb shell input keyevent 82 &

It also works in Circle-ci and probably any continuous integration build server, see broken link here
test:
  pre:
    - ...
    - circle-android wait-for-boot
    - adb shell input keyevent 82
    - adb shell settings put global window_animation_scale 0
    - adb shell settings put global transition_animation_scale 0
    - adb shell settings put global animator_duration_scale 0

My extended test rules work for Android APIs 15-22, and there was a bug in Android 23 emulator.
I'll try it for later versions 24+ using android-topeka sample another day, probably it works.
Any help, improvement or effective alternative using sdkmanager would be much appreciated.

A: If it possible use adb shell command:
adb shell settings put global window_animation_scale 0.0
adb shell settings put global transition_animation_scale 0.0
adb shell settings put global animator_duration_scale 0.0

tested on jenkins ci


text:
Q: How do I get a handle to the UVM factory? I'd like to get a handle to the UVM factory so as to use function such as set_type_override_by_name().

A: The UVM factory uses the singleton design pattern to provide a handle.  You get() a handle using the static get() method.
uvm_factory uvm_factory_h;
uvm_factory_h = uvm_factory::get();
uvm_factory_h.set_type_override_by_name("original_type_name","override_type_name");

etc.

A: You can directly use set_type_override_by_name method, without having uvm_factory handle.
For uvm_factory Handle -
Still, if you want to have uvm_factory class handle ,then you can use uvm_coreservice_t class to get uvm_factory handle.

The singleton instance of uvm_coreservice_t provides a common point
  for all central uvm services such as uvm_factory, uvm_report_server
  and so on.
The service class provides a static <::get> which returns
  an instance adhering to uvm_coreservice_t. The rest of the
  set_ get_ pairs provide access to the internal uvm
  services

To get uvm_factory handle:
uvm_coreservice_t cs = uvm_coreservice_t::get();
uvm_factory factory = cs.get_factory();
factory.set_type_override_by_name(original_type_name,override_type_name, replace);

For more information, visit http://sourceforge.net/p/uvm/code/ci/UVM_1_2_RELEASE/tree/distrib/src/base/uvm_coreservice.svh


text:
Q: What do you call those posters eye doctors use to test your eyesight? What do you call those posters eye doctors use to test your eyesight?

A: These are called 'Snellen charts', or more generally an 'eye chart'.


text:
Q: webserver in kubernetes incoming https allowed reply content in http blocked I deployed a web server in angular material in k8s and configured an ingress for this service, the ingress allows https incoming queries. The  This webserver talks to a backend service via http to get and content of the query.
-------https------->ingress---->webserver--------http-------->service to answer query
I've got an error that the ingress blocks reply content as it's from http
The error message is:
Mixed Content:
The page at https://myserver.com was loaded over ####.js HTTPS, but requested an insecure XMLHttpRequest  endpoint: "http://backend:port/end_point"
This request has been blocked; the content must be served over https

I tried the below solution but it did not work for me.
Redirects using http instead of https when in k8s with tls hand off by ingress
How can I fix this issue? Thanks.

A: This is a security feature of the browser object (your web server) which prevent HTTP content loaded via a secure page (HTTPS). You need to upgrade your backend to support HTTPS.


text:
Q: How to aggregate files in Mule ESB CE I need to aggregate a number of csv inbound files in-memory, if necessary resequencing them, on Mule ESB CE 3.2.1.
How could I implement this kind of logics?
I tried with message-chunking-aggregator-router, but it fails on startup because xsd schema does not admit such a configuration:
<message-chunking-aggregator-router timeout="20000" failOnTimeout="false" >
            <expression-message-info-mapping correlationIdExpression="#[header:correlation]"/>
</message-chunking-aggregator-router>

I've also tried to attach mine correlation ids to inbound messages, then process them by a custom-aggregator, but I've found that Mule internally uses a key made up of:
Serializable key=event.getId()+event.getMessage().getCorrelationSequence();//EventGroup:264

The internal id is everytime different (also if correlation sequence is correct): this way, Mule does not use only correlation sequence as I expected and same message is processed many times.
Finally, I can re-write a custom aggregator, but I would like to use a more consolidated technique.
Thanks in advance,
Gabriele

UPDATE
I've tried with message-chunk-aggregator but it doesn't fit my requisite, as it admits duplicates.
I try to detail the scenario I need to cover:

*

*Mule polls (on a SFTP location)

*file 1 "FIXEDPREFIX_1_of_2.zip" is detected and kept in memory somewhere (as an open SFTPStream, it's ok).
Some correlation info are mantained for grouping: group, sequence, group size.

*file 1 "FIXEDPREFIX_1_of_2.zip" is detected again, but cannot be inserted because would be duplicated

*file 2 "FIXEDPREFIX_2_of_2.zip" is detected, and correctly added

*stated that group size has been reached, Mule routes MessageCollection with the correct set of messages

About point 2., I'm lucky enough to get info from filename and put them into MuleMessage::correlation* properties, so that subsequent components could use them.
I did, but duplicates are processed the same.
Thanks again
Gabriele

A: Here is the right router to use with Mule 3: http://www.mulesoft.org/documentation/display/MULE3USER/Routing+Message+Processors#RoutingMessageProcessors-MessageChunkAggregator


text:
Q: What if we want to clamp/clip current to a certain value or range as we do with diodes for voltage? I have seen diode clamping/clipping circuits and can see that they can work well with such simple construction. However, what if we want to clamp/clip the current to some value rather than voltage?

A: Here are a bunch of constant current circuits that I found while googling "contant current circuit: -

*

*This is the classic use of a transistor - the load is in the
collector and you set the bias on the base so that there is a
certain voltage across R1 - if that voltage is 3.3V then, due to R1
being 3k3, no more than 1mA can be passed to the load.

*If the LED (or load) tries to take more current than a certain value the lower NPN transistor starts to switch on the reduces the base voltage on the darlington thus current limiting is achieved.

*This is the classic use of the LM317 regulator chip

*This is a fairly simple and accurate current limit circuit. The voltage across R2 is held at (V+ -Vref) by action of the op-amp and transistor - this means the load (connected to the emitter) cannot draw more current than (V+ -Vref)/R2.

*This is the same as (4) (sorry, my mistake)

*This is very similar to (2) but works with a +V referenced load.

*This is similar to (4) and (5) but uses a MOSFET as the current limiting element.

With voltage limiting the word clamping is often used. With current, the term used is often "limiting".