text:
Q: How to turn a permutations function into a lazy generator? I am trying to get all of the permutations of an array, one permutation at time, using a generator.
This is the original code (which works as intended and returns an array of permutations), and below is my attempt to change it:
function permutations(iList, maxLength) {
        const cur = Array(maxLength)
        const results = []

        function rec(list, depth = 0) {
            if (depth === maxLength) {
                return results.push(cur.slice(0))
            }
            for (let i = 0; i < list.length; ++i) {
                cur[depth] = list.splice(i, 1)[0]
                rec(list, depth + 1)
                list.splice(i, 0, cur[depth])
            }
        }
        rec(iList)
        return results
    }

My code, which returns nothing:
function* permutations2(iList, maxLength) {
    const cur = Array(maxLength)

    function* rec(list, depth = 0) {
        if (depth === maxLength) {
            yield cur.slice(0)
        }
        for (let i = 0; i < list.length; ++i) {
            cur[depth] = list.splice(i, 1)[0]
            rec(list, depth + 1)
            list.splice(i, 0, cur[depth])
        }
    }
    yield rec(iList)
 }

For example, for print(permutations2([1, 2, 3], 2))
I want to get
[1, 2]
[1, 3]
[2, 1]
[2, 3]
[3, 1]
[3, 2]

However with the original code I am getting an array of the permutations:
[[1, 2],
[1, 3],
[2, 1],
[2, 3],
[3, 1],
[3, 2]]

I would be grateful to understand why my code is not working, and how to fix it.
Thanks!

A: A lazy generator will take some more work.
Instead of returning your results now, you use yield* to yield all the results that will come forth from rec.
Now rec is also a generator function.
And in a similar manner, instead of return and adding onto our results array, we yield the result.
Something you need to change here is adding the else, because yield does not stop the rest of the function from executing. It's only a pause. That's why we need else to make sure that this code does not execute after we yield.
Inside the else, like above, whenever we call rec, we need to yield the results of rec as well.

function* permutations(iList, maxLength) {
    const cur = Array(maxLength)

    function* rec(list, depth = 0) {
        if (depth === maxLength) {
            yield cur.slice(0);
        } else {
            for (let i = 0; i < list.length; ++i) {
                cur[depth] = list.splice(i, 1)[0];

                yield* rec(list, depth + 1);

                list.splice(i, 0, cur[depth])
            }
        }
    }

    yield* rec(iList);
}

console.log([...permutations([1, 2, 3], 2)]);

This seems to produce the same results but it is lazy now.

A: This is actually all the change you need, generator function, then yield* instead of return.

function* permutations(iList, maxLength) {
    const cur = Array(maxLength)
    const results = []

    function rec(list, depth = 0) {
        if (depth === maxLength) {
            return results.push(cur.slice(0))
        }
        for (let i = 0; i < list.length; ++i) {
            cur[depth] = list.splice(i, 1)[0]
            rec(list, depth + 1)
            list.splice(i, 0, cur[depth])
        }
    }
    rec(iList);
    yield* results;
}

console.log([...permutations([1, 2, 3], 2)]);

Note that this creates a generator that is not lazy. It computes all of the values beforehand and then yields them all.
yield* is a short way to yield all elements of an iterable or another generator.


text:
Q: How to load jQuery content into div from external content specific div New to jQuery.
I've got two lines of code.
$("#proj_content").load("/projects/rest #proj_cont");
$("#proj_content").load(jQuery(this).attr("class"));

The first does the job perfectly. I want to load the directory "projects/rest" and only the content from the div #proj_cont
The second allows me to make this dynamic through a CMS but I can't figure out how to get the #proj_cont in there.
Any help would be much appreciated.
I believe what I need is something close to this:
$("#proj_content").load($(this).attr("class") " + #proj_cont "); –

A: Use ordinary string concatenation:
$("#proj_content").load("/projects/rest #" + $(this).attr("class"));

or maybe you meant:
$("#proj_content").load("/projects/" + $(this).attr("class") + " #proj_cont");

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError: fetch is not a function in React Native & Jest I have a React Native project that contains only the sample Jest tests that are created with a new project (they just check if rendering works on iOS and Android).
My project uses fetch for network requests in one of the components. This works fine when I run the app, but when I run the tests they fail with this error message:

TypeError: fetch is not a function.

Anyone knows what's going on?
Here's the part of my code that uses fetch:
export default class MainScene extends Component {

constructor(props) {
    super(props);
    this.renderRowView = this.renderRowView.bind(this);
}

onFetch(page = 1, callback) {

    var date = new Date();
    date.setDate(date.getDate() - 7);

    fetch(  url, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    })
    .then((response) => response.json())
    .then((responseJson) => {
        if (responseJson.response.pages <= page) {
            callback(responseJson.response.results, {
                allLoaded: true
            });
        } else {
            callback(responseJson.response.results);
        }
    })
    .catch((error) => {
        console.error(error);
    });
}}

An the test file:
import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  const tree = renderer.create(
    <Index />
  );
});

A: Add this to your test file.
import 'isomorphic-fetch';


text:
Q: IsPressed trigger works when False, doesn't work when True I have multiple styles in my applications. Here's the one this question is about:
<Style x:Key="RoundCornerSmart" TargetType="{x:Type vk:SmartButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type vk:SmartButton}">
                <Border CornerRadius="8" BorderBrush="#006AB6" BorderThickness="1" Name="border">
                    <Grid x:Name="grid">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" TargetName="border">
                            <Setter.Value>
                                LightGray
                            </Setter.Value>
                        </Setter>
                    </Trigger>

                    <Trigger Property="IsPressed" Value="False">
                        <Setter Property="Background" TargetName="border">
                            <Setter.Value>
                                White
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Setter Property="FontSize" Value="18" />
    <Setter Property="Height" Value="62" />
    <Setter Property="Width" Value="62" />
    <Setter Property="Margin" Value="10" />
    <Setter Property="Foreground" Value="Black" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

SmartButton is a class which extends the Button class, it's a Button user-control.
 <vk:SmartButton HoldCommand="{Binding Path=ClickCommand}" EnableClickHold="True" MillisecondsToWait="1000" x:Name="key_U" Content="U" Grid.Column="8" Style="{DynamicResource RoundCornerSmart}"/>

When the smart button isn't pressed - its background is white, which is how it's supposed to be. However, when it's pressed, the background doesn't change. It's still white. What am I doing wrong? Why is the IsPressed not triggered?
EDIT:
When I comment the OnPreviewMouseLeftButtonDown method, it works.
Here's what happens in that method:
if (EnableClickHold)
        {
            Timer = new DispatcherTimer(DispatcherPriority.Normal, this.Dispatcher)
            {
                Interval = TimeSpan.FromMilliseconds(MillisecondsToWait)
            };
            Timer.Tick += Timer_Tick;
            Timer.IsEnabled = true;
            Timer.Start();
            e.Handled = true;
        }

A: The problem was:
e.Handled=true;

That line in the OnPreviewMouseLeftButtonDown method. I don't know why though. When I commented it, the background was set to LightGrey, it worked.


text:
Q: Send Http Request to .Net Server i want to send post request to .Net server. there is my code for post request:
  public func SendPostHttpRequest(baseURL: String, parameter: [String:Any], closure:@escaping ((_ success:JSON,_ error:NSError?) -> Void)) {
    let manager = Alamofire.SessionManager.default
    if let url = URL(string: baseURL) {
      var urlRequest = URLRequest(url: url)
      urlRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
      urlRequest.setURLEncodedFormData(parameters: parameter)
      manager.request(urlRequest).responseString { response in
        debugPrint(" HTML error -------> \(response)")
      }
      manager.request(urlRequest).responseJSON { response in
        switch response.result {
        case .success(let JSON) :
          closure(JSON,nil)
        case .failure(let error):
          closure(nil,error as NSError)
          debugPrint("get error ---> \((error.localizedDescription)) ")
        }
      }
    }
  }

that is define Extension for set URLEncodedFormData to request
 extension URLRequest {
        private static let alloweCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789  -_.*@$!#/:+[]\n")
          public mutating func setURLEncodedFormData(parameters: [String: Any]) {
            var encodedParameters = ""
            for (key, value) in parameters {

              if !encodedParameters.isEmpty {
                encodedParameters += "&"
              }
              encodedParameters += URLRequest.urlEncoded(value: key) ?? ""
              encodedParameters += "="

              let valuee = value
              if let boolValue = valuee as? Bool {
                encodedParameters += "\(boolValue)"
              }
              if let intValue = valuee as? Int {
                encodedParameters += "\(intValue)"
              }
              if let stringValue = valuee as? String {
                encodedParameters += (URLRequest.urlEncoded(value: stringValue) ?? "")
              }
            }
            self.httpMethod = "POST"
            self.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            self.httpBody = encodedParameters.data(using: .utf8)
          }

          private static func urlEncoded(value: String?) -> String? {

            return value?.addingPercentEncoding(withAllowedCharacters: alloweCharacters)!.replacingOccurrences(of: " ", with: "")
          }
        }

i have an issue in send variables with different types to server.
in server side i get this error:
Object reference not set to an instance of an object.
I think because I'm sending all the parameters to the string, the server side does not figure out the bool and integer variables.
this is request object class, My question now is that the parameter type in integer whit setURLEncodedFormData method send as integer type to server or String?
class RegisterRequest: NSObject {
  var Usertoken: String!
  var ProffessionId: Int?
  override init() {
    self.Usertoken = ""
    self.ProvinceId = nil
}
}


text:
Q: iPhone/iPad App updates within App itself I know that after I have deployed my ipad/iphone app into App Store, it will notify those who have installed my app when I have a new update.
However, I have seen some apps getting an update prompt after opening the app itself. It will actually do the updates within the app itself, instead of from the App Store. Would like to know how this is being done. Is it through application coding?
My app displays information of certain projects based on categories. Would like to know if the user can actually choose the categories he/she wishes to update, if the update is done via the app itself, as described above.
Please advise. Thanks a lot.

A: You cannot update the actual application code, but you can update content if you have a webservice set up that the app can check-in with.
Conceptually it is no different then the Facebook app which updates its content (your news feed) when you open the app.
There are many ways to do this type of thing and a quick Google search should lead you to some tutorials.


text:
Q: JDBC - Retrieve Boolean output from Oracle Procedure I need to invoke an Oracle procedure with one IN parameter with VARCHAR2 and OUT parameter as BOOLEAN data type.
Below is my code using SimpleJdbcCall
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(getTemplate())
            .withCatalogName("package_name")
            .withProcedureName("proc_name")
            .withoutProcedureColumnMetaDataAccess()
            .declareParameters(
                new SqlParameter ("userName", Types.VARCHAR),
                new SqlOutParameter("status", Types.BOOLEAN)
            );
Map<String, Object> inParams = new HashMap<String, Object>();
inParams .put("userName",  userInput);
Map<String, Object> outputValue= jdbcCall.execute(inParams);

Exception : CallableStatementCallback; uncategorized SQLException for
  SQL [{call PACKAGE_NAME.PROC_NAME(?, ?)}]; SQL state [99999];
  error code [17004]; Invalid column type: 16; nested exception is
  java.sql.SQLException: Invalid column type: 16

After doing a research i found that "JDBC drivers do not support the passing of Boolean parameters to PL/SQL stored procedures"
It has been suggested to wrap the PL/SQL procedure with a second PL/SQL procedure. The main problem is that i am restricted for write access in the db as that is client data. please help me to fix this issue.
Some of the links i referred

*

*https://docs.oracle.com/cd/F49540_01/DOC/java.815/a64685/tips3.htm

*https://community.oracle.com/thread/2139408?tstart=0

*https://community.oracle.com/thread/887712?tstart=0

*https://community.oracle.com/thread/975159?tstart=0

*Stored Function - Sending/Receiving Boolean - BD

*http://docs.oracle.com/cd/B28359_01/java.111/b31224/apxtblsh.htm#i1005380

A: From the official Oracle JDBC documentation:

It is not feasible for Oracle JDBC drivers to support calling
  arguments or return values of the PL/SQL RECORD, BOOLEAN, or table
  with non-scalar element types. [...] As a workaround to PL/SQL RECORD,
  BOOLEAN, or non-scalar table types, create container procedures that
  handle the data as types supported by JDBC. For example, to wrap a
  stored procedure that uses PL/SQL boolean, create a stored procedure
  that takes a character or number from JDBC and passes it to the
  original procedure as BOOLEAN or, for an output parameter, accepts a
  BOOLEAN argument from the original procedure and passes it as a CHAR
  or NUMBER to JDBC. Similarly, to wrap a stored procedure that uses
  PL/SQL records, create a stored procedure that handles a record in its
  individual components, such as CHAR and NUMBER, or in a structured
  object type.

This is exactly what you did in your answer, but I wanted to add the documentation as reference.

A: I fixed the issue by writing a wrapper procedure to process the result of the actual procedure and sending back the result as varchar data type .
If any of you find it as wrong approach or if you a have any easy way to fix this, please do share your comments.
Below is the procedure:
DECLARE
userName VARCHAR2(13);
status BOOLEAN;
result VARCHAR2(13);

BEGIN
userName := ?;
status := NULL;
package_name.proc_name ( userName, status);
BEGIN
IF status THEN result := 'Yes';
ELSIF NOT status THEN result := 'No';
ELSE result := 'NULL';
END IF;
END;
COMMIT;
? := result;
END ;

Also instead of simpleJdbcCall, i used CallableStatement for processing this. Refer below:
try{
    String wrapperProc= "DECLARE userName VARCHAR2(13);  status  BOOLEAN;  result VARCHAR2(13); BEGIN userName := ?; status := NULL; "+
        "package_name.proc_name ( userName, status ); BEGIN IF status THEN result := 'Yes'; ELSIF NOT status THEN " +
            "result := 'No'; ELSE result := 'NULL'; END IF; END; COMMIT; ? := result;END ;";
    CallableStatement proc_stmt= null;
    proc_stmt = getTemplate().getDataSource().getConnection().prepareCall(wrapperProc);
    proc_stmt.setString(1, "userName");
    proc_stmt.registerOutParameter(2, Types.VARCHAR);
    proc_stmt.execute();
    System.out.println("Final Result : "+proc_stmt.getString(2));
} catch(SQLException e){
    System.out.println("SQL Exception : "+e.getMessage());
    e.printStackTrace();
} catch (Exception e) {
    System.out.println("Exception : "+e.getMessage());
    e.printStackTrace();
}

~~Suriya


text:
Q: how to slide down the action bar in android to display something like coversation i want to display the conversation between me and admin when i dragged the action bar. since i was new to android programming i dont know how to slide the action bar also. the following code is a decoy(dummy) code, coz its not letting me to post the question without sample code. please help me to drag or slide down the action bar to display conversation. thank you.
          import android.support.v7.app.ActionBarActivity;
          import android.os.Bundle;
          import android.view.Menu;
          import android.view.MenuItem;
          import android.widget.Button;
          import android.view.View;

           public class MainActivity extends ActionBarActivity {

            @Override
           protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
        Button bt=(Button)findViewById(R.id.button);
       bt.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {

       }
         {

       }
       }

      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if  it      is         present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
      }

    @Override
     public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
     }
      }


text:
Q: Priority queue in java tie break for removing duplicate elements If there are multiple elements with same value in PriorityQueue, while removing from the queue which element is popped?
Is there any specific order in which these same elements are popped?

A: There is no specific order.  The Javadoc specifies:

If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily.


text:
Q: Oracle, average team stats by individual players throws exception I want to calculate the average productivity of all teams in a icehockey  competition. To do this, I want to make a query to calculate the productivity of each player and take the average of it for having the productivity of 1 club. To calculate the productivity of 1 player, I divide the number of goals by the played games. number of goals from 1 player.
I tried it to use following query:
SELECT TEAM.CODE, (1 - AVG(SUM(TS.GOALS)) / SUM(CS.GAMES) * 100) AS "Percentage"
FROM DIM_TEAM TEAM
JOIN PLAYER P ON P.TEAM_ID = TEAM.ID
JOIN TEAM_STATS TS ON TS.PLAYER_ID = P.ID
JOIN COMPETITION_STATS CS ON P.ID = CS.PLAYER_ID
GROUP BY TEAM.CODE;

I'm totally stuck, because I get following exception:

Error: ORA-00937: not a single-group group function
SQLState:  42000 ErrorCode: 937

The code worked in the past, but I think the business implementation is also wrong. Can anyone help me to figure this out?

A: I removed the sum(ts.goals) as that is the reason for your error and I don't think it is needed.  You need to beware of divide by zero in this query though..
    SELECT TEAM.CODE, (1 - AVG(TS.GOALS) / SUM(CS.GAMES) * 100) AS "Percentage"
    FROM DIM_TEAM TEAM
    JOIN PLAYER P ON P.TEAM_ID = TEAM.ID
    JOIN TEAM_STATS TS ON TS.PLAYER_ID = P.ID
    JOIN COMPETITION_STATS CS ON P.ID = CS.PLAYER_ID
    GROUP BY TEAM.CODE;


text:
Q: XmlDocument.Validate() - get error message from exception Is it possible to return the errors from Xml.Validate(...)? i.e. the point at which my xml fails to validate against the xsd.
In this snippet the validation would simply fail the try-catch, and return false. Removing the try-catch throws a system exception.
Note: 'var Xml' is of type XmlDocument.
public static class XmlValidator
{
    public static bool Validate(UploadedFile uploadedFile)
    {
        try
        {
            var Xml = uploadedFile.XmlFromUpload();
            string XsdPath = @"C:\Projects\XMLValidator\Xsd\books.xsd";

            Xml.Schemas.Add(null, XsdPath);
            Xml.Validate(ValidationCallBack);
            return true;
        }
        catch
        {
            return false;
        }
    }

    private static void ValidationCallBack(object sender, ValidationEventArgs e)
    {
        throw new Exception();
    }
}

A: The ValidationEventArgs parameter of the ValidationCallBack contains the error:
https://msdn.microsoft.com/en-us/library/system.xml.schema.validationeventargs%28v=vs.110%29.aspx
It has Exception, Message and Severity properties. Consider saving these and then making them available, e.g.:
public static class XmlValidator
{
    public static bool Validate(UploadedFile uploadedFile)
    {
        _errors.Clear();
        var Xml = uploadedFile.XmlFromUpload();
        string XsdPath = @"C:\Projects\XMLValidator\Xsd\books.xsd";

        Xml.Schemas.Add(null, XsdPath);
        Xml.Validate(ValidationCallBack);
        return !_errors.Any();
    }

    private static void ValidationCallBack(object sender, ValidationEventArgs e)
    {
        _errors.Add(e.Exception);
    }

    private static List<Exception> _errors = new List<Exception>();

    public static IEnumerable<Exception> GetErrors()
    {
        return _errors;
    }
}


text:
Q: Difference between equal frequency and quantile binning Equal-frequency binning divides the data set into bins that all have the same number of samples. Quantile binning assigns the same number of observations to each bin. What is the difference between both methods? It seems to me that both do the same and it is just a matter of terminology. Unfortunately, I could not find a clear answer.
References:

*

*Equal frequency binning

*Quantile binning

A: For data that are continuous and have not been rounded so much that
there are ties, both of the methods can be used to make intervals with equal counts, provided that the number of intervals is an even divisor of the number of observations.
Suppose I have $n = 80$ observations, and I want ten bins with 8 observations in each. [I'm using R to sample 80 observations from the distribution $\mathsf{Norm}(\mu=50,\sigma=7).]$ Then I could use deciles to make the cutpoints separating intervals.
set.seed(202)   # use this seed to get exactly same data again
x = round(rnorm(80, 50, 7) ,3)

I set the width of the print window so that exactly eight (sorted)
observations will print on each line below. Numbers in [ ]s show the index
(number in order) of the first observation on each line. This is not necessary, but may make it easier to follow through the process.
sort(x)
 [1] 33.491 35.961 36.467 37.278 37.752 39.986 40.121 42.078
 [9] 42.154 42.384 43.157 43.723 43.989 44.071 44.500 44.564
[17] 44.569 44.823 45.205 45.363 45.372 45.851 46.071 46.917
[25] 46.987 47.488 47.645 48.192 48.404 48.978 49.031 49.238
[33] 49.249 49.251 49.304 49.336 49.366 50.137 50.200 50.526
[41] 50.587 50.631 50.968 51.597 51.662 51.762 51.768 52.191
[49] 52.322 52.376 52.513 52.928 53.257 53.281 53.471 53.556
[57] 53.587 53.617 54.041 54.179 54.958 55.249 56.167 56.325
[65] 56.346 56.432 56.606 56.702 57.143 57.606 58.259 58.483
[73] 60.116 61.688 62.374 62.852 62.971 63.822 65.614 69.224

Check that there are no ties. (This is important because ties might
force unequal counts among the ten intervals.)
length(unique(x))
[1] 80            # distinctly different values

Choose deciles 0%, 10%, 20%, ..., 90%, 100% as the cut points (bin
boundaries:
cutp = quantile(x, seq(0, 1, by=.1));  cutp
     0%     10%     20%     30%     40%     50%     60%
33.4910 42.1464 44.5680 46.9660 49.2446 50.5565 52.2434
    70%     80%     90%    100%
53.5653 56.3292 58.6463 69.2240

Notice that the deciles separate the ten lines of the printout of the 80 observations above.
Now I'll make a histogram using these cutpoints for the bases of the
histogram bars. The procedure rug puts tick marks along the horizontal
axis to show exact positions of data values.
hist(x, br=cutp, col="skyblue2");  rug(x)

Ordinarily, this is not a good way to make a pretty histogram.
(However, for certain kinds of printed tables, it may be helpful to have the same number of observations in each interval.) I'm showing the histogram so that you can see the effect of forcing
the number of counts in each interval to be the same. In the figure above each of the ten bars has exactly the same area.
Usually, the software
picks 'round' numbers for bin boundaries. But I wanted you to see that
there are eight observations in each interval (histogram bin) in the figure above.
Here is a typical histogram drawn by R. There are different numbers of
observations in each bin. (And the bars have correspondingly different areas.) In a 'density' histogram the total area of
all the bars is $1.$
hist(x, prob=T, col="skyblue2");  rug(x)

In R, a non-plotting "histogram" displays information used to make the figure
just above (for simplicity I have not shown the entire list).
hist(x, plot=F)

$breaks
[1] 30 35 40 45 50 55 60 65 70

$counts
[1]  1  5 12 19 24 11  6  2

$mids
[1] 32.5 37.5 42.5 47.5 52.5 57.5 62.5 67.5


text:
Q: Why attributes in dispatch don't come in actions (vuex)? I have a problem with sending data from vue to vuex.
When I am try send dates to vuex via 'let' - axios don't see these dates.
But when I am try input dates in axios request - ok, and I can see response.
Why it could be?

A: If you want to pass multiple params to Vuex actions you need to wrap them in an object, e.g.
loadIncomings(context, { clubId, dateFrom, dateTo })
Vuex considers the first param as the context and the second as the payload. That's why your clubId gets passed but all other params are discarded.


text:
Q: PySpark Join with Key in simple way Here I have two table teacher and student, I want to Join these table with Teacher ID ( A,B,C,D) . I have the solution as well. My question is, Is there any other way on Getting the same result , like a simple join etc. as Join works in Key value pair.
"""
My Input
    teacher
    A,Alpha
    B,Bravo
    C,Charlie
    D,Delta

    student
    1,A,Aadarsh
    2,c,Sun
    3,B,Aagam
    4,A,Aadidev
    5,B,Ideal
    6,B,Aaditya
    7,B,Supreme
    8,A,Arrival
    9,c,Aahan

    """
    from pyspark import SparkContext
    sc = SparkContext()

    def stu(st):
        line = st.split(",")
        stId = line[0]
        stTId = line[1]
        stName = line[2]
        return (stTId,stId,stName)
    def tea(te):
        line = te.split(",")
        teId = line[0]
        teName = line[1]
        return (teId,teName)

    getStu = student.map(lambda x : stu(x))
    getTea = teacher.map(lambda y : tea(y))
    joinStuTea = getTea.map(lambda x : (x[0],x[1])).join(getStu.map(lambda x : (x[0],(x[1],x[2]))))
    formatData = joinStuTea.map(lambda (x1,(x2,(k,v))) : k + " " + x1 + " " + x2 + " " +  v)
    for x in formatData.collect():
        print x

Result
1 A Alpha Aadarsh
4 A Alpha Aadidev
8 A Alpha Arrival
2 C Charlie Sun
9 C Charlie Aahan
3 B Bravo Aagam
5 B Bravo Ideal
6 B Bravo Aaditya
7 B Bravo Supreme

A: You can use dataframes.
First let's convert your RDD student, teacher into dataframes:

stu_df = spark.createDataFrame(
    student.map(lambda l: l.split(",")),
    ["stId", "teId", "stName"]
)
teacher_df = spark.createDataFrame(
    teacher.map(lambda l: l.split(",")),
    ["teId", "teName"]
)

Now to join them
df = stu_df.join(teacher_df, "teId", "inner")

    +----+----+-------+-------+
    |teId|stId| stName| teName|
    +----+----+-------+-------+
    |   B|   5|  Ideal|  Bravo|
    |   B|   3|  Aagam|  Bravo|
    |   B|   6|Aaditya|  Bravo|
    |   B|   7|Supreme|  Bravo|
    |   C|   2|    Sun|Charlie|
    |   C|   9|  Aahan|Charlie|
    |   A|   1|Aadarsh|  Alpha|
    |   A|   4|Aadidev|  Alpha|
    |   A|   8|Arrival|  Alpha|
    +----+----+-------+-------+


text:
Q: How to setup rule for emails that contains specific words in top email body only? I created a rule that moves emails that contains a specific word in body to another folder.
It applies whenever that word is in body of older emails down the thread (when you scroll down to older emails that were replied to).
I need it to identify that word within the most recent email body only (and disregard the rest of the thread).

A: Outlook doesn't distinguish old email bodies and new ones. The message body is a single string. The best what you can do is to compare the message body of two items from the same conversation and extract the newer part. So, following that you will be able to recognize whether a keyword is a part of the newer message or not. The GetConversation method obtains a Conversation object that represents the conversation to which this item belongs. A conversation represents one or more items in one or more folders and stores.
Use the Find/FindNext or Restrict methods of the Items class to find items that  correspond to the specified condition. Read more about them with code examples in the following articles:

*

*How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

*How To: Use Restrict method to retrieve Outlook mail items from a folder
Also you may find the AdvancedSearch method of the Application class helpful. The key benefits of using the AdvancedSearch method in Outlook are:

*

*The search is performed in another thread. You don't need to run another thread manually since the AdvancedSearch method runs it automatically in the background.

*Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).

*Full support for DASL queries (custom properties can be used for searching too). You can read more about this in the Filtering article in MSDN. To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).

*You can stop the search process at any moment using the Stop method of the Search class.

Read more about that in the Advanced search in Outlook programmatically: C#, VB.NET article.


text:
Q: Know which file is related to a process execution In Unix, with top I have an output similar to this:
13916 root 18 0 903m 129m 9936 S 51.4 0.1 3:07.01 php

How can I know which file is this php process executing?
For example:
13916 root 18 0 903m 129m 9936 S 51.4 0.1 3:07.01 php /var/www/index.php

A: Hit c while running top. It will show the full command line, rather than just the process name.
Or to enable it from the command line you can run

top -c

I don't have php installed to test, but here is an example from one of my systems

2378 root      20   0   19268   2104   1844 S   0.0  0.0   0:56.73 /usr/sbin/irqbalance --pid=/var/run/irqbalance.pid
 2461 root       0 -20       0      0      0 S   0.0  0.0   0:00.00 [cfg80211]
 2468 root      20   0  917492  13412   8596 S   0.0  0.0   0:00.43 /usr/sbin/libvirtd
 2479 root      20   0    4248   1532   1384 S   0.0  0.0   0:00.00 /usr/sbin/acpid
 2513 root      20   0   71692   4884   4200 S   0.0  0.0   0:00.01 /usr/sbin/cups-browsed
 2514 root      20   0  276012   4776   4012 S   0.0  0.0   0:18.67 /usr/lib/accountsservice/accounts-daemon
 2523 root      20   0  278500   4492   3816 S   0.0  0.0   0:00.06 /usr/lib/policykit-1/polkitd --no-debug
 2533 root      20   0   14408   1896   1752 S   0.0  0.0   0:00.00 /sbin/agetty --noclear tty1 linux
 2593 root      20   0   24656   1772   1560 S   0.0  0.0   0:00.00 /usr/bin/kdm -config /var/run/kdm/kdmrc
 2621 root      20   0  262292  28976  11648 S   0.0  0.1   2:40.10 /usr/bin/X :0 vt7 -br -nolisten tcp -auth /var/run/xauth/A:0-4iKqJa
 2627 ntp       20   0   37484   3896   3276 S   0.0  0.0   0:21.49 /usr/sbin/ntpd -p /var/run/ntpd.pid -g -u 115:126


text:
Q: Why does $V(I(S))=\overline{S}$? Let $S\subset\operatorname{Spec}A$, where $A$ is a commutative ring with $1$. I am having trouble seeing why $V(I(S))=\overline{S}$, where $\overline{S}$ is the Zariski closure of $S$.
My attempt is as follows. It is not hard to see that $S\subset V(I(S))$: $V(I(S))$ is the set of all prime ideals of $A$ containing $I(S)$, and $I(S)$ is the intersection of all elements (prime ideals) of $S$. Since every element of $S$ contains $I(S)$, it follows that $S\subset V(I(S))$. This implies that $\overline{S}\subset V(I(S))$.
The issue I'm having is proving the reverse inclusion. Suppose $V(J)$ is any closed set containing $S$. Then $I(V(J))\subset I(S)$ since $I(\cdot)$ is inclusion reversing. I'm not sure where to go from here or even if this is the correct line of thought to have. What am I missing?

A: The idea of hitting $V(J)$ with $I$ is a good idea and can probably be made to work, but I think it's more straightforward to reason directly with $V(J)$ and $J$. It's a matter of unwinding the definitions completely:
Suppose $V(J)\supset S$ as you said. What is $V(J)$? It is the set of all primes containing $J$, where $J$ is some ideal in $A$. What does $S\subset V(J)$ tell us about the relationship between $J$ and the prime ideals that are members of $S$? Well, $\mathfrak{p}\in V(J)$ means $\mathfrak{p}\supset J$, by definition. So $S\subset V(J)$ means that for all $\mathfrak{p}\in S$, we have $J\subset \mathfrak{p}$. Thus, intersecting over all these primes, we get
$$J\subset \bigcap_{\mathfrak{p}\in S} \mathfrak{p}.$$
Recalling that $I(S)$ is nothing but the right side of this, we have
$$J\subset I(S).$$
But then this means that any prime ideal containing $I(S)$ also contains $J$! In other words, any member of $V(I(S))$ is also a member of $V(J)$! This is the assertion that
$$V(I(S))\subset V(J).$$
So any closed set containing $S$ actually contains $V(I(S))$, and it follows that $V(I(S))\subset \overline S$, as desired.
(To me it feels like saying the same sentence over and over again in slightly different language until it becomes the desired statement.)

A: Recall that $I(V(J)) = \sqrt{J}$. Since $I(V(J))\subseteq I(S)$, applying $V$, then
$$
V(J) = V(\sqrt{J}) = V(I(V(J))) \supseteq V(I(S)).
$$
Thus $V(I(S))$ is contained in any closed subset containing $S$, so $V(I(S)) = \overline{S}$.


text:
Q: Login and register phpbb users within an asp.net website I've been asked if it's possible to create an ASP.NET MVC website which integrates a phpbb forum in an iframe, and lets users login and register to the forum through the website, as well as making them logged in to the entire website at the same time.
Is there a good way to make this possible efficiently and securely?
I've no experience with phpbb or php.

A: There is no API you have to build it all yourself. There are several strategies you can follow, one secure way is to let the other application integrate via the database and let it use the same session information (user, session, key tables).
Please see also this question:
Replicate PHPBB password hashing in ASP.net c#


text:
Q: Warning throwed breaks compilation I have a question about how maven manage the severity of the warnings.
I have two environments, in one Environment (My local computer, maven 3.2.2), maven throws the error  "unmappable character for encoding UTF-8" with severity "WARNING", so, i can compile with no problem.
On the other environment (Jenkins, mavne 3.2.1), this error is throw with severity "ERROR", so, the compilation ends at this point.
You know how I can tell Maven to throw this error as "WARNING" on the Jenkins environment?

A: The problem is that the Maven version installed on Jenkins uses the Maven Compiler Plugin version 2.5.1, this version throws the "unmappable character" as "ERROR" instead of "WARNING". This causes that the Maven Compiler Plugin stop at this error.
I forced on the POM.xml to use a newer version (3.5.1) and the problem was solved.


text:
Q: Tensorboard remove images from logs on the go I'm using tensorboard on pytorch: https://pytorch.org/docs/stable/tensorboard.html
I save images every epoch with add_image: https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter.add_image
I'm trying to find a way to keep only the last epoch of images because otherwise the tensorboard file becomes huge.
Is there a way to do it? Also if I want also to keep the best epoch j. Is there a way to do this too?
A similar question is also here: Remove image outputs from TensorBoard but it's not defined like this + it ~6 years ago.


text:
Q: Expression.Call causes "Static method requires null instance, non-static method requires non-null instance" I have viewed similar SO questions but cannot figure out why mine won't work.
I need to convert my Func<string, bool> value to an Expression to be used in the Moq framework but I cannot get passed an error when trying to convert the Func to an Expression.
This is the error:

Static method requires null instance, non-static method requires
  non-null instance.

This is my sample code:
using System;
using System.Linq.Expressions;

namespace ConsoleApp1
{
    class Program
    {
        public class MyObject
        {
            public void Add<T>(Func<T, bool> value)
            {
                // Line below causes error: Static method requires null instance,
                // non-static method requires non-null instance.
                Expression<Func<T, bool>> expression =
                    Expression.Lambda<Func<T, bool>>(Expression.Call(value.Method));

                // I need to use the expression for the line below that is commented out
                // (for context reasons I have included this)
                //_myMock.Setup(m => m.MyMethod(key, It.Is(expression))).Returns("test");
            }
        }

        public static void Main(string[] args)
        {
            // Call it using:
            var myObject = new MyObject();
            myObject.Add(new Func<string, bool>(x => x.StartsWith("test")));
        }
    }
}

Not sure if my function is a static or non-static, but I would have thought it was static. I inspected the Func object using the debugger and there is a field called "IsStatic" set to false (value.Method.IsStatic). A bit confused what else to try.
Thank you.
Stack Trace:
System.ArgumentException
  HResult=0x80070057
  Message=Static method requires null instance, non-static method requires non-null instance.
Parameter name: method
  Source=System.Core
  StackTrace:
   at System.Linq.Expressions.Expression.ValidateStaticOrInstanceMethod(Expression instance, MethodInfo method)
   at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
   at System.Linq.Expressions.Expression.Call(MethodInfo method, Expression[] arguments)
   at ConsoleApp1.Program.MyObject.Add[T](Func`2 value) in C:\Users\userName\source\repos\ConsoleApp1\ConsoleApp1\Program.cs:line 14
   at ConsoleApp1.Program.Main(String[] args) in C:\Users\userName\source\repos\ConsoleApp1\ConsoleApp1\Program.cs:line 28

A: Your method that you are wrapping in expression call is not static.

To call not static method you would need valid instance to pass as this, and this can get tricky if you actually use some variable from outside of the func. You can inspect the method further and see its declaring type. Instance of it would be required to make the Expression.Call work.

To just do the mock setup, as it is your goal, you could modify your Add method and just get the expression directly
Add<T>(Expression<Func<T, bool>> expression)
{
    _myMock.Setup(m => m.MyMethod(key, It.Is(expression))).Returns("test");
}

and this will just work when called like this:
myObject.Add((string x) => x.StartsWith("test"));


text:
Q: What are The SPIR-V Capability (Geometry) Requirements I have 2 framebuffers. First, one is layered. And renders HDR image to Cubemap.
In this Renderpass Geometry Shader is used.
Debug layer gives me the following error message.
[VAL][VUID-VkShaderModuleCreateInfo-pCode-01091] Validation Error: [ VUID-VkShaderModuleCreateInfo-pCode-01091 ]
        Object 0: handle = 0x14f9a58bfe8, type = VK_OBJECT_TYPE_DEVICE;
        | MessageID = 0xa7bb8db6 | vkCreateShaderModule(): The SPIR-V Capability (Geometry) was declared, but none of the requirements were met to use it.
        The Vulkan spec states: If pCode declares any of the capabilities listed in the SPIR-V Environment appendix, one of the corresponding requirements must be satisfied (https://vulkan.lunarg.com/doc/view/1.2.170.0/windows/1.2-extensions/vkspec.html#VUID-VkShaderModuleCreateInfo-pCode-01091)

I searched for  SPIR-V geometry shader requirements but I couldn't find what I am missing.
My Geometry shader code is
#version 450 core

layout(triangles, invocations = 6) in;
layout(triangle_strip, max_vertices = 3) out;

void main()
{
    for(int i = 0; i < 3; i++)
    {
        gl_Layer = gl_InvocationID ;
        gl_Position = gl_in[i].gl_Position + vec4(vec3(gl_InvocationID)/5 , 1);
        EmitVertex();
    }
    EndPrimitive();
}


text:
Q: Getting an undefined index error my php is very "weak" so I am having trouble with this -
<?php

include_once "../scripts/connect_to_mysql.php";

$title = $_POST['title'];
$desc = $_POST['description'];

$query = mysql_query("UPDATE images SET title='$title', description='$desc'") or die (mysql_error());

echo 'Operation Completed Successfully!

Click Here';
exit();
?>

The undefined index error is description on line 9 which is $desc = $_POST['description']; and "description" is in the database spelling is also right.

A: Your form needs to send this information to the php file. It seems as you only have title in your form and not description. You should post your form for better help.
<form ...>
  <input type="text" name="description" value="">
  <input type="text" name="title" value="">
</form>

You should always escape your data which you are using in SQL queries.

A: Apparently, a description field is not present in the $_POST array, thus index description does not point to anything.
What does var_dump($_POST); print?
Also, is this an internal system? If not, you should read up on SQL injections.

A: There is no element with index description in the $_POST array.
Try var_dump($_POST); before that line to examine the array. (Alternatively, if some information is cut, use print_r($_POST);

A: Try doing:
if(isset($_POST['description'])){echo "yes";}else{echo "no";}

This wont fix it but it will help determing whether $_POST['description'] exists.. Also, what is the source of $_POST['description']?, is it set in ../scripts/connect_to_mysql.php? How?
Unless performing more complex tasks (i.e. AJAX), POST variables are typically set by submitting a form- does your code come after the page is loaded following a form submission? If not, you may be incorrectly using _POST variables...
If $_POST['description'] is set somewhere in the code of ../scripts/connect_to_mysql.php, and by including the file you wish to then retrieve its value- you may be going about things wrongly- can you provide information about the origin of $_POST['description']?


text:
Q: Have Word not mark abbreviations as end-of-sentence I have Microsoft Word's rather handy grammar checker on, but if I use an abbreviation or a word like "Yahoo!" Word marks the punctuation as the end of the sentence, and then marks the uncapitalized next word as a grammar error because it thinks that is the start of a sentence. Is there any way to fix this?

A: If it is only a couple of abbreviations of brand names (Yahoo!) that you keep coming across, then you can add them to the AutoCorrect exceptions for "do not capitalize after:"
In Word 2007 click the Office Orb button and choose Word options or in 2010 click File then Options
I'm not sure about 2007 but in 2010 you're looking for the AutoCorrect options under Proofing.

On a side note there should already be a substantial list of abbreviations, assuming they are enabled.


text:
Q: Typo in hovertext on /tags/synonyms On https://meta.stackoverflow.com/tags/synonyms (and presumably all other /tags/synonyms pages on other SE sites; it's certainly present on SO/SU/SF), when you hover over the "active" button (which takes you to https://meta.stackoverflow.com/tags/synonyms?filter=active&tab=newest), the following text is displayed as hovertext:

Only active tag synonym

On grammatical grounds, this should be:

Only active tag synonyms

A: Another bug introduced during our i18n efforts. Fix will be out in the next build, rev 2013.11.11.1623 on meta and 2013.11.11.1145 on sites.


text:
Q: Function in R to get the SE of values for several dates, with each dates values being the sum of previous dates values and SE taken each time My data:

treatment
replicate
date
value

city
1
May13
1

city
2
May13
3

rural
1
May13
11

rural
2
May13
7

city
1
May20
2

city
2
May20
0

rural
1
May20
19

rural
2
May20
12

city
1
May27
5

city
2
May27
0

rural
1
May27
21

rural
2
May27
14

I already have a function that sums the values for each date across replicates, then takes the mean, and for each additional date takes the cumulative sum of that date plus the previous, and divides by the number of replicates, and so on:
data %>% group_by(treatment, date) %>% summarize(value = mean(value)) %>% mutate(value = cumsum(value))

What I would like to do now is obtain standard error for each date, with each date's values being itself plus the values of the all prior dates, which for the above dataset would give this result:

treatment
date
mean
SE

city
May13
2
1

rural
May13
9
2

city
May20
3
0

rural
May20
24.5
5.5

city
May27
5.5
2.5

rural
May27
42
9

So far, I can only come up with code to get the standard error for each date, but independent of the other dates. Or, I can code to get standard error for each date, independent of other dates, but then cumulatively summed, which is also not what I want:
data %>% group_by(treatment, date) %>%
  summarize(value = mean(value)) %>% mutate(value = cumsum(value), std.error(value))

se <- function(x) sd(x)/sqrt(length(x))

b<-transform(aggregate(value~treatment+date,data,cumsum),
             value= ave(value, treatment, FUN=cumsum))

I am trying to get the SE for date 1. Then, I want to add the values of dates 1 and 2 together (within replicate) then take the SE for that vector. For date 3, I want to add the values of the previous 2 dates to date 3 and then take the SE. Hopefully this makes sense.
Thanks for any suggestions.

A: I like dplyr as much as the next person but sometimes a simple loop can make the code and logic much more readable and understandable imo:
 getSE <- function(data.in){

  unique.dates <- unique(data.in$date)

  n.dates <- length(unique.dates)
  n.treatments <- length(unique(data.in$treatment))

  date.list <- list()

  for(i in 1:n.dates){

    date.list <- append(date.list, unique.dates[[i]])

    data.flt <- filter(data.in, date %in% date.list)

    temp <- data.flt %>%
      group_by(treatment, replicate) %>%
      mutate(rep.sum = sum(value)) %>%
      ungroup() %>%
      group_by(treatment) %>%
      summarise(se = se(rep.sum)) %>%
      mutate(date = unique.dates[[i]])

    if(i == 1){
      data.out <- temp
    } else {
      data.out <- bind_rows(data.out, temp)
    }

  }
  data.out <- select(data.out, treatment, date, se)
  return(data.out)
}

# A tibble: 6 x 3
  treatment date     se
  <chr>     <chr> <dbl>
1 city      May13  1
2 rural     May13  2
3 city      May20  0
4 rural     May20  3.18
5 city      May27  1.12
6 rural     May27  4.02

A: I think it depends a bit on how you think about it.  The way you've framed the problem, you're calculating the SE for each date-treatment pair.  If you think about the mean each day as a random variable, that has a normal distribution with a given standard error, then when you sum up the means you should probably calculate the variance of the summed means by summing up the sampling variances.  We know that the variance of a linear combination is:

Assuming that the covariance between means of different dates is zero, then you could just sum up the squared standard errors and take the square root of the sum to get the sampling variability of the sum.
library(dplyr)
dat <- tibble::tribble(
  ~treatment,   ~replicate, ~date,  ~value,
"city", 1,  "May13",    1,
"city", 2,  "May13",    3,
"rural",    1,  "May13",    11,
"rural",    2,  "May13",    7,
"city", 1,  "May20",    2,
"city", 2,  "May20",    0,
"rural",    1,  "May20",    19,
"rural",    2,  "May20",    12,
"city", 1,  "May27",    5,
"city", 2,  "May27",    0,
"rural",    1,  "May27",    21,
"rural",    2,  "May27",    14)

dat %>% group_by(treatment, date) %>%
  summarize(sv = var(value)/n(),
            value = mean(value)) %>%
  mutate(value = cumsum(value),
         se = sqrt(cumsum(sv)))
#> `summarise()` has grouped output by 'treatment'. You can override using the
#> `.groups` argument.
#> # A tibble: 6 × 5
#> # Groups:   treatment [2]
#>   treatment date     sv value    se
#>   <chr>     <chr> <dbl> <dbl> <dbl>
#> 1 city      May13  1      2    1
#> 2 city      May20  1      3    1.41
#> 3 city      May27  6.25   5.5  2.87
#> 4 rural     May13  4      9    2
#> 5 rural     May20 12.2   24.5  4.03
#> 6 rural     May27 12.2   42    5.34

Created on 2023-02-28 with reprex v2.0.2


text:
Q: Different listeners for each notification Here's my code below,
var opt1 = {type: "basic",title: "Teva Noti1",message: "Don't click me!",iconUrl: "icon-phone.png"}
chrome.notifications.create("noti1",opt1,function(notificationId){
    chrome.notifications.onClicked.addListener(function(notificationId){
        alert("test1")
    })
});

var opt2 = {type: "basic",title: "Teva Noti2",message: "Don't click me!!!",iconUrl: "icon-phone.png"}
chrome.notifications.create("noti2",opt2,function(notificationId){
    chrome.notifications.onClicked.addListener(function(notificationId){
        alert("test2")
    })
});

I want to do different actions for each notifications. In my code, both alerts popped when I clicked any one of the notifications

A: You can try adding just one listener to the notifications and check which one was clicked in the listener:
chrome.notifications.onClicked.addListener(function(notificationId){
    if (notificationId == "noti1"){
        alert("test1");
    } else if (notificationId == "noti2"){
        alert("test2");
    });


text:
Q: How to give a name to containers and images in Docker compose? I have a simple ASP.NET Core Web with SQL Server project named PostOptimizer created with Visual Studio 2017 and deployed to docker containers. I want to give a name to the each image and container created by Docker-compose because it gives automatically names like this:
"dockercompose7669752967822022310_postoptimizer_1" and "dockercompose7669752967822022310_sql.data_1"
I could not figure out how to do it even after reading the Service configuration reference of Docker Compose where I expected to be able to put a subkey of build like name: "thecontainername", but it is not available. How to do it?
This is the content of my docker-compose.yml file:
version: '3.4'

services:
  sql.data:
    image: microsoft/mssql-server-linux:2017-latest
    environment:
      - SA_PASSWORD=Sql_Password1
      - ACCEPT_EULA=Y
    ports:
      - "5434:1433"

  postoptimizer:
    image: ${DOCKER_REGISTRY-}postoptimizer
    build:
      context: .
      dockerfile: PostOptimizer/Dockerfile
    depends_on:
      - sql.data

And this is the one of the Dockerfile:
FROM build AS publish
RUN dotnet publish PostOptimizer.csproj -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "PostOptimizer.dll"]

A: You can use the subkey container_name it will name the container with your given name.
version: '3.4'

services:
  sql.data:
    image: microsoft/mssql-server-linux:2017-latest
    environment:
      - SA_PASSWORD=Sql_Password1
      - ACCEPT_EULA=Y
    ports:
      - "5434:1433"
    container_name: sqldata

  postoptimizer:
    image: ${DOCKER_REGISTRY-}postoptimizer
    build:
      context: .
      dockerfile: PostOptimizer/Dockerfile
    depends_on:
      - sql.data
    container_name: postoptimizer


text:
Q: Creating a varbinary column in a mysql database using code first Entity framework 4.1 When I try to create a varbinary column "Data" using the entity framework and a code first method by defining data as.
Public Property Data() As Byte()

The problem is that when I run the program the script generated for this table doesnt specify a length for varbinary, which obviously breaks the execution and returns syntax errors from the mysql server.
CREATE TABLE `TestAction`(
    `ID` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `Name` mediumtext NOT NULL,
    `Data` varbinary,
    `Tested` datetime NOT NULL,
    `TestID` int NOT NULL);

I have already tried to initiate the byte array and added a max length attribute to the property but with no success. Has anyone succesfully done this? or can help it would be much appreciated
Answer----
Ive managed to solve this in the using the fluent api to force the entity framework to cast my byte() to varbinary and then setting the max length in the associated EntityTypeConfiguration class. I tried somthing similar before but conbined the length with the type name in the HasColumnType() method such that ...HasColumnType("varbinary(45) but that didnt work. The below line of code however solved my problem.
[Property](Function(P) P.Name).IsRequired().HasMaxLength(45).HasColumnType("varbinary")


text:
Q: formatBlock command does not overwrite existing block on list item Please see http://jsfiddle.net/4aQtk/3/
I tried to change style of li via execcommand("formatBlock",...). It works well on normal paragraph nodes, but makes nodes on list items.
Firefox 27 : OK, style elements(p, h1, h2) wrapped just text in li element. (expected)

text

another text

Chrome 33 : Failed, formatBlock command brake down ul into several uls and wrap ul with style elements.

            text

another text

How do I prevent creating nodes on them?

A: If you wrap the contents of the li into a div it works fine.

list item 1

list item 2

list item 3

An h1 tag isn't a valid child for an unordered list so it kind of wraps it outside the parent ul and puts a new ul inside the h1-tags. Because a h1 just replaces the div there is no problem anymore.
I hope this helped.
Edit:
The fact that it works with the paragraphs is it that it just replaces the p-tags with h1's so the best way should be if the h1's were inside the paragraphs.

A: From https://developer.mozilla.org/en-US/docs/Web/API/document.execCommand
Adds an HTML block-style tag around the line containing the current selection, replacing the block element containing the line if one exists (in Firefox, BLOCKQUOTE is the exception - it will wrap any containing block element). Requires a tag-name string to be passed in as a value argument. Virtually all block style tags can be used (eg. "H1", "P", "DL", "BLOCKQUOTE"). (Internet Explorer supports only heading tags H1 - H6, ADDRESS, and PRE, which must also include the tag delimiters < >, such as "".)
The
 element represents a list of items, therefor the formatBlock comand will wrap it the list with the Block elment (p, h1,...). Since this is not allowed for the li element, the list is split into multiple lists and the "list to format" is wrapped with the Block element.
Since your code triggers always on the li element, this is done again and again, because you are executing a formatingcomand, which is not intended to be used on this kind of element. @Steven Vanden Broucke posted a solution, how you can avoid this.
Since it is not exactly specified how this should be handled, I suggest doing that.
Edit:
I created a bug report at chromium for this issue. ( https://code.google.com/p/chromium/issues/detail?id=372925&thanks=372925&ts=1400009358 )


text:
Q: free cd ripper software on windows
Possible Duplicate:
What good, free audio CD ripping/extraction tools exist for Windows, and supporting multiple formats?

I am looking to find a cd ripper software package that is free for windows. I am looking to rip audio. It can be in .wave or mp3 format

A: I use the built in Windows Media Player to rip my CDs to MP3.

A: FreeRip
FreeRIP is an advanced CD to MP3 Converter that comes packed with features. At its core, FreeRIP reads audio from your CDs and allows you to save them to your coumputer in a variety of digital formats including WMA, MP3, Ogg, Wav, or FLAC audio files

A: Assuming that you're using Windows: If you are looking for third party software (not built-in), I would recommend BonkEnc.

BonkEnc is a free audio converter and
  CD ripper with support for various
  popular formats and encoders. It
  currently converts between MP3,
  MP4/M4A, WMA, Ogg Vorbis, FLAC, AAC,
  WAV and Bonk formats.
With BonkEnc you easily rip your audio
  CDs to MP3 or WMA files for use with
  your hardware player or convert files
  that do not play with other audio
  software. You can even convert whole
  music libraries retaining the folder
  and filename structure.
The integrated CD ripper supports the
  CDDB/freedb online CD database. It
  will automatically query song
  information and write it to ID3v2 or
  other title information tags.

There's even a portable version.


text:
Q: Parse.com - saveAll on PFObject does it account for 1 API call? I have an IOS app and I want to make sure I minimally use the API request to parse.com due to the 30/sec request limitation on the free tier. Could some one please clarify if saving disparate PFObjects in one method call "[PFObject saveAll:NSArray]" amounts to 1 API call or multiple API calls.
I need a definite answer since there is no clear answer anywhere on the interwebs. Parse.com support please help since I want to code the implementation differently if it accounts for many API requests in which case I will make sure I have better error handling when I save each pfObject separately.
Thanks.

A: From Parse:

saveAll attempts to do as few API calls as possible. Usually a call to saveAll results in only one API request. However, if any of the objects in the set has a relation to another unsaved object, that object will have to be saved first, resulting in more API requests.

https://www.parse.com/questions/saveall-how-many-api-requests

A: I'm using PFObject saveAllInBackground:block and regardless if there's a relation to another unsaved object, my api count in Analytics always increases by the number of objects in the array.

A: With Parse moving to the new pricing model they also changed the way batch operation requests (e.g. saveAll) are counted:
Where previously batch requests counted as a single request, it now takes n requests (where  n is the number of objects passed to saveAll).
There was a extension of the old way of counting for apps that were already depending on it, but as of February 2015 batch operations like saveAll use 1 request per object

A: From what I have seen using Parse, saving many PFObjects accounts as 1 API call.
However, the thing I don't know about is that if there are any limits on the number of objects to be saved at once and still be considered as 1 API call.
Also I recommend that you test it yourself. Try saving multiple objects at once and see how your API calls number change in the dashboard.
Please note that batch operations will fail as a whole if one object fails (e.g. object does not exist).

A: For me saveAll is also using as many API calls as objects are saved. I think they changed this with the new pricing and this is a non-sense, since one user saving multiple data at once generates an insane peak on the Api consumption.


text:
Q: Error with SalesForce authentication from C# Client(s) I am new to SalesForce and am working through getting up to speed with the basics as we will be beginning a large integration project next week.  For at least part of our integration we will need to access the SalesForce Rest API.  To that end another gentleman on my team and I have done some basic prototyping of calls using Postman with good success, in particular around OAuth2 authentication.  Our problem is that while everything seems to work fine in Postman, as soon as we switch to using C# to make the calls we begin getting an error instead of our auth token.  The response is HTTP Status 400 Bad Request and the content of the response is
{"error":"invalid_grant","error_description":"authentication failure"}.

Here is a sample of some of the C# code we have tried:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web;

namespace SFTokenTest
{
    internal class Program
    {
        private const string LoginUrl = "https://test.salesforce.com/services/oauth2/token";

        private static void Main(string[] args)
        {
            FormUrlEncodedContent content = new FormUrlEncodedContent(new []
            {
            new KeyValuePair<string, string>("grant_type",HttpUtility.UrlEncode("password")),
            new KeyValuePair<string, string>("password",HttpUtility.UrlEncode("PASSWORD")),
            new KeyValuePair<string, string>("username", HttpUtility.UrlEncode("USERNAME")),
            new KeyValuePair<string, string>("client_id",HttpUtility.UrlEncode("CLIENTID")),
            new KeyValuePair<string, string>("client_secret",HttpUtility.UrlEncode("CLIENTSECRET"))
            });
            HttpResponseMessage response;
            using (HttpClient client = new HttpClient())
            {
                response = client.PostAsync(LoginUrl, content).Result;
            }

            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            Console.WriteLine(response.StatusCode);

            Console.ReadLine();
        }
    }
}

Note: this is one of many implementations we have tried including using HttpWebRequest and WebClient, all with the same result.
In addition to our own code we have tried pulling code from the GitHub repository developerforce/Force.com-Toolkit-for-NET which also presented the same issue.
So far we are two days into troubleshooting this with no luck and we have stumped our SalesForce consultant as to why it is not working.  We tried resetting the Security Token this afternoon to no avail as well.  I have looked through a number of articles online (including on StackOverflow) most of which point to the following issues:

*

*Bad Credentials - We are using the same credentials successfully in Postman that we are attempting to use in our C# application(s) and we have tried re-coping and pasting them from the SalesForce UI and we have tried hand keying them into our code in case we were picking up invisible characters.  (By credentials I am including username, password, client_id, and client secret.)

*Bad or missing Content-Type header - we are definitely sending "application/x-www-form-urlencoded" which I have checked in each application a number of times (and have sniffed to verify it was actually being sent).

*Unencoded Parameters - I have seen this on a number of StackOverflow threads and have verified that we are encoding the parameters we are sending I the request body.

It seems there is something that Postman is doing that we are not in our requests, but I cannot seem to pinpoint what it is.  We even captured requests from both Postman and one of our clients and diffed them and they came back as identical.
Any help would be greatly appreciated.

A: If you haven't solved this yet, I think this might be your issue.
So according to this: https://help.salesforce.com/apex/HTViewSolution?id=000221207
Starting from June 2016 Salesforce will is disabling TLS 1.0 encryption accross its whole platform in a phased approach.
If you are on any version prior to .net 4.6, it means that you won't have TLS 1.1/1,2 switched on by default. There is a little list here of options you can use to enable it: https://help.salesforce.com/apex/HTViewSolution?id=000221207#Inboundintegrations
For a console application like yours, just tested on my side and the following worked for me (on .net 4.5.2):
        string LoginUrl = "https://login.salesforce.com/services/oauth2/token";
        //the line below enables TLS1.1 and TLS1.2
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
        FormUrlEncodedContent content = new FormUrlEncodedContent(new[]
        {
        new KeyValuePair<string, string>("grant_type", "password"),
        new KeyValuePair<string, string>("client_id","CLIENTID"),
        new KeyValuePair<string, string>("client_secret","CLIENTSECRET"),
        new KeyValuePair<string, string>("password","PASSWORD + SECURITYTOKEN"),
        new KeyValuePair<string, string>("username", "USERNAME")
        });
        HttpResponseMessage response;
        using (HttpClient client = new HttpClient())
        {
            response = client.PostAsync(LoginUrl, content).Result;
        }
        Console.WriteLine(response.Content.ReadAsStringAsync().Result);
        Console.WriteLine(response.StatusCode);
        Console.ReadLine();


text:
Q: Unable to install WMF 4.0 for Window 7 SP1 I am trying to install Windows update for Installing Windows PowerShell 4.0.
The Update is : Windows6.1-KB2819745-x64-MultiPkg.msu at This Link
Following are my system Specifications:

I already have prerequisites to install WMF 4.0 which are SP1 and .NET 4.5.
I get a simple plain error with no details that update can not be installed.

what can i do to install this particular update?
Just in case anyone want to know, I need to install this update to Install KVM required for building VNext Apps.


text:
Q: What is the best way to pass around User info in a web app? I always roll my own authentication -- I have a control issues.
In a web app using Web Forms, which is a better way to drag along user information through a site:

*

*Save User object to Session, grab object from Session on page load/init.

*Save UserId to Session, instantiate new user obj on page load/init.

*A better way that I don't know about.

Assume 1 web server is being used.
I prefer #2 b/c it guarantees up-to-date data, but it does make more trips to the db.
Please give advantages/disadvantages.
-iw

A: Door #2 Ian.

Rolling your own can definitely have its drawbacks - especially in security (Such as liability, which is ALL on you now).  Save your user data in the database.  When the user logs in then check to see if they are authenticated and then just take their user authorization with them in the session which should, in my opinion, be stored on your filesystem (not database) if this is how you are handling security.


text:
Q: Fluid icon relative to parent In my fiddle, There are two buttons with icons. Currently I am using fixed width and heightfor these icons, how can I use percentage relative to the parent size of these icons? Example: 80%?
Fixed width and height of my icons:
    .gc_footer_nix_icon_img, .gc_footer_use_icon_img {
        width: 25px;
        height: 25px;
    }

HTML:

$100 Amount

Test subtitle

Test terms

Test Date

Use

Nix

CSS:
body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.gc_gift {
    margin-top:1.5%;
    margin-left:auto;
    margin-right:auto;
    margin-bottom:1.5%;
    height: auto;
    width: 97%;
    position:relative;
    overflow: scroll;
    webkit-overflow-scrolling: touch;
    border:1px solid #D1D1D1;
}
.gc_gift_inner {
    font-size:1em;
    text-align: left;
    background-color: #ffffff;
    border:0px solid #D1D1D1;
    display:table;
    margin-top:2.5%;
    margin-left:auto;
    margin-right:auto;
    margin-bottom:2.5%;
    height: auto;
    width: 95%;
    position:relative;
    overflow: scroll;
    webkit-overflow-scrolling: touch;
}
.gc_amount {
    color: red;
    font-size:2em;
}
.gc_subtitle {
    font-weight: bold;
    font-size: 1em;
    color: #707070;
}
.gc_hr {
    width: 100%;
    position: relative;
    margin: auto;
    border-color: #D1D1D1;
    border-style: solid;
    border-width: 1px 0 0 0;
}
.gc_terms {
    font-size: 0.8em;
    color: #707070;
}
.gc_footer {
    width: 95%;
    display: table;
    position: relative;
}
.gc_footer_expiry {
    display: table-cell;
    vertical-align: bottom;
    font-size: 0.8em;
    font-weight: bold;
    width: 40%;
    color: #707070;
    border: 0px solid yellow;
}
.gc_footer_use_nix {
    display: table-cell;
    vertical-align: middle;
    width: 60%;
    border:0px solid green;
    margin: auto;
    text-align: right;
}
.gc_footer_use {
    display: inline-block;
    vertical-align: middle;
    background-color: #3F6EB6;
    border-radius: 1px;
    padding: 2%;
    position: relative;
    border:0px solid red;
    margin-right: 5%;
}
.gc_footer_use_txt {
    text-align: right;
    display: table-cell;
    vertical-align: middle;
    color: white;
    font-size: 1em;
    font-weight: bold;
}
.gc_footer_use_icon {
    text-align: right;
    display: table-cell;
    vertical-align: middle;
}
.gc_footer_nix {
    display: inline-block;
    vertical-align: middle;
    background-color: #D61920;
    border-radius: 1px;
    color: white;
    font-size: 1em;
    border: 0x solid green;
    padding: 2%;
    margin-right: 5%;
}
.gc_footer_nix_txt {
    text-align: center;
    display: table-cell;
    vertical-align: middle;
    position: relative;
    border: 0px solid blue;
    width: 50%;
    font-weight: bold;
}
.gc_footer_nix_icon {
    text-align: center;
    display: table-cell;
    vertical-align: middle;
    position: relative;
    border: 0px solid yellow;
    width: 50%;
}
.gc_footer_button_wrapper {
    display: table;
    width: 100%;
    position: relative;
    border: 0px solid blue;
}
.gc_container {
    background-color:#ffffff;
    height: auto;
    width: 90%;
    display:table;
    margin-top:3%;
    margin-bottom:3%;
    margin-left:auto;
    margin-right:auto;
    position:relative;
    border:1px solid #D1D1D1;
}
.gc_amount, .gc_subtitle, .gc_terms, .gc_footer {
    border: 0px solid green;
    display:table;
    width:100%;
    padding-top:0.3em;
    padding-bottom:0.3em;
}
.gc_footer_nix_icon_img, .gc_footer_use_icon_img {
    width: 25px;
    height: 25px;;

}

A: You need to set width to gc_footer_nix and gc_footer_use , and then you'll be able to set the width on the images . Fiddle: http://jsfiddle.net/TgW2D/7/


text:
Q: shell script to truncate all MySql tables I'm looking for a Unix shell script that will truncate all tables in a schema. A similar question was already asked, but I have some additional requirements which makes none of the provided answers satisfactory:

*

*Must be a Unix shell script (i.e. no python, perl, PHP)

*The script must truncate the tables in an order which respects foreign key constraints

*I'd prefer not to have to use a stored proc

Thanks in advance,
Don

A: How about something cheeky like this:
mysqldump  --no-data mydb | mysql mydb

Gets a dump of the schema and replays it into the database!
Alternatively, check out mk-find in Maatkit, you should be able to do something like this:
mk-find -exec "truncate %s"

Description of mk-find:

This tool is the MySQL counterpart to
  the UNIX 'find' command. It accepts
  tests (such as "find all tables larger
  than 1GB") and performs actions, such
  as executing SQL ("DROP TABLE %s").
  With this tool at your disposal you
  can automate many tedious tasks, such
  as measuring the size of your tables
  and indexes and saving the data for
  historical trending, dropping old
  scratch tables, and much more. It is
  especially useful in periodic
  scheduled tasks such as cron jobs.


text:
Q: How to distribute stock quantity from a single cell to different aging brackets based on the the aging brackets quantities? We have a table with item codes and current stock quantity and quantities in aging brackets whenever they were received (1-90, 91-120, etc) as follows:

I need to distribute the STOCK_AS_ON_DATE quantity in the age brackets until no balance quantity is left.
Example:
Item A's STOCK_AS_ON_DATE is 40377, in A1TO90 column we can see that 4000 quantities were received, in A91TO120, 4000 quantities were received, in A121TO270,  13000 quantities were received, we want to distribute the STOCK_AS_ON_DATE quantity in such a way in the other aging fields until the total of all the aging fields equals STOCK_AS_ON_DATE. In this item's case, when we reach column A631TO720, 1377 quantity balance is left out of the 40377. If any aging bracket value is 0, we have to leave it as it is and move forward.

Below is the Oracle query to create a sample table and data:
CREATE TABLE AA_STK_AGING
(
  ITEM              NVARCHAR2(10),
  STOCK_AS_ON_DATE  NUMBER,
  A1TO90            NUMBER,
  A91TO120          NUMBER,
  A121TO270         NUMBER,
  A271TO360         NUMBER,
  A361TO450         NUMBER,
  A451TO540         NUMBER,
  A541TO630         NUMBER,
  A631TO720         NUMBER,
  A721PLUS          NUMBER
)
LOGGING
NOCOMPRESS
NOCACHE
NOPARALLEL
MONITORING;

SET DEFINE OFF;
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('A', 40377, 4000, 4000, 13000,
    0, 8340, 1660, 8000, 4400,
    223380);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('B', 48, 50, 0, 160,
    45, 50, 90, 70, 120,
    2913);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('C', 3269, 7100, 6600, 24100,
    9925, 0, 27975, 23700, 20000,
    929437);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('D', 3330, 3000, 4400, 6100,
    1700, 0, 10400, 3000, 18200,
    628437);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('E', 13225, 3000, 0, 25100,
    4500, 4500, 2900, 110, 14800,
    171590);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('F', 1759, 526, 478, 0,
    0, 0, 502, 484, 0,
    13308);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('G', 2528, 0, 3500, 0,
    3500, 0, 3000, 0, 0,
    43706);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('H', 163, 950, 550, 2850,
    1480, 735, 2025, 1450, 875,
    52278);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('I', 158, 520, 200, 914,
    350, 420, 540, 300, 150,
    10557);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('J', 254, 750, 350, 1650,
    1050, 570, 1300, 1070, 710,
    25886);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('K', 75864, 20400, 0, 34800,
    32400, 0, 32400, 28800, 34800,
    701550);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('L', 18074, 15525, 0, 0,
    41480, 27630, 0, 28850, 0,
    861545);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('M', 45247, 20000, 0, 0,
    35000, 60000, 0, 0, 0,
    834240);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('N', 3332, 4125, 0, 5625,
    2690, 3015, 2035, 3380, 5290,
    152709);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('O', 287, 522, 132, 1878,
    864, 66, 725, 795, 852,
    36503);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('P', 338, 401, 134, 1113,
    484, 127, 627, 745, 813,
    18715);
Insert into AA_STK_AGING
   (ITEM, STOCK_AS_ON_DATE, A1TO90, A91TO120, A121TO270,
    A271TO360, A361TO450, A451TO540, A541TO630, A631TO720,
    A721PLUS)
 Values
   ('Q', 892, 650, 1000, 3200,
    1800, 0, 3400, 3600, 2200,
    113347);
COMMIT;

We have tried using the CASE statement but as we move further to other columns it's becoming complicated.
CASE WHEN A1TO90 < STOCK_AS_ON_DATE THEN A1TO90 ELSE ( CASE WHEN A1TO90 >= STOCK_AS_ON_DATE THEN STOCK_AS_ON_DATE END ) END

There must be some other way which we are not aware of. Please suggest a simpler way to achieve our results. Thanks in advance.

A: A brute-force approach might be to use least() to decide whether to use the column quantity or the remainder from adding up all the columns to the left; with greatest() to stop any negative values. Something like:
select ITEM,
  STOCK_AS_ON_DATE,
  least(A1TO90,    STOCK_AS_ON_DATE) as A1TO90,
  least(A91TO120,  greatest(0, STOCK_AS_ON_DATE - A1TO90)) as A91TO120,
  least(A121TO270, greatest(0, STOCK_AS_ON_DATE - A1TO90 - A91TO120)) as A121TO270,
  least(A271TO360, greatest(0, STOCK_AS_ON_DATE - A1TO90 - A91TO120 - A121TO270)) as A271TO360,
  least(A361TO450, greatest(0, STOCK_AS_ON_DATE - A1TO90 - A91TO120 - A121TO270 - A271TO360)) as A361TO450,
  least(A451TO540, greatest(0, STOCK_AS_ON_DATE - A1TO90 - A91TO120 - A121TO270 - A271TO360 - A361TO450)) as A451TO540,
  least(A541TO630, greatest(0, STOCK_AS_ON_DATE - A1TO90 - A91TO120 - A121TO270 - A271TO360 - A361TO450 - A451TO540)) as A541TO630,
  least(A631TO720, greatest(0, STOCK_AS_ON_DATE - A1TO90 - A91TO120 - A121TO270 - A271TO360 - A361TO450 - A451TO540 - A541TO630)) as A631TO720,
  least(A721PLUS,  greatest(0, STOCK_AS_ON_DATE - A1TO90 - A91TO120 - A121TO270 - A271TO360 - A361TO450 - A451TO540 - A541TO630 - A631TO720)) as A721PLUS
from AA_STK_AGING;

which is ugly and doesn't scale very well, but isn't really complicated per se. (This gives zero for the columns after you've exhausted the stock; your example had null for the final column for item A, but not sure if it matters; making it null is just a bit more complicated.)
If you want the total column you showed - again not sure you really do - you can use that as a CTE or inline view:
select t.*,
  A1TO90 + A91TO120 + A121TO270 + A271TO360 + A361TO450 + A451TO540 + A541TO630 + A631TO720 + A721PLUS as TOTAL
from (
  select ITEM,
    STOCK_AS_ON_DATE,
    least(A1TO90,    STOCK_AS_ON_DATE) as A1TO90,
    ...
  from AA_STK_AGING
) t;

db<>fiddle
If you are on 11g then you could unpivot your columns to rows:
select *
from AA_STK_AGING
unpivot (QUANTITY for BUCKET in (A1TO90 as 1, A91TO120 as 91, A121TO270 as 121,
  A271TO360 as 271, A361TO450 as 361, A451TO540 as 451, A541TO630 as 541,
  A631TO720 as 631, A721PLUS as 721));

then perform a similar calculation using a running total:
select ITEM, STOCK_AS_ON_DATE, BUCKET,
  least(QUANTITY,
    greatest(0, STOCK_AS_ON_DATE + QUANTITY
      - sum(QUANTITY) over (partition by ITEM order by BUCKET))) as QUANTITY
from AA_STK_AGING
unpivot (QUANTITY for BUCKET in (A1TO90 as 1, A91TO120 as 91, A121TO270 as 121,
    A271TO360 as 271, A361TO450 as 361, A451TO540 as 451, A541TO630 as 541,
    A631TO720 as 631, A721PLUS as 721)
);

and pivot that back to columns:
select *
from (
  select ITEM, STOCK_AS_ON_DATE, BUCKET,
    least(QUANTITY,
      greatest(0, STOCK_AS_ON_DATE + QUANTITY
        - sum(QUANTITY) over (partition by ITEM order by BUCKET))) as QUANTITY
  from AA_STK_AGING
  unpivot (QUANTITY for BUCKET in (A1TO90 as 1, A91TO120 as 91, A121TO270 as 121,
    A271TO360 as 271, A361TO450 as 361, A451TO540 as 451, A541TO630 as 541,
    A631TO720 as 631, A721PLUS as 721)
  )
)
pivot (max(quantity) for (bucket) in (1 as A1TO90, 91 as A91TO120, 121 as A121TO270,
  271 as A271TO360, 361 as A361TO450, 451 as A451TO540, 541 as A541TO630,
  631 as A631TO720, 721 as A721PLUS)
)
order by ITEM;

db<>fiddle
If you're on 10g then you could manually unpivot and pivot but it probably isn't worth the complication over the brute-force approach.
Both approaches give:
ITEM STOCK_AS_ON_DATE A1TO90 A91TO120 A121TO270 A271TO360 A361TO450 A451TO540 A541TO630 A631TO720 A721PLUS TOTAL
---- ---------------- ------ -------- --------- --------- --------- --------- --------- --------- -------- -----
A               40377   4000     4000     13000         0      8340      1660      8000      1377        0 40377
B                  48     48        0         0         0         0         0         0         0        0    48
C                3269   3269        0         0         0         0         0         0         0        0  3269
D                3330   3000      330         0         0         0         0         0         0        0  3330
E               13225   3000        0     10225         0         0         0         0         0        0 13225
F                1759    526      478         0         0         0       502       253         0        0  1759
G                2528      0     2528         0         0         0         0         0         0        0  2528
H                 163    163        0         0         0         0         0         0         0        0   163
I                 158    158        0         0         0         0         0         0         0        0   158
J                 254    254        0         0         0         0         0         0         0        0   254
K               75864  20400        0     34800     20664         0         0         0         0        0 75864
L               18074  15525        0         0      2549         0         0         0         0        0 18074
M               45247  20000        0         0     25247         0         0         0         0        0 45247
N                3332   3332        0         0         0         0         0         0         0        0  3332
O                 287    287        0         0         0         0         0         0         0        0   287
P                 338    338        0         0         0         0         0         0         0        0   338
Q                 892    650      242         0         0         0         0         0         0        0   892

If you were on 12c or above you could look at match_recognize(), but you seem to be on either 10g or 11g.


text:
Q: Scripting parallel FTP downloads (multiple connections) on Windows I need a scripting solution to download several (more then 100) websites by FTP for backup purposes. For each website I want a scripting solution which supports 10 parallel connections to only one website.

*

*Each website has his own FTP address.

*Splitting the complete task in 10 different batches is ok but still there will be 1 connection to 1 server which cause very a very slow download.
Create tars on the server is not a option and is out of this question :-)

I'm using Windows 8.1, 64-bit.
I tried Windows FTP but that supports only 1 parallel connections to 1 server.
Also WinSCP is not supporting more then 1 parallel connection to 1 FTP server command line mode. I tried several options and maybe I'm doing something wrong here???
download.bat > this file is started with admin rights
md n:\backupftp\ithaka.im\public_html
winscp.exe /script="ithaka.txt"

ithaka.txt
open ftp://xxx:xxxxx@ftp.ithaka.im/domains/ithaka.im/public_html
lcd n:\backupftp\ithaka.im\public_html
get *

The winscp.exe and winscp.com are portable executables in the same directory as the download.bat and ithaka.txt
As a result of this I don't see the GUI interface. Only a task in the task manager. If I turn on logging I see only 1 connection to 1 FTP server at a time. No parallel downloads from 1 FTP server.
If I change the download.bat into (notice that I change .exe to .com):
md n:\backupftp\ithaka.im\public_html
winscp.com /script="ithaka.txt"

The result will be:
modules                   |            0 B |    0,0 KB/s | binary |   0%
php                       |            0 B |    0,0 KB/s | binary |   0%
php.test                  |           4 KB |    6,9 KB/s | binary | 100%
php.module                |           7 KB |    6,6 KB/s | binary | 100%
php.install               |           1 KB |    1,8 KB/s | binary | 100%
php.info                  |          274 B |    1,3 KB/s | binary | 100%
block                     |            0 B |    1,3 KB/s | binary |   0%

etc etc etc.. these downloads are not parallel and not supported by WinSCP.
So:

*

*Do I something wrong with WINSCP

*Is there a FTP scripting solution which support this on Windows? I looked into several alternatives but they all have graphical user interfaces which I don't want..

A: WinSCP scripting does not support parallel transfers on its own.
But you can run multiple WinSCP scripts in parallel.
You just have to split the set of files/directories to batches.
There's actually a ready-made PowerShell script based on WinSCP .NET assembly that does this.
See Automating download in parallel connections over SFTP/FTP protocol.
You can run the script (say parallel_download.ps1) like:
powershell.exe -File parallel_download.ps1 -sessionUrl ftp://xxx:xxxxx@ftp.ithaka.im/ ^
    -remotePath /domains/ithaka.im/public_html/ ^
    -localPath n:\backupftp\ithaka.im\public_html\ ^
    -batches 3

The above command can be directly used in a batch file (.bat).
Or executed from a command-line, if merged into a single line with all ^ removed.


text:
Q: Certificate request seems stuck after storing new private key I've been trying to roll out our an environment on Kubernetes using LetsEncrypt with CertManager to provision certificates.
However, it seems that the certificate, for whatever reason, can't be provided.
I've been going through the steps over at
https://cert-manager.io/docs/faq/troubleshooting/ but I get stuck on 'Stored new private key in temporary Secret Resource "xxx"', and I cannot find any troubleshooting steps to solve this.
The events list from my past few attempts to reset the certificate
My ingress.yaml looks as follows:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: myname-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  tls:
  - hosts:
    - app.mydomain.io
    secretName: tls-secret
  rules:
  - host: app.mydomain.io
    http:
      paths:
      - backend:
          serviceName: mydomain-identity-v1
          servicePort: 80
        path: /login(/|$)(.*)
      - backend:
          serviceName: mydomain-account-v1
          servicePort: 80
        path: /account(/|$)(.*)

With the following cluster-issuer:
apiVersion: cert-manager.io/v1alpha2
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: ***
    privateKeySecretRef:
      name: letsencrypt-prod
    solvers:
    - http01:
        ingress:
          class: nginx

I have followed the following guide to get everything installed:
https://learn.microsoft.com/en-us/azure/aks/ingress-static-ip#create-a-ca-cluster-issuer
It is working on our development environment just fine, however for this new environment it seems to not want to issue an actual CertificateRequest. The ClusterIssuer resource is showing as ready
Has anyone encountered this before, or know what to do? My searches so far have yielded nothing.

A: I have done this implementation successfully in Azure AKS clusters, you can follow this way -

*

*Install cert-manager from here

*Then follow these steps from this stackoverflow post
Make one clusterIssuer or you can make individual issuer too, once you patch the hostname to ingress, then the tls-certificate in that namespace will be autogenerated by Jetstack after the acme-challenge validation
Kindly make sure to map the IP of loadbalancer nginx/traefik etc to DNS/hostname

A: I was using a newer version of cert-manager on this environment than I was on the other one. There must have been some mismatch between my kubernetes version and the version of cert-manager causing the issue. By reverting to the same cert-manager version the problem has resolved itself.


text:
Q: LWC Component how to use only custom fields how to fetch only custom fields in this code
I have created a LW component for getting object information when I enter the object name in the search I get all fields in that object but I need only custom fields to be listed when I enter the object name.
import { LightningElement, wire, track } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import {getObjectInfo} from
export default class WireGetObjectInfo extends LightningElement {
    objectApiNameInputValue = 'Account';
    objectApiName;
    @track objectInfo;
    fieldApiNameInputValue;
    fieldApiName;
    @wire(getObjectInfo, { objectApiName: '$objectApiName' })
    objectInfo;
    objectNameChange(event) {
        this.objectApiNameInputValue = event.target.value;
    }
    handleBtnClick() {
        this.objectApiName = this.objectApiNameInputValue;
    }
    fieldNameChange(event) {
        this.fieldApiNameInputValue = event.target.value;
    }
    get fieldOptions() {
        let fieldList = [];
        if (this.objectInfo) {
            if (this.objectInfo.data) {
                if (this.objectInfo.data.fields) {
                    for (var i = 0; i < Object.entries(this.objectInfo.data.fields).length; i++) {
                        fieldList.push({
                            label: Object.entries(this.objectInfo.data.fields)[i][0],
                            value: Object.entries(this.objectInfo.data.fields)[i][0]
                        });
                    }
                }
            }
        }
        return fieldList;
    }

}

JS FILE
<template>
    <lightning-card title="Get Object Information " icon-name="custom:custom67">
        <lightning-layout multiple-rows>
            <lightning-layout-item size="12" small-device-size="12" medium-device-size="12" large-device-size="12"
                padding="around-small">

                    <lightning-input value={objectApiNameInputValue} placeholder="Enter object API name"
                        onchange={objectNameChange} label="Search"></lightning-input>

                        <lightning-button label="Get Object Info" onclick={handleBtnClick}></lightning-button>

                    <template if:true={objectInfo.data}>
                        <lightning-combobox name="fieldApiName" label="Select Field To Get Informtion" value=""
                            placeholder="Select Field Api Name" options={fieldOptions} onchange={fieldNameChange}
                            required>
                        </lightning-combobox>
                    </template>

            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>

HTML FILE
public with sharing class dynamicObjectList {
private static String baseUrl = URL.getSalesforceBaseUrl().toExternalForm()
+ '/services/data/v46.0/tooling/query?q=Select+MetadataComponentId,MetadataComponentName,RefMetadataComponentName,RefMetadataComponentId,MetadataComponentType+from+MetadataComponentDependency+where+MetadataComponentId=\'00NIw0000011xDN\'';

@AuraEnabled(cacheable=true)

public static string getfields(string objectname, string fieldApiName){
string query = 'select DeveloperName,QualifiedApiName from FieldDefinition where EntityDefinitionId = :objectname and QualifiedApiName =:fieldApiName ORDER BY DeveloperName ASC';
list lstObject = Database.query(query);
HTTPRequest req = new HTTPRequest();
req.setEndpoint(baseUrl);
req.setMethod('GET');
// OAuth header
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
req.setHeader('Content-Type', 'application/json');
    Http h = new Http();
    HttpResponse res = h.send(req);
   return res.getBody();

}
}
Apex class

A: If you want just the custom fields, you can filter for that:
get fieldOptions() {
  if(this.objectInfo.data) {
    return Object.entries(this.objectInfo.data.fields)
      .filter(([_,{custom}])=>custom)
      .map(([value,{label}])=>({value,label}));
  }
  return [];
}

Note a lot of optimizations here:
if(this.objectInfo.data) {

Up to this point will always be safe to check in a wire-bound property, as these are initialized before your first getter is ever called.
    return Object.entries(this.objectInfo.data.fields)

Converts the fields of an object into an array.
      .filter(([_,{custom}])=>custom)

Takes the field describe info from the second index (array index 1), pulls out the custom property, and then returns only those entries that are custom fields.
      .map(([value,{label}])=>({value,label}));

Converts the filtered array into a label-value pair.


text:
Q: Switching into a network namespace does not change /sys/class/net? The Linux man page for network namespaces(7) says:

Network namespaces provide isolation of the system resources associated with networking: [...], the /sys/class/net directory, [...].

However, simply switching into a different network namespace doesn't seem to change the contents of /sys/class/net (see below for how to reproduce). Am I just mistaken here in thinking that the setns() into the network namespace is already sufficient? Is it always necessary to remount /sys in order to get the correct /sys/class/net matching the currently joined network namespace? Or am I missing something else here?
Example to Reproduce
Take an *ubuntu system, find the PID of the rtkit-daemon, enter the daemon's network namespace, show its network interfaces, and then check /sys/class/net:
$ PID=`sudo lsns -t net -n -o PID,COMMAND | grep rtkit-daemon | cut -d ' ' -f 2`
$ sudo nsenter -t $PID -n
# ip link show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
# ls /sys/class/net
docker0  enp3s0  lo  lxcbr0  ...

Please notice that while ip link show correctly only shows lo, /sys/class/net shows all network interfaces visible in the "root" network namespace (and "root" mount namespace).
In the case of rtkit-daemon also entering the mount namespace of it doesn't make a difference: sudo nsenter -t $PID -n -m and then ls /sys/class/net still shows network interfaces not present in the network namespace.
"Fix"
Many kudos to @Danila Kiver for explaining what really is going on behind the Linux kernel scenes. Remounting sysfs while the correct network namespace is joined will show the correct entries in /sys/class/net:
$ PID=`sudo lsns -t net -n -o PID,COMMAND | grep rtkit-daemon | cut -d ' ' -f 2`
$ sudo nsenter -t $PID -n
# MNT=`mktemp -d`
# mount -t sysfs none $MNT
# ls $MNT/class/net/
lo
# umount $MNT
# rmdir $MNT
# exit

So this now yields the correct results in /sys/class/net.

A: Let's look into man 5 sysfs:
/sys/class/net
    Each  of the entries in this directory is a symbolic link representing
    one of the real or virtual networking devices that are visible in
    the network namespace of the process that is accessing the directory.

So, according to this manpage, the output of ls /sys/class/net must depend on the network namespace of the ls process. But... Actual behavior does not seem to be as described in this manpage. There is a nice kernel documentation about how it works.
Each sysfs mount has a namespace tag associated with it. This tag is set when sysfs gets mounted and depends on the network namespace of the calling process. Each sysfs entry (e.g. an entry in /sys/class/net) also may have a namespace tag associated with it.
When you iterate over the sysfs directory, the kernel obtains the namespace tag of the sysfs mount, and then it iterates over the entries, filtering out those which have different namespace tag.
So, it turns out that the results of iterating over the /sys/class/net depend on the network namespace of the process which initiated /sys mount rather than on the network namespace of the current process, thus, you must always mount /sys in the current network namespace (from any process belonging to this namespace) to see the correct results.