text:
Q: Optimize linq statement I have the linq statement below. How can I solve this without the loop. It is a tag system and I only want those exercises that have the tags with the ids in "myints"
int[] myints = {1,2};
  foreach (int tagid_temp in myints)
  {
    ExerciseByTagId =
        (from exercise in context.ExerciseSet
         where context.ItemsTagsSet
               .Where(a => a.TagsId == tagid_temp)
               .Select(a => a.ExerciseId).Contains(exercise.Id)
      select exercise);
  }

A: Guessing a little based on your query, but something like this?
(EDIT - realized my first example would return duplicate exercises if multiple matching tags were found)

    int[] myints = {1,2};
ExerciseByTagId =
    context.ExerciseSet
           .Where(e => context.ItemsTags
                              .Any(t=> t.ExerciseId == e.Id
                                         && myints.Contains(t.TagsId)
                 );

To get the items where ALL of the related items are in the list:
int[] myints = new int[] {1,2};

var ExerciseByTagId =
    context.ExerciseSet
    .Where(
        e => context.ItemsTags
                    .Where(t=> t.ExerciseId == e.Id)
                    .All(t => myints.Contains(t.TagsId))
        );

A: Contains()is pretty close to what you need, so use your own ContainsAll() function:
public static bool ContainsAll<T>(this IEnumerable<T> sequence, params T[] matches)
{
    return matches.All(value => sequence.Contains(value));
}

A: I tested this on a rather similar db structure, and it produces a single SQL statement:
var selected = new [] {1,2};

var ex = from ts in context.ItemsTagsSet
         where selected.Contains(ts.TagsId)
         group ts by ts.ExerciseId into g select new
         {
            ExerciseId = g.Key,
            Count      = g.Count()
         } into x
         where x.Count == selected.Length
         join e in context.ExerciseSet on e.ExerciseId equals x.ExerciseId
         select e;


text:
Q: Using Robot Framework to scan for open ports on localhost I'm using Robot Framework to test network issues and servers. I'm on a windows environment.
Right now, I'm in need to test if a certain service is available on localhost on a certain port. I could use netstat together with the Process library to figure out if the desired service is running on the designated port, but this seems to be a bit clumsy.
What might be a best suited Robot Framework library, to obtain the desired information?

A: You can do this by using robot framework SSHLibrary (http://robotframework.org/SSHLibrary/SSHLibrary.html)
Below example shows how to create ssh tunnel for port 8082 in the 192.168.10.10 host and map the 8082 port to 8083 in the local machine

*** Settings ***
Documentation          This example demonstrates executing a command on a remote machine
...                    and getting its output.
...
...                    Notice how connections are handled as part of the suite setup and
...                    teardown. This saves some time when executing several test cases.

Library                SSHLibrary
Suite Setup            Open Connection And Log In
Suite Teardown         Close All Connections

*** Variables ***
${HOST}                192.168.10.10
${USERNAME}            username
${PASSWORD}            Password

*** Test Cases ***
Execute Command And Verify Output
    [Documentation]    Execute Command can be used to run commands on the remote machine.
    ...                The keyword returns the standard output by default.
    ${output}=         Execute Command    echo Hello SSHLibrary!
    Should Be Equal    ${output}          Hello SSHLibrary!

*** Keywords ***
Open Connection And Log In
   Open Connection     ${HOST}
   Login               ${USERNAME}        ${PASSWORD}
   create local ssh tunnel  8083  ${HOST}  8082  #source_port  host_ip  destination_port

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plot two DataFrames first column with first column, second columns with second etc I have two Dataframes with 3 columns and 7 rows each,
A = {'col1': [20, 3, 45.6, 2, 500, 3e45, nan], 'col2': [nan, 90, 1e3, nan, 78, 6, nan],'col3':[25, 7e56, nan, nan, 23, 0.4, 78.04]}
B = {'a': [1, 24, 30, nan, nan, 56, 2.5], 'b': [100, nan, 10, 78.09, 1e29, 0.84, nan],'c': [nan, 4.6, nan, nan, 9e45, 0.2, nan] }
df_A = pd.DataFrame(data=a)
df_B = pd.DataFrame(data=b)

I'd like to iterate over the two Dataframes in order to do a scatter plot of the first column of df_A (col1) vs the first column of df_B (a), then the second column of A vs the second of B etc. And each plot should have the name of the columns as labels of the axis.
I tried with this, but it gives me as error the fact that x and y aren't of the same size.
for col in df_A:
     plt.scatter(df_A[col], df_B[col], label=col)

A: As already said in the comments, make sure either that both df have the same column names, or maybe try using this approach.
for col in range(len(df_A.columns)):
    plt.figure()
    plt.scatter(df_A[df_A.columns[col]], df_B[df_B.columns[col]], label=df_A.columns[col])
    plt.legend()

If instead you also have an error because the data is of different size, then a solution is to either trim the data of one df, or add some padding with dummy data to the shorter df.

A: You are trying to access col both in df_A and df_B and in your example the column names are different which leads to an error.
I managed to reproduce your example by using matplot subplots and this is the code that works:
import numpy as np
import matplotlib.pyplot as plt

#Load the dataframes
nan = np.nan
a = {'col1': [20, 3, 45.6, 2, 500, 3e45, nan], 'col2': [nan, 90, 1e3, nan, 78, 6, nan],'col3':[25, 7e56, nan, nan, 23, 0.4, 78.04]}
b = {'a': [1, 24, 30, nan, nan, 56, 2.5], 'b': [100, nan, 10, 78.09, 1e29, 0.84, nan],'c': [nan, 4.6, nan, nan, 9e45, 0.2, nan] }
df_A = pd.DataFrame(data=a)
df_B = pd.DataFrame(data=b)

#Plot
#To fix the column name problem use enumerate with indexes.
for i,col in enumerate(df_A):
    plt.subplot(2, 2, i+1)
    plt.title(col)
    plt.scatter(df_A[col].values,df_B.iloc[:,i].values)

plt.show()

A: In the end, I solved it like this:
x_name = df_A.columns
y_name = df_B.columns

for i,col in enumerate(df_A.columns):
     plt.scatter(df_A.iloc[:,i], df_B.iloc[:,i])
     plt.xlabel(x_name[i])
     plt.ylabel(y_name[i])
     plt.show()


text:
Q: Position SVG lines over HTML elements, while still allowing interaction with the HTMl elements Given the following Codesnippet:

.html {
  position: absolute;
  height: 100%;
  width: 100%;
  left: 0;
  top: 0;
}

.svg {
  position: fixed;
  height: 100%;
  width: 100%;
  left: 0;
  top: 0;
}

      Some text

    <svg class="svg">
          <line x1="0" y1="0" x2="200" y2="200" stroke="blue" stroke-width="10"></line>
        </svg>

(See http://jsfiddle.net/5phzgxLa/)
I would like to have the SVG line be drawn over the p element within the HTML, while still being able to fully interact with the HTML (the title text should still display on hover, and the onclick handler should still fire on clicking the text).
I can change the HTML and CSS in any way needed to do this, but I do need the SVG to be fixed over the HTML, as I essentially want an SVG layer I can draw things on over normal HTML, with the SVG layer moving as the page is scrolled.
Is this possible? If not, is there any way to achieve a similar effect?


text:
Q: Avoid hang-ups while processing big csv files in R My task is loading a big csv file (9 gb) and extracting some specific rows and save theses specific rows in a new csv file. This proceeding I'm doing with a function. Therefore in my console I load my function with the source() command and then execute the function with myfun().
Exceeds the csv file 6 gb my computer hang-up.
Solution approaches that I tried with no success:

*

*How can I remove all objects but one from the workspace in R?

*

*Because I have a function my variables aren't in my workspace and so I can't remove them…

*The gc() command

*

*Here on stackoverflow are some various post to this topic

*Recently I used gc() to release my memory – and it works

*But now I need my three variables (start, quantity and l) – means not all variables are allowed to delete

*In the fifth or sixth for-loop the computer hang-up

*Note:  without the gc() command I only reach the second or third for-loop

*

*The gc() command has an effect

An additional note to my csv file:

*

*It has 6 columns

*I need to extract every fortieth or hundredth row

*

*The distance of rows I have to detect

*And I'm not sure if the distance of rows is constant over the whole csv file

My pc is a win7 machine with 64 bit and 16 mb internal memory.
And now my question: Is there a way to avoid hang-ups? Maybe a better position of gc() in my code or some other arguments for gc()?
When you need further information please comment – I will edit my post.
Many thanks in advance!
Now my code:
    library(data.table)  # because of the fread() command

    myfun=function () {

    start=i
    quantity=2.2*10^7  # this is the number of rows and this amount is about 1.2 gb of the csv file
    for (l in 1:12) {  # the 12 is guessed… perhaps here exists also a better solution

        DT=fread("C:\\user1\\AllRows.csv",sep = ";",stringsAsFactors=FALSE,drop=7,header=FALSE,nrows= quantity,skip=start,data.table=FALSE)
        colnames(DT)=c("col_1"," col_2"," col_3"," col_4"," col_5"," col_6")

        # Detect the distance of rows and extract the corresponding rows
        # and save it in data.df

        # and now data.df will be saved
        file=file.path("C:\\user1\\ExtractedRows.csv"))
        if (l==1) {write.table(data.df,file=file,sep=";",dec=",",row.names=FALSE,col.names= c("col_1"," col_2"," col_3"," col_4"," col_5"," col_6"),append=FALSE)}
        if (l!=1) {write.table(data.df,file=file,sep=";",dec=",",row.names=FALSE,col.names=FALSE,append=TRUE)}

        # release the internal memory
        gc(reset=T)

        # incrementing start
        start = start + quantity

    }  # end of for loop

    }  # end of function

A: When working with data too big to fit in memory, you can use SQLlite to hold the data on the disk and then query out what you need.
Here is reference to help get you started: https://www.r-bloggers.com/r-and-sqlite-part-1/
This approach is probably better suited to your problem than the method you outlined in your question.


text:
Q: Invalid Bundle Info.plist specifies a non-existent file for the CFBundleExecutable key I've updated to Xcode 7 and running into the following issue when trying to archive and send an update to my app to itunes connect.
We have discovered one or more issues with your recent delivery.
To process your delivery, the following issues must be corrected:
Invalid Bundle - Info.plist specifies a non-existent file for the CFBundleExecutable key.
Once these issues have been corrected, you can then redeliver the corrected binary.

I've tried to removing the CFBundleExecutable but then I can't build the target. This relates to some google signing sdk issue and isn't my problem.
source: https://stackoverflow.com/a/32645052/1329173
The only other thing I can find is https://github.com/danielgindi/ios-charts/issues/442 but again this isn't a libray I'm using.
In iTunesConnect it shows me the upload is still in "processing" state and will not get avaible due to issue.
I've also tried cleaning and removing debug and bin folders.
The CFBundleExecutable is set to Executetable_name
<key>CFBundleExecutable</key>
    <string>${EXECUTABLE_NAME}</string>

A: Do you have any .bundle included in your project ?
If you do, check its content, and make sure it doesn't contain any plist, and this plist doesn't contain CFBundleExecutable key.
(a broad search for CFBundleExecutable in your workspace might give you hint at where this problem comes from...)
In my case, simply removing the whole Instabug.bundle did the trick, although you might want to use such a third party, so you might edit the plist instead to remove this problematic key...

A: I got it to work not knowing what exactly coursed it. I update OS X from Yosemite to El Capitan (10.11). Then Xcode had some components to update when launching, which it didn't specified, it's still Xcode version 7.0.1 (7A11001). The last thing that had changed was iTunes Connect interface (sep-oct 2015), so they could have had some maintenance/update that messed something up as it was labeled as "processing" in iTunes Connect. Processing for a week


text:
Q: Bug in search results I ran the following search:

[bash] or [awk] answers:0 score:0+ closed:no

However, the top result there shows a score of -1, which is a contradiction of my requirement score:0+.  What am I doing wrong?

A: It's not working because score:0+ is not a valid search. Look how "score" is not listed on the right:

You want to use score:0.., like this.


text:
Q: How to use buttons to keep adding text in HTML JavaScript? I need to create a web page that displays 10 buttons (0-9). When, for example, the button number 4 is clicked, the web page should display the following message under the buttons:
You have entered four

When, for example, the button number 9 is clicked next, the message will become:
You have entered four-nine

This process continues.
Here is what I have so far. I have been able to display each number individually, but cannot figure out how to continue adding numbers to the display once they've been clicked.

function number0(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML = "zero";
}

function number1(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML = "one";
}

function number2(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML = "two";
}

function number3(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML = "three";
}

function number4(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML = "four";
}

function number5(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML = "five";
}

function number6(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML = "six";
}

function number7(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML = "seven";
}

function number8(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML = "eight";
}

function number9(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML = "nine";
}
<button onclick="number0()">0</button>
<button onclick="number1()">1</button>
<button onclick="number2()">2</button>
<button onclick="number3()">3</button>
<button onclick="number4()">4</button>
<button onclick="number5()">5</button>
<button onclick="number6()">6</button>
<button onclick="number7()">7</button>
<button onclick="number8()">8</button>
<button onclick="number9()">9</button>

A: You need to not overwrite the content every time:

  <button onclick="number0()">0</button>
  <button onclick="number1()">1</button>
  <button onclick="number2()">2</button>
  <button onclick="number3()">3</button>
  <button onclick="number4()">4</button>
  <button onclick="number5()">5</button>
  <button onclick="number6()">6</button>
  <button onclick="number7()">7</button>
  <button onclick="number8()">8</button>
  <button onclick="number9()">9</button>

You can optimize the script with event listeners and HTML custom attributes:

var displaySpan = document.getElementById("display");
document.querySelectorAll('.number-btn').forEach(function(btn) {
  btn.addEventListener('click', function(e) {
    displaySpan.innerHTML += displaySpan.innerHTML
      ? "-"
      : "You have entered: ";
    displaySpan.innerHTML += e.target.getAttribute('data');
  });
});

  <button class="number-btn" data="zero">0</button>
  <button class="number-btn" data="one">1</button>
  <button class="number-btn" data="two">2</button>
  <button class="number-btn" data="three">3</button>
  <button class="number-btn" data="four">4</button>
  <button class="number-btn" data="five">5</button>
  <button class="number-btn" data="six">6</button>
  <button class="number-btn" data="seven">7</button>
  <button class="number-btn" data="eight">8</button>
  <button class="number-btn" data="nine">9</button>

A: it's pretty easy, the only thing you have to do is just swap "=" with "+=". For example:
function number6(){
  var displaySpan = document.getElementById("display");

  displaySpan.innerHTML += "six";
}

"+=" takes previous value, and add new one.
If you want to make it easier to edit, and easy add new values, I would suggest to use function with switch like this:
function number(number){
    var displaySpan = document.getElementById("display");

    //Defines what is in inner
    var innerDisplay = displaySpan.innerHTML;
    //Will be defined by switch and then added to text
    var newNumber = '';

    //It takes number from the function and define new number
    switch(number){
        case 0:
            newNumber = "zero";
            break;

        case 1:
            newNumber = "one";
            break;
        //And add all of this then.
    }

    //then check if there is alredy some number in display
    if (innerDisplay){
        innerDisplay += "-" + newNumber;
    } else{
        //If there is no already set text in display, ten create new one
        innerDisplay = "You have entered " + newNumber;
    }
}

And in HTML just swap name and give numbers in fucntion:
<button onclick="number(0)">0</button>
<button onclick="number(1)">1</button>
<button onclick="number(2)">2</button>
<button onclick="number(3)">3</button>
<button onclick="number(4)">4</button>
<button onclick="number(5)">5</button>
<button onclick="number(6)">6</button>
<button onclick="number(7)">7</button>
<button onclick="number(8)">8</button>
<button onclick="number(9)">9</button>

And then, if u want to change something, you just edit one function not ten.

A: Here's a full working demo:

<!doctype html>

    <title></title>

    <button onclick="number('zero')">0</button>
    <button onclick="number('one')">1</button>
    <button onclick="number('two')">2</button>
    <button onclick="number('three')">3</button>
    <button onclick="number('four')">4</button>
    <button onclick="number('five')">5</button>
    <button onclick="number('six')">6</button>
    <button onclick="number('seven')">7</button>
    <button onclick="number('eight')">8</button>
    <button onclick="number('nine')">9</button>

A: You jsute need to add a bash - id the displaySpan.innerHTML isn't empty.
Sample :
displaySpan.innerHTML += (displaySpan.innerHTML.length === 0 ? '' : '-') + "number";

A: You could do something simple, like this:

// Store a reference to our text-container element (to display the output message)
const textEl = document.querySelector('#text-container');

// Our event handler function that will handle any click event on a button
const handleClick = e => {
  if (e.target.tagName === 'BUTTON') {
    if (textEl.innerText.length === 0) {
      textEl.insertAdjacentHTML('beforeend', 'You have entered ');
    } else {
      textEl.insertAdjacentHTML('beforeend', '-');
    }
    textEl.insertAdjacentHTML('beforeend', e.target.value);
  }
};

// When any button in btn-container is clicked, handleClick will fire
document.querySelector('#btn-container').addEventListener('click', handleClick);

  <button value="zero">0</button>
  <button value="one">1</button>
  <button value="two">2</button>
  <button value="three">3</button>
  <button value="four">4</button>
  <button value="five">5</button>
  <button value="six">6</button>
  <button value="seven">7</button>
  <button value="eight">8</button>
  <button value="nine">9</button>

Basically, just give every button a value which you can then use when a click event occurs on the parent div (this technique is called event delegation and it requires only 1 since event handler, instead of 1 for each button). When a button is clicked, simply add it's value to the string.

A: You can have a single function that takes event as the argument and set the onclicks of all the buttons to that function. You also have to set the value of the buttons to the numbers in words. So in the function you get the event target and the value, which is the word form and add it up to the innerHTML of the display span. so to check if a hyphen is needed you can use the length of the innerHTML string to know if a number has already been added up.
Like this:

    You have entered
    <button value= "zero" onclick="number(event)">0</button>
    <button value= "one" onclick="number(event)">1</button>
    <button value= "two" onclick="number(event)">2</button>
    <button value= "three" onclick="number(event)">3</button>
    <button value= "four" onclick="number(event)">4</button>
    <button value= "five" onclick="number(event)">5</button>
    <button value= "six" onclick="number(event)">6</button>
    <button value= "seven" onclick="number(event)">7</button>
    <button value= "eight" onclick="number(event)">8</button>
    <button value= "nine" onclick="number(event)">9</button>


text:
Q: I read that you cant leave Teams for core and non core scenarios So I have an app on a website that loads in an iframe.  Is this allowed or not in app source and the teams design challenge.  I also read that you can have an exe launch.  Where would we store the exe so that it could launch?

A: You can load Iframe with in teams as tab. Could you please check this docs?


text:
Q: Python : Import modules once then share with several files I have files as follow,
file1.py
file2.py
file3.py

Let's say that all three use
lib7.py
lib8.py
lib9.py

Currently each of the three files has the lines
import lib7
import lib8
import lib9

How can I setup my directory/code such that the libs are imported only once, and then shared among the three files?

A: Import each of them in a separate module, and then import that:
lib.py:
import lib7
import lib8
import lib9

In each of the files (file1.py, file2.py, file3.py), just use import lib. Of course, you then have to reference them with lib.lib7 – to avoid that, you can use from lib import *.

A: You will have to import something at least once per file. But you can set it up such that this is a single import line:
The probably cleanest way is to create a folder lib, move all lib?.py in there, and add an empty file called __init__.py to it.
This way you create a package out of your lib?.py files. It can then be used like this:
import lib
lib.lib7

Depending on where you want to end up, you might also want to have some code in the __init__.py:
from lib7 import *
from lib8 import *
from lib9 import *

This way you get all symbols from the individual lib?.py in a single import lib:
import lib
lib.something_from_lib7


text:
Q: Python - Treating the string 'NA' as Null or NaN to do fillna() I have a dataframe:
mydf = pd.DataFrame({'foo': ['bar', 'NA', 'Bar'], 'bar': ['NA', 'foo', 'NA']})

I would like to fill the 'NA' values using the fillna() function.
However, fillna() does not detect 'NA' as Null/NaN values.
Would I have to convert all 'NA' to NaN? Or is there a way I can treat 'NA' as NaN in my dataframe?

A: You can use replace function
mydf.replace('NA', <value_you_want>, inplace=True)

Or, first, replace 'NA' with NaN and the use fillna method
import numpy as np
mydf.replace('NA', np.nan, inplace=True)
mydf.fillna(<value_you_want>)

A: You need to convert all the 'NA' to NumPy.nan values and because python detects 'None' and not 'NA'.


text:
Q: Why are some files named 'www'? I have spent the last month playing around with Cordova app building and I have noticed that many established cordova plugin repositories contain files named 'www'. Could someone explain to me what the 'www' represents or stands for and what type of files should be contained in these folders? TYIA

A: Generally speaking ..  When creating a Cordova app, a www directory is created.  This is considered the "working directory".  And for certain apps, like Phonegap apps say, this www directory is where all the "front facing" web related files reside.  Files that contain JS, CSS, or HTML to be read by a web browser or web interface.  An example of Cordova App setup and creation can be found HERE  --  You can see how during app creation, Cordova creates a www directory.


text:
Q: SSRS report in iframe appears then disappears I am using an iframe to show an SSRS report and I am experiencing a strange problem. When I attempt to present a report that contains nothing by a chart everything works perfectly, but when I attempt to show a report that contains a list of customers the content appears then disappears right after loading.
The main difference is that the chart report is by SSRS stored as an image converted to binary data in the database, while the customer list report is by SSRS stored as text data converted to binary data in the database. The customer list report is rendered as a lot of different JavaScript functions and HTML code, while the chart report is rendered as a lot of different JavaScript functions and some HTML code to present the final chart image.
I just cannot get my head around why this should crash. I would have thought that it would be completely safe HTML-wise to render a complete HTML document in an iframe. Does anyone have any clue as to why the list report first appears then all of a sudden disappears again when the chart report works perfectly?
EDIT: I am only experiencing this behaviour in Chrome. Firefox and IE both render the list report aswell as the chart report, although there is a table overlap problem in Firefox, but first things first.

A: I just upgraded Google Chrome to the latest version and that solved the issue. I did some research online and my results suggest that iframe content suddenly disappearing after loading is a known issue with a certain previous version of Chrome. I have no version number, but if anyone else experiences a similar issue then they should attempt to upgrade to the latest version.


text:
Q: Importing from excel "applications" using SSIS I am looking for any tips or resources on importing from excel into a SQL database, but specifically when the information is NOT in column and row format.
I am currently doing some pre-development work for a project, and in most ways I would like to use SSIS for the project. The one area that my research and googling is leaving a big question mark over is the import of the excel sheet.
In short our users are using excel as a simple calculator / application. Values are entered into specific cells in the sheet and then in other cells formulas come up with the final answers. The sheet has been "beautified" to make it easier for users to use (i.e. white space, merged cells, pretty colours, etc). I need a mechanism to get both the raw values and the final answers and import them into a SQL database.
There is a ton of information on the trials and tribulations of importing column and row info into Excel, but have any fellow stack-overflowers had experience with this? Is SSIS appropriate for this (the other viable option would have to be integration into a .NET service).
Thanks!

A: What about adding a sheet to the workbook that pulls the answers from the calculation sheet and shows them in a tabular format, and then use the magic of SSIS to suck in the values from that new sheet?
If you can't modify the worksheet, you might want to look into Interop services or something where you can specify the exact cells you want to pull data from.
I'd try the first route if possible, though another option might be to simply recreate their Excel calculator as a .NET app...

A: A SSIS Excel data source uses worksheet or range -- think table with column names. You could also consider using VBA from within Excel to push data into your DB.

A: SpreadsheetGear for .NET will let you load an Excel workbook, put values in cells, calculate, get results as raw values or formatted text and more. This might be your best option if the data is not suitable for SSIS - but it will require that you use .NET (C#, VB or any .NET language) to automate your process. The advantage of SpreadsheetGear is that you then have a solution which does not depend on anything other than .NET (of course it depends on SpreadsheetGear, but SpreadsheetGear can be deployed royalty free with your application using xcopy deployment or any other deployment method).
You can see live samples here and download the free trial here.
Disclaimer: I own SpreadsheetGear LLC


text:
Q: What's the purpose of Button stretching option in xcode 8 I don't understand what stretching option(from Attributes Inspector of UIButton) is. Could someone explain about the purpose of stretching option of UIButton?
I fully understand UIImage stretching principle and I usually use the stretching option for PNG images. But, UIButton stretching does not work for any image, especially for the Background Image of UIButton.
Please do not comment about Image Slicing. My topic is not asking about slicing.
Here is my case:

Above is my original image and of size 74x74. If I use UIImage stretching option like this: "X: 0.5, Y: 0.5, Width: 0, Height: 0" in Attributes Inspector in Xcode 8, I can get pure stretched image like below:

However, once I apply this Image to UIButton Background Image, it has no stretching effect.
Can anybody explain about UIImage stretching option or why is this needed for UIButton? Please give me comments about it!
Thanks!

A: Here you are modifying contentStretch property.Defines the stretchable and nonstretchable regions of a view.Using x,y,width and height properties you can define the region to stretch.
For example x = 0 , y = 0 , width = 1 and height = 0 means , view's entire area is stretchable.
Content stretching is often used to animate the resizing of a view. For example, buttons and other controls use stretching to maintain crisp borders while allowing the middle portions of the control to stretch and fill the available space.
You can find more details here - contentStretch


text:
Q: Creating Hive Table Producer for Kafka Topic My use case is to create a Producer using Apache Hive table records and send it to a Kafka Topic.
I explored Confluent Kafka Connect, but so far they only offered a demo from Kafka Topic to Hive tables using HDFS Connector.
Has anyone done one from source Hive tables to a Kafka Topic using Kafka Connectors?
Or are there other options like writing custom Java API package that we can use?
I'm well open to other options.

A: You were correct that Kafka HDFS Connect is only a Sink, not a Source for Kafka. Edit: Seems there is now an HDFS3Source (under a trial license)
Personally, I would skip Hive entirely, and read from HDFS.
You can use pure Java to do this, or you can use Spark/Flink for integration with those Kafka libraries, or you can try more visual tools like Apache NiFi or Streamsets to pull HDFS data and send it to Kafka.
Usually, HDFS is not a source for Kafka data, anyway, from what I've seen. If you need to pull things out, Spark seems to be the most commonly used tool to do that. Writing to a Kafka topic is an implementation detail.


text:
Q: iCalendar Stopped working since March 1st 2016 (Outlook) I'm really out of words to understand this problem that I have.
I'm sending a meeting request in an email as an alternate view "text/calendar".
It worked for the last 3 years. Now, since march 1st, it does not show the .ICS file inside the outlook email. When I open the same email with my gmail account, it does show the email as intended.
This is my iCal string
BEGIN:VCALENDAR
PRODID:-//Episode Software//Email Meeting Manager//EN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
X-MS-OLK-FORCEINSPECTOROPEN:TRUE
BEGIN:VEVENT
DTSTART:20160112T160000Z
DTEND:20160112T170000Z
DTSTAMP:20151201T161706Z
ORGANIZER;CN=noreply@fusioncontact.ca
 :mailto:noreply@fusioncontact.ca
UID:{8802ed55-1a3a-478e-a23f-5d35ff62535c}
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
X-MICROSOFT-CDO-IMPORTANCE:1
X-MICROSOFT-DISALLOW-COUNTER:FALSE
X-MS-OLK-AUTOFILLLOCATION:FALSE
X-MS-OLK-CONFTYPE:0
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;
 RSVP=TRUE;
 CN=123@episodesoft.com;X-NUM-GUESTS=0:mailto:123@episodesoft.com
CREATED:20151201T161706Z
DESCRIPTION:Nouveau rendez-vous avec Leetwo Metal Inc pour 2016-01-12- J.P
LAST-MODIFIED:20151201T161706Z
LOCATION:7800 Aut Transcanadienne, Pointe-Claire, H9R1C6
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Nouveau rendez-vous avec Leetwo Metal Inc pour 2016-01-12- J.P
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR

This is how I create the alternate view before sending the email.
AlternateView.CreateAlternateViewFromString(m_calendarViewString, loCalendarType)
Note that the m_calendarViewString is equal to that iCal string.
When I send this email to my gmail account, it works perfectly. It does put the appointment into my calendar and it is also selected as "Yes".
Here is a screenshot :

My screenshot is in french. It says that you have a new meeting with bla bla. Yes, Maybe, No. As you can see, the "Oui" (Yes) is selected by default.
Anyone has any clue, why all of a sudden it stopped working?
Thanks in advance.

A: You do not give much details about your Outlook environment: have you tried with different versions of Outlook, did you upgrade recently, is your Outlook client talking to an Exchange Server or to an IMAP Server, etc... In other words, this probably has more to do with a change in your environment than with this particular date or ics request.
You can also have a look at Multipart email with text and calendar: Outlook doesn't recognize ics


text:
Q: Change input marker How can i change the flashing input marker (the one that looks like this: |) in a textfield? I want it to be a flashing underscore (_) like in the windows cmd instead.

A: I dont't think you can change the browser default blinking cursor..
If you're interested, I found some javascript 'workaround' examples that might get you started in the right direction if you check out the source and tweak a bit.
http://www.burnmind.com/tutorials/typing/
http://shachi.prophp.org/demo.html
http://www.masswerk.at/jsuix/index.html


text:
Q: "Countable" and "Sequence" in Toplology I'm having difficulty with the meanings of these terms in several references. "Countable" may mean either a set with cardinality = N (i.e. countably infinite) , or with cardinality $\le$ N (i.e. countably infinite or finite). "Sequences" may mean specifically an infinite sequence (with cardinality = N), or may allow infinite or finite (with cardinality $\le$ N)

*

*.... Specifically, a space X is said to be first-countable if each point has a countable neighborhood basis (local base). That is, for each point x in X there exists a sequence $N_1, N_2, … $ of neighborhoods of x such that ....(Wiki)

*.... More explicitly, this means that a topological space T is second countable if there exists some countable collection $\mathcal{U} = \{U_i\}_{i=1}^\infty $ of open subsets of T... (Wiki)

*a Lindelöf space is a topological space in which every open cover has a countable subcover. The Lindelöf property is a weakening of the more commonly used notion of compactness, which requires the existence of a finite subcover.... (Wiki)

*In mathematics a topological space is called separable if it contains a countable, dense subset; that is, there exists a sequence $\{x_{n}\}_{n=1}^{\infty } $of elements of the space such that every nonempty open subset of the space contains at least one element of the sequence.... (Wiki - in this case it seems that the sequence is intended to be infinite).

*In mathematics, a countable set is a set with the same cardinality (number of elements) as some subset of the set of natural numbers. A countable set is either a finite set or a countably infinite set. ....Some authors use countable set to mean countably infinite alone (Wiki)

My confusion continues into, for example, the proof that a second countable metric space is Lindelöf, e.g. here: https://proofwiki.org/wiki/Sequentially_Compact_Metric_Space_is_Lindel%C3%B6f
As far as I can see, the proof seems to establish that every cover has a "countable", possibly finite, subcover: should it also prove that the subcover is not finite ?

A: I don't follow what the problem is. In general, and here, countable means countably infinite or finite. Sequence (at least in this context) means "sequence indexed by the natural numbers". Maybe you need to note that the terms in a sequence need not be distinct; an "infinite sequence" may actually attain only finitely many values.
So for example say $X=\{0\}$, with the only possible topology. Then $X$ is first countable. The required sequence of neighborhoods of $0$ is $N_1,N_2,\dots$, where $N_j=X$ for all $j$.
Similarly a space with only finitely many points is separable. It's clear that such a space contains a countable dense subset. The sequence in the "that is" part of (4) would be any ("infinite") sequence that contains every element of $X$ infinitely often.


text:
Q: Angular prevent multiple form submissions I would like to prevent users from being able to submit forms multiple times in my application. I built a directive that will disable the button once it has been clicked which works fine, however the button stays disabled when the form submission fails and I'm not sure how to resolve that.
The problem scenario: A user fills out the form and clicks submit. The button is disabled to prevent additional clicks. ngSubmit makes a GET request to an API which returns a response with a code outside of the 200's. My code will then look at the error, determine what went wrong, and set validation errors on the form so the user can correct the issue then try again.
However the directive has no idea what happened after the button was disabled and has no way of knowing it needs to be enabled now to allow the user to submit the form again.
@Directive({
  selector: '[appPreventDoubleClick]'
})
export class PreventDoubleClickDirective {
  private alreadyClicked = false;

  constructor(
    private elementRef: ElementRef
  ) { }

  @HostListener('click', [ '$event' ]) onClick(event: MouseEvent): void {
    this.handleClick(event);
  }

  private handleClick(event: MouseEvent): void {
    if (this.alreadyClicked) {
      event.preventDefault();
    } else {
      this.alreadyClicked = true;
    }
  }
}


text:
Q: Class 'Zend_Measure_Weight' not found - Magento I am getting Fatal error when I go to shipping page in Magento (ver 1.9). Its saying:

Fatal error: Class 'Zend_Measure_Weight' not found in
  /home/www/mysite.com/www/newsite/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php
  on line 439

I have this code on line 439:
'dimensions_variables'  => array(
                'L'         => Zend_Measure_Weight::POUND,
                'LB'        => Zend_Measure_Weight::POUND,
                'POUND'     => Zend_Measure_Weight::POUND,
                'K'         => Zend_Measure_Weight::KILOGRAM,
                'KG'        => Zend_Measure_Weight::KILOGRAM,
                'KILOGRAM'  => Zend_Measure_Weight::KILOGRAM,
                'I'         => Zend_Measure_Length::INCH,
                'IN'        => Zend_Measure_Length::INCH,
                'INCH'      => Zend_Measure_Length::INCH,
                'C'         => Zend_Measure_Length::CENTIMETER,
                'CM'        => Zend_Measure_Length::CENTIMETER,
                'CENTIMETER'=> Zend_Measure_Length::CENTIMETER,

            )

How can I fix it ?

A: Because you call it from your model, so you have to add this before your class
require_once(Mage::getBaseDir('lib') . '/Zend/Measure/Weight.php');

class ........ extends Mage_Core_Model_Abstract

and done, you can call the Zend_Measure_Weight class now.


text:
Q: Json String parse into Dictionary key value pairs c# I am trying the convert my json string into dictionary but could not successful.
    {
  "healths": [
    {
      "serviceName": "UserMgt",
      "subService": [
        {
          "subServiceName": "Base",
          "status": 10
        },
        {
          "subServiceName": "Url",
          "description": "Url is bad",
          "status": 10
        },
        {
          "subServiceName": "Configuration",
          "status": 2
        }
      ]
    },
    {
      "serviceName": "ConfigurationMgt",
      "subService": [
        {
          "subServiceName": "url",
          "description": "urlis OK!",
          "status": 2
        },
        {
          "subServiceName": "Configuration Db",
          "status": 2
        }
      ]
    }
}...and so son

So, as you see we have a service name, and based on that we have subserviceName then again service name and subservicename.Basiclly i want to convert this into dictionary as a key-value pair so that based on the key(service) we have values subservice(again a key value pair).
I tried many things but does not get a proper result.
like for example using newtonsoft nuget.
JObject jsonObj = JObject.Parse(formattedJson);
Dictionary<string, object> dictObj = jsonObj.ToObject<Dictionary<string, object>>();
foreach(var kv in dictObj)
{
  Console.WriteLine(kv.Key + "::::" + kv.Value);
}

In this scenario I am getting output like key as a healths and every thing as a value.
Can anyone please help me regarding this.The Json and c# is new for me.
Thanks In Advance.

A: Assuming that you are guaranteed to have the described structure, you can deserialize to JObject and use LINQ's ToDictionary to process it:
var dict = JsonConvert.DeserializeObject<JObject>(json)["healths"]
    .ToDictionary(
        s => s["serviceName"].ToString(),
        s => s["subService"]
            .ToDictionary(ss => ss["subServiceName"].ToString(), ss => ss["status"].ToString()));

Where you can change ss => ss["status"].ToString() to select what is actually needed as subService value.


text:
Q: How to install GCC 5.4 on ubuntu 17.10 (Downgrade)? I have ubuntu 17.10.
gcc version 7.2.0 (Ubuntu 7.2.0-8ubuntu3.2)
I have to get GCC 5.4. I've tried:
 sudo apt-get install gcc-5.4

 sudo apt-get install gcc-5.4 g++-5.4

But i'm receiving :
E: Unable to locate package gcc-5.4
E: Couldn't find any package by glob 'gcc-5.4'
E: Couldn't find any package by regex 'gcc-5.4'

At apt-get install gcc I receive
    gcc is already the newest version (4:7.2.0-1ubuntu1).
I have to downgrade to 5.4,
How can I solve it? Thanks

A: You can go to the packages.ubuntu.com page for gcc-5 and you will see that eg xenial still has it: https://packages.ubuntu.com/xenial/gcc-5
Now it may just be a matter of adding the xenial repo info back into /etc/sources.list (or maybe /etc/sources.list.d/xenial.conf to easily uncomment later), run apt-get update and apt-get install gcc-5.
Another alternative is to use Docker and just run in a xenial container...

A: I work it
https://packages.ubuntu.com/bionic/amd64/gcc-5/download
in

/etc/apt/sources.list
deb http://cz.archive.ubuntu.com/ubuntu bionic main universe


text:
Q: How to remove script from page when there is no xml or phtml files? I have a Anaraky_GDRT 1.0.10 (Google Dynamic Remarketing) installed. Also I've got AMP pages set up using Design/ Matched Expression in Magento admin. AMP pages can't have any scripts on them but the way Anaraky_GDRT is made is that the script is added in app/code/community/Anaraky/Gdrt/Block/Script.php which adds the script globally. I've been adding basically blank XML files in my AMP directory to get rid of any scripts or blank phtml files.  But I can't figure a way to remove the Anaraky_GDRT script as it doesn't have any XML or phtml files in app/design/frontend/base/default/layout
Here is the script file that adds the Google Dynamic Remarketing Tag in app/code/community/Anaraky/Gdrt/Block/Script.php:
<?php
class Anaraky_Gdrt_Block_Script extends Mage_Core_Block_Abstract {

    private $_storeId = 0;
    private $_pid = false;
    private $_pid_prefix = "";
    private $_pid_prefix_ofcp = 0;
    private $_pid_ending = "";
    private $_pid_ending_ofcp = 0;

    private function getEcommProdid($product)
    {
        $ecomm_prodid = (string)($this->_pid ? $product->getId() : $product->getSku());
        $ofcp = false;
        if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE ||
            $product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_GROUPED)
        {
            $ofcp = true;
        }

        if (!empty($this->_pid_prefix) && (($this->_pid_prefix_ofcp === 1 && $ofcp) ||
            $this->_pid_prefix_ofcp === 0))
        {
                $ecomm_prodid = $this->_pid_prefix . $ecomm_prodid;
        }

        if (!empty($this->_pid_ending) && (($this->_pid_ending_ofcp === 1 && $ofcp) ||
            $this->_pid_ending_ofcp === 0))
        {
                $ecomm_prodid .= $this->_pid_ending;
        }

        return $ecomm_prodid;
    }

    private function getParams()
    {
        if ((int)Mage::getStoreConfig('gdrt/general/gdrt_product_id', $this->_storeId) === 0)
            $this->_pid = true;

        $this->_pid_prefix = Mage::getStoreConfig('gdrt/general/gdrt_product_id_prefix', $this->_storeId);
        $this->_pid_prefix_ofcp = (int)Mage::getStoreConfig('gdrt/general/gdrt_product_id_prefix_ofcp', $this->_storeId);
        $this->_pid_ending = Mage::getStoreConfig('gdrt/general/gdrt_product_id_ending', $this->_storeId);
        $this->_pid_ending_ofcp = (int)Mage::getStoreConfig('gdrt/general/gdrt_product_id_ending_ofcp', $this->_storeId);

        $inclTax = false;
        if ((int)Mage::getStoreConfig('gdrt/general/gdrt_tax', $this->_storeId) === 1)
            $inclTax = true;

        $type = $this->getData('pageType');
        $params = array('ecomm_pagetype' => 'siteview');
        switch ($type) {
            case 'home':
                $params = array( 'ecomm_pagetype' => 'home');
                break;

            case 'searchresults':
                $params = array( 'ecomm_pagetype' => 'searchresults');
                break;

            case 'category':
                $category = Mage::registry('current_category');
                $params = array(
                    'ecomm_pagetype' => 'category',
                    'ecomm_category' => (string)$category->getName()
                );
                unset($category);
                break;

            case 'product':
                $product = Mage::registry('current_product');
                $totalvalue = Mage::helper('tax')->getPrice($product, $product->getFinalPrice(), $inclTax);

                $params = array(
                    'ecomm_prodid' => $this->getEcommProdid($product),
                    'ecomm_pagetype' => 'product',
                    'ecomm_totalvalue' =>  (float)number_format($totalvalue, '2', '.', '')
                );
                unset($product);
                break;

            case 'cart':
                $cart = Mage::getSingleton('checkout/session')->getQuote();
                $items = $cart->getAllVisibleItems();

                if (count($items) > 0) {
                    $data  = array();
                    $totalvalue = 0;
                    foreach ($items as $item)
                    {
                        $data[0][] = $this->getEcommProdid($item->getProduct());
                        $data[1][] = (int)$item->getQty();
                        $totalvalue += $inclTax ? $item->getRowTotalInclTax() : $item->getRowTotal();
                    }

                    $params = array(
                        'ecomm_prodid' => $data[0],
                        'ecomm_pagetype' => 'cart',
                        'ecomm_quantity' => $data[1],
                        'ecomm_totalvalue' => (float)number_format($totalvalue, '2', '.', '')
                    );
                }
                else
                    $params = array( 'ecomm_pagetype' => 'siteview' );

                unset($cart, $items, $item, $data);
                break;

            case 'purchase':
                $order = Mage::getModel('sales/order')->loadByIncrementId(
                                Mage::getSingleton('checkout/session')
                                            ->getLastRealOrderId());

                $data  = array();
                $totalvalue = 0;
                $items = $order->getAllItems();

                foreach ($items as $item)
                {
                    $data[0][] = $this->getEcommProdid($item->getProduct());
                    $data[1][] = (int)$item->getQtyToInvoice();
                    $totalvalue += $inclTax ? $item->getRowTotalInclTax() : $item->getRowTotal();
                }

                $params = array(
                    'ecomm_prodid' => $data[0],
                    'ecomm_pagetype' => 'purchase',
                    'ecomm_quantity' => $data[1],
                    'ecomm_totalvalue' => (float)number_format($totalvalue, '2', '.', '')
                );
                unset($order, $items, $item);
                break;

            default:
                break;
        }

        return $params;
    }

    private function paramsToJS($params)
    {
        $result = array();

        foreach ($params as $key => $value)
        {
            if (is_array($value) && count($value) == 1)
                $value = $value[0];

            if (is_array($value))
            {
                if (is_string($value[0]))
                    $value = '["' . implode('","', $value) . '"]';
                else
                    $value = '[' . implode(',', $value) . ']';
            }
            elseif (is_string($value))
                $value = '"' . $value . '"';

            $result[] = $key . ': ' . $value;
        }

        return PHP_EOL . "\t" . implode(',' . PHP_EOL . "\t", $result) . PHP_EOL;
    }

    private function paramsToURL($params)
    {
        $result = array();

        foreach ($params as $key => $value)
        {
            if (is_array($value))
                $value = implode(',', $value);

            $result[] = $key . '=' . $value;
        }

        return urlencode(implode(';', $result));
    }

    private function paramsToDebug($params)
    {
        $result = '';

        foreach ($params as $key => $value)
        {
            if (is_array($value) && count($value) == 1)
                $value = $value[0];

            if (is_array($value))
            {
                if (is_string($value[0]))
                    $value = '["' . implode('","', $value) . '"]';
                else
                    $value = '[' . implode(',', $value) . ']';
            }
            elseif (is_string($value))
                $value = '"' . $value . '"';

            $result .= '
' .
                '           ' . $key . ':  	' .
                '            ' . $value . '	' .
                '
';
        }

        return $result;
    }

    protected function _toHtml()
    {
        $this->_storeId = Mage::app()->getStore()->getId();
        $gcId = (int)Mage::getStoreConfig('gdrt/general/gc_id', $this->_storeId);
        $gcLabel = trim(Mage::getStoreConfig('gdrt/general/gc_label', $this->_storeId));
        $gcParams = $this->getParams();

        $version = (string)Mage::getConfig()->getNode()->modules->Anaraky_Gdrt->version;

        $s = PHP_EOL .
            '' . PHP_EOL .
            '' . PHP_EOL .
            '' . PHP_EOL .
            '' . PHP_EOL .
            '
' . PHP_EOL .
            'paramsToURL($gcParams) . '"/>' . PHP_EOL .
            '
' . PHP_EOL .
            '' . PHP_EOL .
            '' . PHP_EOL;

        if ((int)Mage::getStoreConfig('gdrt/debug/show_info', $this->_storeId) === 1)
        {
            $lk = str_replace(' ', '', Mage::getStoreConfig('dev/restrict/allow_ips', $this->_storeId));
            $ips = explode(',', $lk);
            if (empty($ips[0]) || in_array(Mage::helper('core/http')->getRemoteAddr(), $ips))
            {
                $s .= PHP_EOL .
                    '
' . PHP_EOL .
                    '
' .
                    '
' .
                    '
Anaraky GDRT debug v.' . $version . '
	' .
                    '           Model/Controller/Action:  	' .
                    '            ' . $this->getData('pagePath') . '	' .
                    '
' .
                    $this->paramsToDebug($gcParams) .
                    '
' .
                    '
';
            }
        }

        return $s;
    }
}

So my question is how can I remove the script from my AMP pages?
Here's something I tried various combinations of but it either removes the script from every page or not:
$url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    if (strpos($url,'amp') !== true){

        $s = PHP_EOL .
            '' . PHP_EOL .
            '' . PHP_EOL .
            '' . PHP_EOL .
            '' . PHP_EOL .
            '
' . PHP_EOL .
            'paramsToURL($gcParams) . '"/>' . PHP_EOL .
            '
' . PHP_EOL .
            '' . PHP_EOL .
            '' . PHP_EOL;
    }

A: I think this is wrong if (strpos($url,'amp') !== true). strpos returns the position of a string or false if not found.
Please try this instead:
if (strpos($url,'amp') === false) {
    ...
}


text:
Q: Obtaining groups and counts at the same time Suppose my table looks like this:
Name City Salary
n1   c1   10
n1   c1   20
n1   c1   30
n2   c2   20
n2   c2   50
n3   c2   70

And I am interested in the following output:
Name Count
n1   3
n2   2
n3   1

I am fairly new to SQL and have been doing similar commands in SAS (e.g. in this case I would have used PROC FREQ) - but I am now required to write the same code only in the SQL language (I am using Aginity Netezza).

A: If its MySQL, or any fairly standard SQL:
SELECT Name, Count(*)
FROM table
GROUP BY Name


text:
Q: Bad Operand types for binary operator && when trying to calculate birthdate from current date I am trying to get a user to input YR MON DAY and then system calculate the current age based on the provided input and show the age on the screen.
Here is the beginning to my code:
static void checkAgeFormat(int current_date, int current_month,
                            int current_year, int birth_date,
                            int birth_month, int birth_year) {
    int f = 0;
    if(current_date <= 01 && current_date => 31) {
        System.out.println("Invalid current_date");
        f = 1;
    }

I am getting a "Bad Operand types for binary operator &&" I cannot figure out why, and I am fairly new to coding.
Thanks for any help

A: It is >= not => so  if(current_date<=1 && current_date>=31)
(don't use 0 as prefix for numbers, it causes them to be interpreted as octal)

A: What are you trying to return here? The amount of days left before someones birthdate? You could use the between() method of Period class for that.
static void checkAgeFormat(int current_date, int current_month,
                            int current_year, int birth_date,
                            int birth_month, int birth_year) {
LocalDate birthDate = LocalDate.of(birth_year, birth_month, birth_date);
long daysLeft = Period.between(LocalDate.now(), birthDate).get(ChronoUnit.DAYS);

}

A: As I have already mentioned in the comment, the issue is because of the bad symbol, => for the operator. It should be >=. Check this to learn more about operators.
Apart from that, I can see a serious problem with your logic. The way you are validating the date values is a naive way to do it. I suggest you do it using OOTB APIs as shown below:
import java.time.DateTimeException;
import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        // Tests
        checkAgeFormat(45, 10, 2017, 10, 10, 2010);
        checkAgeFormat(30, 2, 2017, 10, 10, 2010);
        checkAgeFormat(31, 4, 2017, 10, 10, 2010);
        checkAgeFormat(30, 15, 2017, 10, 10, 2010);
        checkAgeFormat(30, 4, 2020, 10, 10, 2010);
    }

    static void checkAgeFormat(int current_day, int current_month, int current_year, int birth_day, int birth_month,
            int birth_year) {
        int f = 0;
        LocalDate currentDate, birthDate;
        try {
            currentDate = LocalDate.of(current_year, current_month, current_day);
            birthDate = LocalDate.of(birth_year, birth_month, birth_day);
            System.out.println("If you see this line printed, the date values are correct.");
            // ...Rest of the code
        } catch (DateTimeException e) {
            System.out.println(e.getMessage());
            f = 1;
        }
        // ...Rest of code
    }
}

Output:
Invalid value for DayOfMonth (valid values 1 - 28/31): 45
Invalid date 'FEBRUARY 30'
Invalid date 'APRIL 31'
Invalid value for MonthOfYear (valid values 1 - 12): 15
If you see this line printed, the date values are correct.

A: isn't it easier to write a function where the user will provide year, month and the day and it will return how old is the user? Below is an example of a function that does it.
public static int getYears(int year, int month, int day)
{
    LocalDate yearOfBirth = LocalDate.of(year, month, day);
    LocalDate currentDate = LocalDate.now();
    Period period = Period.between(yearOfBirth, currentDate);
    return period.getYears();
}

A: you are getting the error because
you are using if (current_date <= 01 && current_date =>31) instead of
if (current_date <= 01 && current_date >=31)

after editing your code will be:
static void checkAgeFormat(int current_date, int current_month, int current_year, int birth_date, int birth_month, int birth_year) {

        int f=0
        if (current_date <= 01 && current_date >=31){
            System.out.println("Invalid current_date");
            f=1;
        }
}


text:
Q: ColdFusion shopping cart Update: I'm rewriting with all my code for each page as well as my error message... keep in mind I am very new and honestly don't know some of this code...
productlist.cfm 1st page: (hard coded product list code built from select statement)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <meta name="viewport" content="width=device-width, initial-scale=1">
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <link rel="stylesheet" href="http://students.uwf.edu/jeb48/css/style.css" type="text/css" />
 <link rel="stylesheet" href="http://students.uwf.edu/jeb48/css/style.css" type="text/css" />
 <link rel="stylesheet" href="http://students.uwf.edu/jeb48/css/bootstrap.css" type="text/css" />
 <link rel="stylesheet" href="http://students.uwf.edu/jeb48/css/bootstrap-theme.min.css" type="text/css" />
 <link rel="stylesheet" href="http://students.uwf.edu/jeb48/css/bootstrap.min.css" type="text/css" />

 <title>Scuba Diving is Fun!</title>

<cfquery name = "getlist" datasource="jeb48_shoppingcart">
 SELECT ProductID, ProductName, ProductQty, ProductPrice, ProductDescription, ProductPhoto
 FROM Products;
</cfquery>

Product Photo

Product ID

Product Name

Quantity in Inventory

Product Description

Unit Price

          <cfoutput query ="getlist">

#getlist.ProductPhoto#

#getlist.ProductID#

#getlist.ProductName#

#getlist.ProductQty#

#getlist.ProductDescription#

#DollarFormat(getlist.ProductPrice)#
            <cfif #getlist.ProductQty# gt 0>

Add to Cart
            <cfelse>

Out of Stock!
            </cfif>

          </cfoutput>

scart.cfm Page 2: This is the page I'm having trouble with... I know my code is messed up but I do not know how to fix it... the error I'm getting is on this page... the error is "Parameter validation error for the ARRAYAPPEND function." I'm trying to build a cart based on the link in the previous page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <meta name="viewport" content="width=device-width, initial-scale=1">
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <link rel="stylesheet" href="http://students.uwf.edu/jeb48/css/style.css" type="text/css" />
 <link rel="stylesheet" href="http://students.uwf.edu/jeb48/css/bootstrap.css" type="text/css" />
 <link rel="stylesheet" href="http://students.uwf.edu/jeb48/css/bootstrap-theme.min.css" type="text/css" />
 <link rel="stylesheet" href="http://students.uwf.edu/jeb48/css/bootstrap.min.css" type="text/css" />
 <link rel="stylesheet" href="http://students.uwf.edu/jeb48/css/style.css" type="text/css" />

 <title>Scuba Diving is Fun!</title>

Your Shopping Cart

        <cfparam name="url.productid" default="">
        <cfparam name="url.qty" default="">
        <cfquery name = "getCartItem" datasource="jeb48_shoppingcart">
           SELECT ProductID, ProductName, ProductQty, ProductPrice, ProductDescription, ProductPhoto
           FROM Products
           WHERE ProductID = #url.productid#;
        </cfquery>

        <cfset arrShoppingCart = arrayNew(1) />
        <cfparam name="session.cart" default="arrayNew()">
        <cfset arrayAppend( "session.cart", structNew() )>
        < cfset session.cart = arrayNew(1) >
        < cfset thisCartItem = arraylen( session.cart )>
        <cfset arrayAppend( session.cart, structNew() )>
        < cfset thisCartItem = arraylen( session.cart )>
        < cfset session.cart[thisCartItem].itemID = url.productid>
        < cfset session.cart[thisCartItem].quantity = url.qty>

application.cfc
<cfcomponent>
<cfset this.name = "jeb48SC">
<cfset this.datasource = "jeb48_shoppingcart">
<cfset this.loginstorage="Session">
<cfset this.sessionmanagement="Yes">
<cfset this.sessiontimeout="#createtimespan(0,0,45,0)#">
</cfcomponent>

Once I get this working I can begin working on getting the output built... thanks for taking a look.

A: The details of the question have significantly changed, so editing my answer.

  1:  <cfset arrShoppingCart = arrayNew(1) />
  2:  <cfparam name="session.cart" default="arrayNew()">
  3:  <cfset arrayAppend( "session.cart", structNew() )>
  4:  < cfset session.cart = arrayNew(1) >
  5:  < cfset thisCartItem = arraylen( session.cart )>
  6:  <cfset arrayAppend( session.cart, structNew() )>
  7:  < cfset thisCartItem = arraylen( session.cart )>
  8:  < cfset session.cart[thisCartItem].itemID = url.productid>
  9:  < cfset session.cart[thisCartItem].quantity = url.qty>

There are a few problems with this code. I'll ignore the spaces after some opening brackets, you're clearly experimenting and canceling out some experiments.

*

*On line 2, you're not creating an array, you're creating a string with the default value of "ArrayNew()". You need to add hashes around each end. "#ArrayNew()#".

*On line 3, you have the array name quoted, which is invalid. Most cold fusion functions that require a variable name, want it unquoted. Some exceptions are StructkeyExists() and isDefined(), which serve similar purposes. They check if a variable exists so they ask for the variable name as a string, rather than raw.

*Line 4, this is how you properly set an array. Good Job. The only thing is every time someone visits this page, this happens. This line should be when a session is first initiated and it should go something like this <cfif not isDefined("session.cart")><cfset session.cart=ArrayNew(1)></cfif>.

*As I said before, you need to maintain data types across your application. One quick fix is to address your code problems and then create a page that has nothing but this <Cfset structclear(session)>. That gets rid of all your old session data.

*You're on the right track after this. It can be tough when you're trying to debug something that you don't (yet!) understand several aspects of, but you'll get it.

Okay something else we need to talk about. You're new to CF? That's great, time to start an important habit early.
Any Time you're using a #variable# in a query, use a tag called <cfqueryparam. There's a mischievious thing called SQL injection, where a user can modify a url to cause havoc on the website. This tag is your primary defense against this
(There are occasions where some people don't feel it's necessary but you really cannot over-param your variables and as you're new, it's better to be safe than sorry).
Suppose I'm on scart.cfm?productID=7. If I change the url to scart.cfm?productID=7; DROP TABLE Products, your products table disappears. Or maybe I just want cheap goodies. scart.cfm?productID=7; UPDATE Products SET PRICE = 1 (I'd have to guess at column names here), but I could reset all your product prices.
Further CFQueryParam makes your queries slightly faster, and one of my favorite parts, is that when you provide the type, it handles the quoting for you.
Adobe was a bit silly when designing the tag and it's a little long-winded, but you get used to it.
You query above should look like this:
   <cfquery name = "getCartItem" datasource="jeb48_shoppingcart">
       SELECT ProductID, ProductName, ProductQty, ProductPrice, ProductDescription, ProductPhoto
       FROM Products
       WHERE ProductID = <cfqueryparam cfsqltype="cf_sql_integer" value="#url.productID#">
    </cfquery>

Oh, because you're using this.datasource in application.cfc, providing a datasource here is not necessary. so your queries can just look like, which makaes your application more mobile.
<cfquery name="..."> or <cfquery> for queries where name isn't useful.

If you ever find yourself using additional datasources, you can store their names in the request scope, and then you can reference them like datasource="#request.db1#" or #request.db2#', etc. There are some applications people have designed that might have particular users using different databases so they have setups like #session.db#.
If I was searching for something by say a string value, the where could look like this WHERE ProductID = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.productName#'>
See, the tag takes care of the quoting, and it lets other developers know your data types at a glance.

In the future, please provide more of the error.
From what you've shown, it looks like either:

*

*A cfparam declares session.sCartItems somewhere, probably as a basic string. (<cfparam name="session.sCartItems" default=""> which basically just says, "If not defined, define it". In other words, a cfparam on a variable will make an isDefined() check pass.

*In development, you've formerly declared session.sCartItems as a string, and that action is still alive. If that is the case, the not-isDefined() check fails, and the variable is not re-set as an array.

You should resolve the source of this problem. Data types of variables should remain consistent across your application, otherwise you will always constantly be trying to check data types.
However, changing this should bandaid-fix your problem.
<cfif not isDefined("session.scartItems")>

to:
<cfif not isDefined("session.scartItems") or not isArray(session.sCartItems)>

The way this is works is if your variable is not defined, the check stops there. If you variable is defined, the check continues to verify that it is an array.


text:
Q: np.piecewise() acting up with use of math.pow()? I've been trying to get numpy.piecewise to convert a list of coefficients {a_ij} into a piecewise cubic polynomial. Whenever I run the following code,
import math
import numpy as np

x = np.linspace(0.1,9.9,100)
a = [[i] * 4 for i in range(10)]
x_i = [0,1,2,3,4,5,6,7,8,9,10]
condlist = [(x[i] < x)*(x<x_i[i+1]) for i in range(len(x_i)-1)]
funclist = [lambda y: sum([a[k][j] * math.pow(y - x_i[k],j) for j in range(4)]) for k in range(len(a))]
print np.piecewise(x, condlist, funclist)

I get the error
...line 730, in piecewise
y[condlist[k]] = item(vals, *args, **kw)
File "test", line 8, in <lambda>
funclist = [lambda y: sum([a[k][j] * math.pow(y - x_i[k],j) for j in range(4)]) for k in range(len(a))]
TypeError: only length-1 arrays can be converted to Python scalars

The error goes away, however, if and only if I get rid of math.pow(). For some reason, having funclist pass x into math.pow() is what breaks everything.
What's going on? How can I fix this?

A: The functions in the math module expect numeric scalars as arguments. They don't expect NumPy arrays. The functions in funclist are being passed a NumPy array, y.
So math.pow(y-constant, j) is raising a TypeError:
In [22]: y = np.arange(5)
In [31]: math.pow(y - 1, 2)
TypeError: only length-1 arrays can be converted to Python scalars

Use np.power instead of math.pow:
funclist = [lambda y: ([a[k][j] * np.power(y - x_i[k],j) for j in range(4)]).sum()
            for k in range(len(a))]

Note: instead of using the Python sum function, you should also call the NumPy sum method for better performance.


text:
Q: How do I parse my JSON with external middleware now that Express doesn't carry a body parser? How do I parse my JSON with external middleware now that Express doesn't carry a body parser?
For a while, I was using Express bodyParser to receive and respond to JSON posts to the server. Each time I started up the server, express said something about bodyParser being removed soon, and sure enough, I've updated and now JSON requests seem to be showing null.
So I didn't understand how middleware worked, and had followed an express tutorial to use the body parser. Now, using separate body parser middleware, it seems I'm doing it wrong.
Before, my syntax was:
app.use(express.bodyParser());

Now, with the module body-parser as middleware, it's like this:
app.use(bodyParser.json());

And an example as a whole:
var express = require('express');
var bodyParser = require('body-parser');

var app = express();

function listen() {

    app.use(bodyParser.json());
    app.post('/login', function (req, res) {

        var username = req.body.username;
        var password = req.body.password;
        console.log('User ' + username + ' is attempting login...');
        validate(username, password, function (err, result) {

            if (err) loginFail(req, res, err);
            else loginSucceed(req, res, result);

        });
    });

    app.listen(3333);

}

listen();

I tried express.json() as the middleware, but that triggers the fatal error:

Error: Most middleware (like json) is no longer bundled with Express
and must be installed separately. Please see
https://github.com/senchalabs/connect#middleware.

That link leads to the body-parser middleware that I'm using via app.use(bodyParser.json()).

Update:
Using bodyParser.json() results in no error, but the data values are null:

User undefined is attempting login...

My client code should be fine, but here it is for completeness:
function sendLogin() {

    popLogCreds(creds);

    var loginCredentials = {

        "username": creds.username,
            "password": creds.password

    };

    console.log("Sending login credentials: " +
    JSON.stringify(loginCredentials, null, 4));

    request = $.ajax({

        url: "http://54.186.131.77:3333/login",
        type: "POST",
        crossDomain: true,
        data: loginCredentials,
        dataType: "json",
        error: function () {

            postError("Uh Oh! The Officeball server is down.");

        },
        success: function (data) {

            var ParsedData = data;

            sessionStorage.username = creds.username;
            sessionStorage.password = creds.password;
            sessionStorage.fname = ParsedData.fname;
            sessionStorage.lname = ParsedData.lname;
            sessionStorage.rank = ParsedData.rank;

            console.log(sessionStorage);

            window.location.replace("app.html");

        }

    });

}

Which results in:

Sending login credentials: {
    "username": "jonathan@evisiion.com",
    "password": "J******!"
}

And then the result is the POST's error output, which is, as above:

error : function () {
                  postError("Uh Oh! The Officeball server is down.");
              }

Don't take that error message literally. Just means an error happened. The server is, in fact, getting that request, as shown up above.

A: By default, $.ajax() sends data URL-encoded as mentioned in the description of the processData option:

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded".

The body-parser that corresponds to that Content-Type and format is urlencoded():
app.use(bodyParser.urlencoded());

If you'd rather use JSON for the request, you'll need to provide the data already formatted as such along with a matching contentType that bodyParser.json() recognizes:
request = $.ajax({

    url: "http://54.186.131.77:3333/login",
    type: "POST",
    crossDomain: true,
    data: JSON.stringify(loginCredentials),
    contentType: 'application/json',
    dataType: 'json'

    // ...
});

Note for cross-domain: With these modifications, the server will have to handle preflight OPTIONS requests for the route.

And, note that a bodyParser isn't needed for HEAD or GET requests as the data is included in the URL rather than the body. Express parses that separately into req.query.

A: In your node code,
make sure you put these two lines of code
var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());

......then your other code follows..
enjoy...


text:
Q: Android: setRequestProperty function of URLConnection, what does this method do? Although I know that StackOverflow has already setRequestProperty function of HttpURLConnection question, I really don't understand what this method does. I cannot "step into" it (F7) when debugging. I pressed Ctrl-B to view the method's body, but it only has the following code:
public void setRequestProperty(String field, String newValue) {
        checkNotConnected();
        if (field == null) {
            throw new NullPointerException("field == null");
        }
    }

and checkNotConnected:
private void checkNotConnected() {
        if (connected) {
            throw new IllegalStateException("Already connected");
        }
    }

I mean that where is the code that puts the value to the field? Any explanation is appreciated.
UPDATE (2015/08/08):
I have found the way to view its implementation. Since it's abstract, must use Ctrl-Alt-B instead of Ctrl-B to view.

A: I guess you are accessing the wrong way, or have some kind of protected code...
The original function is this:
/**
 * Sets the general request property. If a property with the key already
 * exists, overwrite its value with the new value.
 * ...
 */
public void setRequestProperty(String key, String value) {
    if (connected)
        throw new IllegalStateException("Already connected");
    if (key == null)
        throw new NullPointerException ("key is null");

    if (requests == null)
        requests = new MessageHeader();

    requests.set(key, value);
}

Where requests.set(key, value) do what you're asking for :)!

A: this is back source code of setRequestProperty()
Sets the general request property. If a property with the key already exists, overwrite its value with the new value.
NOTE: HTTP requires all request properties which can legally have multiple instances with the same key to use a comma-seperated list syntax which enables multiple properties to be appended into a single property.
Parameters:
key the keyword by which the request is known (e.g., "accept").
value the value associated with it.
Throws:
java.lang.IllegalStateException
if already connected
java.lang.NullPointerException
if key is null
See also:
getRequestProperty(java.lang.String)
 public void setRequestProperty(String key, String value) {
    if (connected)
       throw new IllegalStateException("Already connected");
   if (key == null)
        throw new NullPointerException ("key is null");

    if (requests == null)
        requests = new MessageHeader();

   requests.set(key, value);
   }

Source Link

A: I have found the way to view its implementation. Since it's abstract, must use Ctrl-Alt-B instead of Ctrl-B to view.

And the back source code of setRequestProperty as the following (inside jre\lib\rt.jar):
public void setRequestProperty(String var1, String var2) {
        if(this.connected) {
            throw new IllegalStateException("Already connected");
        } else if(var1 == null) {
            throw new NullPointerException("key is null");
        } else {
            if(this.isExternalMessageHeaderAllowed(var1, var2)) {
                this.requests.set(var1, var2);
            }
        }
    }


text:
Q: Can't convert TensorFlow saved model to tfjs_layers_model webmodel I am trying to convert TensorFlow saved model to tfjs webmodel, but it gives a ValueError.
The code I used can be found here.
I have pretrained models in mobilenet/saved_model, .ckpt, .meta, .index, and checkpoint files.
tensorflowjs_converter     --input_format=tf_saved_model  --output_format=tfjs_layers_model   --signature_name=serving_default     --saved_model_tags=serve mobilenet/saved_model/ mobilenet/web_model/
Traceback (most recent call last):
  File "/home/shiva/.local/bin/tensorflowjs_converter", line 11, in <module>
    sys.exit(main())
  File "/home/shiva/.local/lib/python2.7/site-packages/tensorflowjs/converters/converter.py", line 373, in main
    (input_format, output_format))
ValueError: Unsupported input_format - output_format pair: tf_saved_model - tfjs_layers_model


text:
Q: C++ Template operator overload I'm writing a template matrix class, and I am a bit confused as to how overloading the * operator would work.
I would want to overload something like this (omitting irrelevant code):
template<typename T>class Matrix4t
{

friend vector3 operator*(const vector3 &inputV3, const matrix4t &inputM4t);

template <typename scalarT>
friend scalarT operator*(const scalarT &inputSclT, const matrix4t &inputM4t);

public:
const matrix4t operator*(const matrix4t)

vector3 operator*(const vector3 &inputV3);

template <typename scalarT>
const matrix4t operator*(const scalarT&);

}

Assuming correct definitions for the individual multiplications I assume this should allow multiplication of my matrix object with an object of type vector3 from both sides of the operand, returning a vector3 each time. Also it should allow multiplication of my matrix with a scalar template value, which could be float, double etc. The definitions of these methods would need to be different, to allow for vector vs scalar multiplication, hence not just using the template for both
On using this operator with a vector3 though, would the compiler know to use the explicitly declared vector3 method, or would it try and create the templated version of the method, which would not work as the definition is written to only allow for a scalar value, and probably also then complain about method redefinition.
Any thoughts on if this would work, or how else I could go about it?
Cheers

A: I have the feeling that you might be aiming for a more complex solution than needed, so I will start building from the ground up, and leave some details for later. First I will start analyzing your proposed syntax and what it means.
friend vector3 operator*(const vector3 &v, const matrix4t &m);
template <typename scalarT>
friend scalarT operator*(const scalarT &inputSclT, const matrix4t &inputM4t);

These are friend declarations. Friend declarations declare (tell the compiler that there is) an entity external to the class and that such an entity should be granted full access to the internals of this class (which in this case is a template). The second friend declaration is of a free function template operator* that takes a scalarT type and a matrix4T<T> object both by const reference and yields an scalarT value. This friend declaration seems strange in that the multiplication of a matrix by a scalar value usually yields another matrix of the same dimensions, rather than just a scalar value.
Note that inside the class template, the name of the template matrix4t does not refer to the template, but the particular specialization (i.e. it represents matrix4t<T>, not the name of the template). The distinction might not seem important now, but sooner or later you will realize the importance of it.
The second declaration is of a non-templated free function operator* that takes a vector3 and a matrix4t both by const reference and yields another vector3. Since we are inside the definition of the matrix4t, the name of the template refers to the specialization matrix4t<T>, but vector3 refers just to the template, and not any particular instantiation. You should either make that a template that accepts vector3<U> for any given type U, or else a non-templated function that accepts a single type (which can be the T argument of our template): vector3<T>. In the same way as with the other declaration, the return value might be off or not... depends on what are the dimensions of the vector (is it row or column?)
Regarding the actual befriending, I recommend that you read this answer to a different similar question.
As of the actual operators, for the scalar type, I would suggest the following approach:

*

*Implement operator*= taking the scalar of the same type as is stored as an argument

*Implement both versions of operator* in terms of operator*=
.
template <typename T> class matrix4t {
public:
    matrix4t& operator*=( T scalar ); // and implement
    friend matrix4t operator*( matrix4t lhs, T scalar ) {
       return lhs*=scalar;
    }
    friend matrix4t operator*( T scalar, matrix4t rhs ) {
       return rhs*=scalar;
    }
};

Notes: operator*= is implemented once, taking the matrix as left hand side (you could also offer an overload taking the matrix as right hand side, but it would look a bit strange: 5 *= matrix yielding a matrix...). Implement operator* as free functions (friendship is only used to provide the free function for each instantiating type, read the linked answer), by forwarding to operator*=.
For the case of multiplying by a vector (and because it is not symmetric) the trick of dispatching to a single implementation will not work, but you can provide the two implementations as non-templated friends as above.
If you wanted to provide operations with mixed types, then all of the above would have to be templates. The added complexity is not the template, but rather determining what the result types should be if you want to promote the types. With C++11 the easiest way would be using decltype and trailing return types:
template <typename U>
friend auto operator*( matrixt4 lhs, U scalar ) -> matrix4t< decltype(scalar * element(0,0) ) > {
   // implement here
}

And similarly for operator*(scalar,matrix). Note that if you are promoting types, operator*= might not make sense at all (as the type would be the same as the lhs), or if it did, it might or might not produce the result that you want. If you consider doing it, the operator+ would have to take the matrix4t<A> argument by reference (as it might not be of the appropriate type) and copy into the matrix4t<B> return type (where A and B are respectively the types of the matrix being multiplied and the result).
From here on, you should decide what you need or want to implement, and you might want to ask more specific questions as they come by.


text:
Q: simultaneous linear congruences- Chinese remainder theorem    T ≡ 126 mod 1293
   T ≡ 0 mod 3936

hi ive tried to solve this using the CRT existence constructive proof but 1293*207 + 3936*-68 =3
then i used x = (a1*m1*n1) + (a2*m2*n2)
and  (0*1293*207) + (126*3936*-68) i checked the solution and answer was wrong so im not sure what to do from here

A: $3\mid T\ $ so it's equivalent to $\ T/3\equiv 42\pmod{431};\,\ T/3\equiv 0\pmod{1312},\ $ with solution
$\ T/3 \equiv \color{}{42\cdot 1312} (1312^{-1}\bmod 431)\equiv \color{#c00}{42\cdot 1312}(-68)\equiv 211232\pmod{\ \ 431\cdot 1312}$
Scaling  the prior comgruence by $3$ yields the solution: $\ T \equiv 633696\pmod{1293\cdot 1312}$
Your mistake is that you effectively scaled twice by $3$ instead of once as above, i.e. you multiplied both $\,\color{#c00}{42}\,$ and $\,\color{#c00}{1312}\,$ by $3$ in your formula $\, \color{#c00}{126\cdot 3936}(-68).\,$


text:
Q: How to post message on Facebook Wall with offline access I am trying to send message from my asp.net website running on localhost with offline access.
Can I post data on fb wall when my asp.net web-site is running on localhost is so then please provide me some solution.
I have tried using graph api provided by facebook on developers.facebook.com and I am sending code from sever-side.

A: The permission named Offline Access has been deprecated.
You can do so by creating a facebook app.
When configuring, your app's permissions should include the permission to post on behalf of your user (publish_stream should do).
Give the app permission for your user - visit https://apps.facebook.com/{your_app_name_or_id}/, you will be asked to allow the app certain permissions regarding your user. Allow.
Obtain the app's token.
Access the graph API using the token you received. One way (should make it easier, I hadn't a chance to go over it thoroughly myself) is using CS SDK.


text:
Q: Internationalization in a monorepo I have an app (just frontend) whose code is structured in a monorepo. There are separate packages for each custom widget. I would also like to have one package with all the translations. In this way, if another package need a translation I just need to import that package. So I created the translation package and in its main file I just wrote (here I use intl):
export 'package:flutter_gen/gen_l10n/app_localizations.dart';

Now, if I import that package in another package and I import the file with:
import 'package:l10n/l10n.dart';

It tells me that that import is not used and gives me error when I use the translation with AppLocalizations.of(context)!.foo

A: If you use VScode (don't know for other editors) you have to manualy import the generated translation package:
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

A: It seems that it's not possible to export generated file by design (check out this github issue). The best solution that I've found to fix my problem is the following:

*

*Create a translation package inside your project, like in packages/translations and add that package to the pubspec.yaml of your your main project. Like this:

dependencies:
  flutter:
    sdk: flutter
  translations:
    path: packages/translations

*In that package create a l10n.yaml file like this:

arb-dir: lib
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
synthetic-package: false

*If you are working in a git repo, add packages/translations/lib/app_localizations*.dart in your .gitignore

*Now if you run flutter packages get && flutter gen-l10n in that translations packages all the translations  will be automatically generated (assuming they are in packages/translations/lib/app_xx.arb)

*Now you can import the translation file from you main package with import 'package:translations/app_localizations.dart';
The only drawback is that the translations are not automatically generated when you type flutter pub get (see this issue). In order to regenerate them you have to type flutter gen-l10n inside the translations package every time. The solution could be improved by using a tool for managing Dart monorepo projects like melos.
An example implementation of what I described (including melos) could be found in this github repo


text:
Q: Updating a manually compiled unix programme with new version? I want to update a version of a program I have previously compiled manually to /opt. Can I just compile the new version and let it overwrite its previous install (Assuming there are no compatibility issues) or is this bad practice?
I'm doing this on a server that is completely backed up; so worst comes to worst I can reimage.

A: It really depends on the program and the differences between versions, and how it's installation process works.  If, for example, you configure it with different settings, which resulted in different sets of modules being built in a program that supports external dynamic modules (Apache, heartbeat, ProFTPd, etc...), there may be modules left in the directories which are built against the old version.
Config files may also be overwritten or new config files not written, depending on the install process.  This has most often bitten me with postfix, where new services are required in the master.cf, but Postfix helpfully provides a tool to fix these instances.
Personally, in the rare cases where I manually install software (rather than using distribution packages), I try to get them in a directory named based on the version, and then create a symbolic link from the generic name to the specific name.  That way I can install the new version in a completely new directory.  Otherwise, it's probably a good idea to move the old directory out of the way, say renaming it to ".old", and then do the reinstall.

A:
Can I just compile the new version and let it overwrite its previous
  install (Assuming there are no compatibility issues) or is this bad
  practice?

Yep, you should be just fine. Binaries get over-written all of the time, sometimes due to manually-compiled packages, but more frequently because of yum/apt/etc. binary package updates.

A: Normally yes. The makefile might provide a "clean" option to uninstall the old binaries.
If you plan to do this often - learn how to build proper packages and use the package-install-options to install/update to new versions or releases.


text:
Q: ZFS Scrub does not finish but repeats over and over again Lately when running a zpool scrub mypool it gets to about 96% and then it resets to 0% and starts again, I waited to see what it would do again and the same thing happened it resets back to 0%. The last time (back in March) I aborted the scrub and thought nothing about it.
I tried it again today after updating my pool to the latest version and have upgraded to Ubuntu 22.04 and its still doing the same thing, its a bit strange, hope someone has an answser.. is there something else I need to do?


text:
Q: Using material design in pre 5 android devices I use android studio and I want to use material design features in API lower than 21.
First of all I read these questions:
how to use material design features in api lower than 21 in eclipse?
I want Material Design in Pre 5.0 device in eclipse
Android Design Support Library And Material Design Backwards Compatibility?
And also I read these:
https://developer.android.com/training/material/compatibility.html
https://developer.android.com/tools/support-library/features.html#v7-appcompat
Also I used this tutorial to create a compatible material design project:
http://www.androidhive.info/2015/04/android-getting-started-with-material-design/
I added this library: com.android.support:appcompat-v7:21.0.0 and i used material themes like the previous link but I couldn't see any material feature in my android 4.2.2. As I find out from google developer it uses compatibility to show material feature in API 21 and it still works without material feature in android lower than 21.
So how can I use material features for android lower than 21?
My gradle is like this :
    apply plugin: 'com.android.application'

    android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "test.parsoa.com.newmaterial"
        minSdkVersion 17
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile "com.android.support:appcompat-v7:21.0.0"
}

A: At first update your dependencies like :
dependencies {
    compile "com.android.support:appcompat-v7:22.2.1"
    compile 'com.android.support:design:22.2.1'  // with this dependency you can use material design components pre api 21
}

Just take a look at http://android-developers.blogspot.de/2015/05/android-design-support-library.html


text:
Q: Typescript generic abstract class - Why doesn't this abstract method inherit the class type? I come from a background in C# and I'm currently trying to get my head around Typescript. I've run in to the following issue while creating a generic abtract class in Typescript, and I'm not sure if it's a problem with my implementation, or a limitation of the language:
Given the following abstract class, and class extending it:
abstract class Filter<T> {
    value T;
    abstract apply<T>(items: T[]): T[];
}

class StringFilter extends Filter<string> {
    apply(items: string[]) {
        return items.filter(i => this.value === i);
    }
}

I get the following error:
Property 'apply' in type 'StringFilter' is not assignable to the same property in base type 'Filter<string>'.
Type '(items: string[]) => string[]' is not assignable to type '<T>(items: T[]) => T[]'.

In C# I would have expected the apply method to share the same generic type as the class, but in Typescript this doesn't seem to be the case.
How can I make sure that a type of Filter<string> has an apply method of type (items: string[]) => string[]?

A: You need to remove the <T> from the abstract apply method.

How can I make sure that a type of Filter has an apply method of type (items: string[]) => string[]?

Well, you're already doing that. The definition of the abstract method "apply" is already ensuring your request.
Setting the abstract class as generic, all the methods/props defined will inherit the T specification in the concrete class.

A: You don't need to provide the generic parameter to apply. The following modification of your code compiles without issues.
abstract class Filter<T> {
    value: T;
    abstract apply(items: T[]): T[];
}

class StringFilter extends Filter<string> {
    apply(items: string[]) {
        return items.filter(i => this.value === i);
    }
}


text:
Q: PdfStamper not adding new text to assisting PDF I am trying to add new text to an existing PDF file but it is not adding. From the code below it doesn't show any error but the text is not added.
I have also looked at some examples below
Example1
Example2
Can you please guide me if there's something I am not doing it right?
This is the code am using to write text to the pdf.
      else
        {
            if (document.State != DocumentState.Signed)
                document.State = DocumentState.Signed;

            document.ActionedUser = user;
            document.ActionDate = DateTime.Now;

      //this return bytes and it changes to document.SignedFileData = memoryStream.ToArray() and that makes it to loose original data
            document.SignedFileData = response.Document.SignedFileBytes;
            #region

            int numberOfPages;

            // create a MemoryStream to write the stamping result to
            using (MemoryStream memoryStream = new MemoryStream())
            {
                //create PdfReader object to read from the existing document
                using (PdfReader reader = new PdfReader(document.EditedFileData))
                // create a PdfStamper object to manipulate the PDF in the reader and write to the MemoryStream
                using (PdfStamper stamper = new PdfStamper(reader, memoryStream))
                {
                    numberOfPages = reader.NumberOfPages;
                    reader.SelectPages("1-100");

                    // PdfContentByte from stamper to add content to the pages over the original content
                    PdfContentByte pbover = stamper.GetOverContent(numberOfPages);
                    iTextSharp.text.Font font = new iTextSharp.text.Font(null, 10, iTextSharp.text.Font.NORMAL, BaseColor.RED);

                    string FisrtName = "Testing";
                    string Position = "Testing";
                    string Signature = "Testing"; ;
                    string SignatureDate = DateTime.Now.ToString();

                    ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(FisrtName, font), 240, 715, 0);
                    ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(Position, font), 230, 628, 0);
                    ColumnText.ShowTextAligned(pbover, PdfContentByte.ALIGN_LEFT, new Phrase(Signature, font), 230, 600, 0);
                    ColumnText.ShowTextAligned(pbover, PdfContentByte.ALIGN_LEFT, new Phrase(SignatureDate, font), 230, 574, 0);
                }
            }

            #endregion
            // Store the manipulated PDF in the EditedFileData property
            document.SignedFileData = memoryStream.ToArray();

            Context.SaveChanges();
            return new SignatureSoapResponse() { Success = true, Message = document.Id.ToString() };
        }

PDF Table

A: In the course of the comments it turned out that the manipulated PDF is to be stored in the EditedFileData property of the PDFFile document.
The OP's code instead stored the result PDF somewhere in the file system using weird names:
new FileStream(Convert.ToBase64String(document.EditedFileData), FileMode.Create))

This target stream of the PdfStamper takes the current content of the document.EditedFileData property, base64 encodes it, and uses it as name of a file in the file system to which the PDF is written.
To store the manipulated PDF in the document.EditedFileData property, one should instead use a MemoryStream as target stream of the PdfStamper and eventually put the memory stream contents into the property in question, i.e.:
// create a MemoryStream to write the stamping result to
using (MemoryStream memoryStream = new MemoryStream())
{
    //create PdfReader object to read from the existing document
    using (PdfReader reader = new PdfReader(document.OriginalFileData))
    // create a PdfStamper object to manipulate the PDF in the reader and write to the MemoryStream
    using (PdfStamper stamper = new PdfStamper(reader, memoryStream))
    {
        numberOfPages = reader.NumberOfPages;
        reader.SelectPages("1-100");

        // PdfContentByte from stamper to add content to the pages over the original content
        PdfContentByte pbover = stamper.GetOverContent(numberOfPages);
        iTextSharp.text.Font font = new iTextSharp.text.Font(null, 16, iTextSharp.text.Font.BOLD, BaseColor.RED);

        string FisrtName = "Director1";
        string Position = "Director1";
        string Signature = "Director1";
        string SignatureDate = DateTime.Now.ToString();

        ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(FisrtName, font), 230, 650, 0);
        ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(Position, font), 230, 628, 0);
        ColumnText.ShowTextAligned(pbover, PdfContentByte.ALIGN_LEFT, new Phrase(Signature, font), 230, 600, 0);
        ColumnText.ShowTextAligned(pbover, PdfContentByte.ALIGN_LEFT, new Phrase(SignatureDate, font), 230, 574, 0);
    }

    // Store the manipulated PDF in the EditedFileData property
    document.EditedFileData = memoryStream.ToArray();
}