text:
Q: How to navigate from master page to detail page view using routing mechanism? sap.ui.define([
    "sap/ui/core/UIComponent",
    "sap/ui/Device",
    "RoutNav/model/models"
], function (UIComponent, Device, models) {
    "use strict";

    return UIComponent.extend("RoutNav.Component", {
        metadata: {
            manifest: "json",
            rootView: "RoutNav.view.View1",

            routes: [
                {
                    pattern: "",
                    name: "Master",
                    view: "Master",
                    targetAggregation: "masterPages",
                    targetControl: "idAppControl",
                    subroutes: [
                        {
                            pattern: "tab:",
                            name: "Detail",
                            view: "Detail"
                        }
                    ]
                }
            ]
        },

        /**
         * The component is initialized by UI5 automatically during the startup of the app and calls the init method once.
         * @public
         * @override
         */
        init: function () {
            // call the base component's init function
            UIComponent.prototype.init.apply(this, arguments);

            // set the device model
            this.setModel(models.createDeviceModel(), "device");
        }
    });
});

I have tried this, in master.view.xml page I have just given a title.  It's not working.

A: you missing config code

 routing : {
      config : {
        routerClass : Application_Name.MyRouter,
        viewType : "XML",
        viewPath : "Application_Name.view",
        targetAggregation : "detailPages",
        transition: "slide",
        clearTarget : false
      },
      routes : [
        {
            pattern : "",
            name : "Master",
            view : "Master",
            targetAggregation : "masterPages",
            targetControl : "idAppControl",
            subroutes : [
                {
                    pattern : "tab:",
                    name : "Detail",
                    view : "Detail"
                }
            ]
        }
    ]
 }

A: Steps to navigate master to detail..using JSON

*

*Master.view.xml

<List id="list" growing="true" mode="SingleSelectMaster"
    growingThreshold="100" growingScrollToLoad="true" select="onSelect"
    noDataText="No Data">
</List>

*Master.controller.js

    navBack: function(){
  var oRouter = new sap.ui.core.UIComponent.getRouterFor(this);
  oRouter.myNavBack("S1");
 },
 onInit: function(){
  this.data = new sap.ui.model.json.JSONModel("Model/data.json");
  sap.ui.getCore().setModel(this.data);

  var list = this.getView().byId("list");
  list.bindItems("/employees", new sap.m.StandardListItem({
   title: "{fname}"
  }));
  list.setModel(this.data);
 },
 onSelect: function(evt){
  var index = evt.getParameter("listItem").getBindingContext().getPath();
  index.charAt(index.length-1)-2;

  var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
  oRouter.navTo("Detail", {
   key : evt.getParameter("listItem").getTitle()
  });
 }

*Detail.view.xml

<Table onSelect="onpress" id="table" class="sapUiSmallMarginTop">
   <headerToolbar>
  <Toolbar>
   <Title level="H2" text="Personal Details" />
   <ToolbarSpacer />
   <Button press="onTableSettings" icon="sap-icon://drop-down-list" />
  </Toolbar>
 </headerToolbar>
  <columns>
   <Column>
    <Text text="Last_Name" key="name"/>
   </Column>
   <Column>
    <Text text="Mobile" />
   </Column>
   <Column>
       <Text text="Age" key="Age" />
   </Column>
  </columns>
 </Table>

*Detail.controller.js

onInit : function() {
  this.getRouter().attachRoutePatternMatched(this.onRouteMatched, this);

 },

 onRouteMatched : function(oEvent) {
  // debugger;
  this.data = new sap.ui.model.json.JSONModel("Model/data.json");
  this.getView().setModel(this.data);

  var dataKey = oEvent.getParameter("arguments").key;

  this.getView().getModel().attachRequestCompleted(function() {
   var data2 = this.getView().getModel().getData().employees;
   var otable = this.getView().byId("table");

   for (var i = 0; i < data2.length; i++) {
    if (data2[i].fname === dataKey) {
     otable.bindItems("/employees", new sap.m.ColumnListItem({
      cells : [ new sap.m.Text({
       text : "{lname}",
      }), new sap.m.Text({
       text : "{mobile}"
      }), new sap.m.Text({
       text : "{age}"
      }) ]
     }));
    }
    otable.setModel(this.data);
   }
  }, this);

 },
 getRouter : function() {
  return sap.ui.core.UIComponent.getRouterFor(this);
 },

*Component.js

 routing : {
      config : {
        routerClass : Application_Name.MyRouter,
        viewType : "XML",
        viewPath : "Application_Name.view",
        targetAggregation : "detailPages",
        transition: "slide",
        clearTarget : false
      },
      routes : [
        {
          pattern : "",
          name : "main",
          view : "Master",
          targetAggregation : "masterPages",
          targetControl : "idAppControl",
           subroutes : [
                        {
                      pattern:"Detail/{key}",
                name: "Detail",
                view: "Detail",
                targetAggregation: "detailPages",
                     }
          ]
        }
      ]
    }

*MyRouter.js

Just find and replace you Application_Name in MyRouter.js file

jQuery.sap.require("sap.m.routing.RouteMatchedHandler");
jQuery.sap.require("sap.ui.core.routing.Router");
jQuery.sap.declare("Application_Name.MyRouter");

sap.ui.core.routing.Router.extend("Application_Name.MyRouter", {

 constructor : function() {
  sap.ui.core.routing.Router.apply(this, arguments);
  this._oRouteMatchedHandler = new sap.m.routing.RouteMatchedHandler(this);
 },

 myNavBack : function(sRoute, mData) {
  var oHistory = sap.ui.core.routing.History.getInstance();
  var sPreviousHash = oHistory.getPreviousHash();

  //The history contains a previous entry
  if (sPreviousHash !== undefined) {
   window.history.go(-1);
  } else {
   var bReplace = true; // otherwise we go backwards with a forward history
   this.navTo(sRoute, mData, bReplace);
  }
 },
 myNavToWithoutHash : function (oOptions) {
  var oSplitApp = this._findSplitApp(oOptions.currentView);

  // Load view, add it to the page aggregation, and navigate to it
  var oView = this.getView(oOptions.targetViewName, oOptions.targetViewType);
  oSplitApp.addPage(oView, oOptions.isMaster);
  oSplitApp.to(oView.getId(), oOptions.transition || "show", oOptions.data);
 },

 backWithoutHash : function (oCurrentView, bIsMaster) {
  var sBackMethod = bIsMaster ? "backMaster" : "backDetail";
  this._findSplitApp(oCurrentView)[sBackMethod]();
 },

 destroy : function() {
  sap.ui.core.routing.Router.prototype.destroy.apply(this, arguments);
  this._oRouteMatchedHandler.destroy();
 },

 _findSplitApp : function(oControl) {
  var sAncestorControlName = "idAppControl";

  if (oControl instanceof sap.ui.core.mvc.View && oControl.byId(sAncestorControlName)) {
   return oControl.byId(sAncestorControlName);
  }

  return oControl.getParent() ? this._findSplitApp(oControl.getParent(), sAncestorControlName) : null;
 }

});

Don't forget to add MyRouter.js file

A: "routing": {
        "config": {
            "routerClass": "sap.m.routing.Router",
            "viewPath": "mc7prod.view",
            "viewType": "XML",
            "controlAggregation": "pages",
            "clearTarget": "false"
     },
     "routes": [
     {
        "pattern": "",
        "name": "Index",
        "view": "Index",
        "targetControl": "appId"
     },
     {
        "pattern": "split",
        "name": "AppMasterDetail",
        "view": "AppMasterDetail",
        "targetControl": "appId",
        "subroutes": [
            {
                "pattern": "master/{entity}",
                "name": "master",
                "view": "TS_Master",
                "targetAggregation": "masterPages",
                "preservePageInSpplitContainer": true,
                "targetControl": "idAppMaDeControl",
                "subroutes": [
                    {
                        "pattern": "detail/{entity}",
                        "name": "detail",
                        "view": "TS_Detail",
                        "targetAggregation": "detailPages"
                    }
                ]}]
        },


text:
Q: can't figure out how to write a simple DB2 function It seems simple but I tried hours to figure it out but I can't..
I wish to create a db2 function which works like coalesce.
The difference is it looks for the value of the first parameter, if it is an empty string which is ''. Then It will use the second parameter.
That's the query I did
 CREATE FUNCTION COALESCEEMPTY (X1 XML, X2 XML)
 RETURNS XML
 LANGUAGE SQL
 CONTAINS SQL
 NO EXTERNAL ACTION
 DETERMINISTIC
 CASE X1
 WHEN '' THEN RETURN X2;
 ELSE RETURN X1;
 END CASE;

and this is the error code i get from db2.
16:09:47  [CREATE - 0 row(s), 0.000 secs]  [Error Code: -104, SQL State: 42601]  DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=X1
 WHEN '' THEN RETURN X2;ERMINISTIC
 CASE;<space>, DRIVER=4.13.127
16:09:47  [ELSE - 0 row(s), 0.000 secs]  [Error Code: -104, SQL State: 42601]  DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=RETURN;ELSE ;JOIN <joined_table>, DRIVER=4.13.127
16:09:47  [END - 0 row(s), 0.000 secs]  [Error Code: -104, SQL State: 42601]  DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=END-OF-STATEMENT;END CASE;JOIN <joined_table>, DRIVER=4.13.127

Thanks for your help.

A: I only do SQL UDFs on Teradata, but DB2 syntax is quite similar.
This should work
CREATE FUNCTION COALESCEEMPTY (X1 XML, X2 XML)
RETURNS XML
LANGUAGE SQL
CONTAINS SQL
NO EXTERNAL ACTION
DETERMINISTIC
RETURN
   CASE WHEN X1 = '' THEN X2 ELSE X1 END;

A: Empty string is not a well-formed XML fragment, so it should not be possible for an XML host variable to be an empty string. If you mean to check for a NULL value, as implied by the function name, it should look like
CASE WHEN X1 IS NULL THEN X2 ELSE X1 END

In standard SQL NULL and empty string are different things.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change color of the iPhone screen I need to change the color of the iPhone screen when i touch on it. The only thing i need to do is to change the color of the area where i am touching. if i am placing a star on the screen as touch then only that area color will be changed.
Any idea about this?

A: Take a look at some of the Graphics and Animation iPhone SDK Samples - there are samples there that show how to paint with different colours and other samples of how to use user input.


text:
Q: Azure Cognitive Search - When would you use different search and index analyzers? I'm trying to understand what is the purpose of configuring a different analyzer for searching and indexing in Azure Search. See: https://learn.microsoft.com/en-us/rest/api/searchservice/create-index#-field-definitions-
According to my understanding, the job of the indexing analyzer is to breakup the input document into individual tokens. Through this process, it might apply multiple transformations like lower-casing the content, removing punctuation and white-spaces, and even removing entire words.
If the tokens are already processed, what is the use of the search analyzer?
Initially, I thought it would apply a similar process on the search query itself, but wouldn't setting a different analyzer than the one used to index the document at this stage completely breaks the search results? If the indexing analyzer lower-cased everything, but the search analyzer doesn't lower-case the query, wouldn't that means you'll never get matches for queries with upper case characters? What if the search analyzer doesn't split tokens on white-spaces? Won't you ever get a match the moment the query includes a space?
Assuming that this is indeed how the two analyzers works together, then why would you ever want to set two different ones?

A: Your understanding of the difference between index and search analyzer is correct. An example scenario where that's valuable is using ngrams for indexing but not for search terms. So this would allow a document with "cat" to produce "c", "ca", "cat" but you wouldn't necessarily want to apply ngrams on the search term as that would make the query less performant and isn't necessary since the documents already produced the ngrams. Hopefully that makes sense!


text:
Q: I need to change the format of the date i am using batch and i need help formatting this one thing, on saved file the date changes everyday but the "yyyy" is just put down as "yy"
Example: if the year was "2021" the name would be "21"
I havent found anything that could get me the last 2 numbers on the year.
Please help as i need this for work.
Sincerely,
Kythe

A: You might cut out the part you do not need:
set DT=%date%

set dd=%DT:~0,2%
set mm=%DT:~3,2%
set yy=%DT:~8,2%

echo %dd%
echo %mm%
echo %yy%

echo "day: %dd%, month: %mm%, year: %yy%"

pause

set variable=%date:~start,length%  assigns to the variable all the the characters of date indexed between start (counting from 0) and (start + length-1)

EDIT:
On other machine date might be formatted differently, as @Squashman pointed out.
To properly cut out the part you need, try:
echo %date%

Now set dd, mm and yy in the correct way you need them to be set


text:
Q: Using cordova datepicker with ng-cordova, the promise "then" doesn't gets executed as it should. On android module.controller('MyCtrl', function($scope, $cordovaDatePicker) {
    $scope.showDatePicker=function(){
        var options = {date: new Date(), mode: 'date'};
        //var options = {date: new Date(), mode: 'time'}; for time
        $cordovaDatePicker.show(options).then(function(date){
            alert(date);
        });
    };
});

The alert should appear soon after the date is selected but it appears when I call showDatePicker second time, and shows the date which was selected in the first attempt.
Example on first click I selected 18-dec-2014 and selected ok on native datepicker window.
It closes without showing alert.
On Second click it first show alert with date "18-dec-2014" and then it shows datepicker.

A: Did you try with vanilla callback instead of using promises? Like this
$cordovaDatePicker.show(options, function(date){
    alert(date);
});

Update
Had a look at the source. Looks like your code should be like this
$q.when($cordovaDatePicker.show(options)).then(function(date){
    alert(date);
});

The show method is returning promise.

A: I was able to fix the issue by loading the libs in correct order.
Before
 <script src="cordova.js"></script>`

`<!-- cordova script (this will be a 404 during development) -->
 <script src="js/ng-cordova.js"></script>

 <script src="cordova.js"></script>`

After
`<!-- cordova script (this will be a 404 during development) -->
 <script src="js/ng-cordova.js"></script>

 <script src="cordova.js"></script>`

by mistake I  included <script src="cordova.js"></script> redundantly before loading ng-cordova.js, removed that extra line and everything worked fine. Since all files were there loaded so I wasn't getting any meaningful error. On a thorough line by line validation of code could help fixing it.


text:
Q: Simple Dotnetnuke or Django Q&A engine Please recommend me some simple engine based on Dotnetnuke or Django that allows users to ask questions and the others to answer them. It doesn't need to be complex, but with tags and categories.

A: Have a look at OSQA, which uses Django and is a nice SO clone.
Look at this thread on meta for other alternatives.


text:
Q: flexbox layout on iphone not taking up the right amount of space I've been trying to get this layout to work for smart phones.  What I'm looking to do is have a fixed header that doesn't move and then have a flex container underneath the header that takes up the rest of the screen space.  Inside the flex container should be 3 sections of the same size that each takes up the size the flex-container.
My current attempt isn't working.  I can't figure out how to keep the fixed header from moving and I can't figure out how to get the flex container the right size with each of the sections.

<!DOCTYPE html>

        <meta name="apple-mobile-web-app-capable" content="yes">
        <title>scroll</title>

A: If you set the position to fixed or absolute, the element's position must be definite. You either have to additionally set the navbar's width to 100%, or add both the left: 0 and right: 0 properties.  Also, don't set each of your sections to height: 80%, but only the flex container. Ensure that each flex item has the flex: 1 property.
Your code should now look like this:

<!DOCTYPE html>

        <meta name="apple-mobile-web-app-capable" content="yes">
        <title>scroll</title>


text:
Q: How to pass url parameters to JSF/xHTML? I know this has been asked multiple times but mine is a slightly diff question.
I have a JSF page which queries a database and throws results, before i move to JSF, i used to do this in JSP and it was working fine.
When i was using JSP below is the link format i used to use
http://localhost:8080/blmdatabase/index.jsp?SearchString=Name&Category=Contact&Submit=Submit

My index.jsp used to capture the values using param.SearchString & param.Category, and 'Submit' used to activate the 'submit' button for the search.
How do i do the same for xHTML/JSF ?
Here is what i tried ...
http://localhost:8080/blmdatabase/index.xhtml?search=#{some search string}

In my index.xhtml
    <td>
    <f:metadata>
        <f:viewParam name="search" value="#{databaseSearch.searchstring}" />
    </f:metadata>
  <p:inputText id="searchstring" size="20" maxlength="20"  value="#{databaseSearch.searchstring}"/> <p:commandButton id="submit" icon="ui-icon-search" title="Search Database" update="panel" actionListener="#{databaseSearch.customerList}" />
    </td>

in my databaseSearch.java
@ManagedBean(name = "databaseSearch")
@SessionScoped

public class databaseSearch implements Serializable {

    public String searchstring;
  //getter and setter for searchstring
}

Also, i would need it 'Submit' the form .... I am new to this, so please excuse me if this was already discussed before ...
Also if i specific index.html , my jsf components would not load, just a blank page. like if i go
http://localhost:8080/blmdatabase/

my primefaces components load fine, but if i do
 http://localhost:8080/blmdatabase/index.xhtml

it does not, so now i am wondering how to pass the parameters :(
Web.xml
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>

A: You could 'submit' your form adding <f:event type="preRenderView"> inside the <f:metadata> tag.
<f:metadata>
    <f:viewParam name="search" value="#{databaseSearch.searchstring}" />
    <f:event type="preRenderView" listener="#{databaseSearch.doSearch}" />
</f:metadata>

This way, you could implement how your bean will search for this specific query string
public void doSearch(ComponentSystemEvent event) {
    if(!searchString.isEmpty()) {
        // Do your search here
    }
}

A: Your Faces Servlet maps to anything that's hold in the faces virtual folder:
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>

So http://localhost:8080/blmdatabase/index.xhtml URL won't be parsed through Faces Servlet. You must use http://localhost:8080/blmdatabase/faces/index.xhtml, note the use of faces/ before your index.xhtml file, also note that your <welcome-file> also points to faces/index.xhtml.
The downside of this URL pattern is that Faces Servlet would also process non-facelets resources like JavaScript files (.js), Style files (.css), images (*.png, *.jpg) and others. A better Faces Servlet mapping would be:
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

In this way, Faces Servlet will process xhtml pages only and you won't need the faces virtual folder anymore. With this change, now you can access to http://localhost:8080/blmdatabase/index.xhtml with no problems.

A: you could use a method in the class dataBaseSearch:
if(searchString != null){
//execute a query in database
// return result to a variable(resultSet or list)
}

and use getter and setter to get the the resultSet or List
and render the result in a datatable.


text:
Q: Cannot perform equivalent text binding with TextBox In my program I have a TextBlock that is bound to a property value in a data model. I would like to change this TextBlock to a TextBox so that it is editable, but would still like to bind text to it. The problem is, when I change the TextBlock to a TextBox, my binding does not work, and the TextBox appears blank.
The property that I am binding to is of a custom class that I have in my program.
This is the property:
//Property for Display Name
public MultiItemString DisplayName {}

This is the MultiItemString class:
public class MultiItemString : INotifyPropertyChanged
{
    private readonly string[] _keys;
    private readonly MultiItemString[] _nestedItems;

    readonly bool _resourceKey;
    private readonly bool _nestedMultiItemStrings;

    public MultiItemString(IEnumerable<string> keys, bool resourceKey = true)
    {
        _keys = keys.ToArray();
        _resourceKey = resourceKey;

        LanguageChange.LanguageChagned += (sender, args) => RaisePropertyChanged("");
    }

    public MultiItemString(IEnumerable<MultiItemString> nestedItems)
    {
        _nestedItems = nestedItems.ToArray();
        foreach (var multiItemString in _nestedItems)
        {
            multiItemString.PropertyChanged += (s, e) => RaisePropertyChanged("Value");
        }
        _nestedMultiItemStrings = true;
    }

    public string Key
    {
        get
        {
            if (_keys != null && _keys.Length != 0) return _keys[0];
            return null;
        }
    }

    public string Value
    {
        get
        {
            var sb = new StringBuilder();
            if (_nestedMultiItemStrings)
            {
                foreach (var MultiItemString in _nestedItems)
                {
                    sb.Append(MultiItemString.Value);
                }
            }
            else
            {
                foreach (var key in _keys)
                {
                    sb.Append(_resourceKey ? (string)Application.Current.Resources[key] : key);
                }
            }
            return sb.ToString();
        }
    }

    public override string ToString()
    {
        return Value;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    void RaisePropertyChanged(string propertyName)
    {
        var temp = PropertyChanged;
        if (temp != null)
            temp(this, new PropertyChangedEventArgs(propertyName));
    }
}

My xaml:
<TextBox Text="{Binding Model.DisplayName}" Height="28" HorizontalAlignment="Left" Name="title_TB" VerticalAlignment="Top" Width="Auto" FontWeight="Bold" FontSize="14" Margin="5,2,0,0" />

How can I bind this property to a TextBox as it's text value, just like I do with TextBlock?

A: This should work:
<TextBox Text="{Binding Model.DisplayName.Value}" Height="28" HorizontalAlignment="Left" Name="title_TB" VerticalAlignment="Top" Width="Auto" FontWeight="Bold" FontSize="14" Margin="5,2,0,0" />

And, update Value property to have setter:
private string _thisShouldBeAValidField ;
    public string Value
        {
            get
            {
if(_thisShouldBeAValidField!=null) return _thisShouldBeAValidField;
                var sb = new StringBuilder();
                if (_nestedMultiItemStrings)
                {
                    foreach (var MultiItemString in _nestedItems)
                    {
                        sb.Append(MultiItemString.Value);
                    }
                }
                else
                {
                    foreach (var key in _keys)
                    {
                        sb.Append(_resourceKey ? (string)Application.Current.Resources[key] : key);
                    }
                }
                return sb.ToString();
            }
    set{
    _thisShouldBeAValidField = value;
    }
        }


text:
Q: Is it safe to swap SATA ports during hibernation? I hibernated my Windows 7 desktop PC, replaced the SATA cables of my 2 hard drives (without paying attention to which ports they were connected), and resumed the system. Everything appeared normal and it entered the desktop with all the applications previously open before hibernation. However, after a few seconds, the screen became frozen and the system no longer responded to anything (mouse/keyboard/network ping).
Does anyone have a definitive answer on whether changing SATA ports of the HDDs during hibernation would crash a Windows 7 system?

A: You have a giant Hooya Sir,
Each drive is addressed in BIOS by it' physical port, then windows uses those physical port addressees to locate drives and map them to a physical device numbers and then map that to a drive letter.
As soon as you re-arrange the drives you have changed the base BIOS maps to the deice, so as soon as windows asks a specific drive letter to do anything, that mapping which points to the drives previous position will fail and if the process using that space was critical, like a swap file, windows is done for.
The good news is rebooting normally should reset all the values and sort the issue out but any work in progress at the time of hibernation will likely be lost for good.
Just one question for you, why would you hibernate a PC then rearrange the drive cables?

A: If a program has files open on a drive, and that drive suddenly is slipped out from beneath that program, it's going to have problems.  The operating system itself always has files open on the drive it is installed from, thus you can certainly expect problems if the operating system's drive is suddenly removed or moved.  There's no way the open files can automatically find what device they belong to if devices are being removed and added at different locations (that'd be an awesome feature for a future OS, however)

A: Think hibernation as stopping the OS in time. Although from physical perspective, you shut down the power and restart it, from OS perspective it has just, in an instant, lost the location of the drive. Same reason really why you shouldn't install new internal hardware without shutting down the computer first.


text:
Q: How to avoid adding of button multiple times which was created dynamically I have a requirement where I need to show a button labeled Set only when both the text in two  Text input fields are the same.
I am able to show the button Set which is created dynamically When clicked on the Validate button .
The Only issue i am seeing is that , the Set button is being added multiple times when ever if clicked on the Validate button
$(function () {
    $("#setcategory").hide();
    $(document).on('click', '#validate', function (event) {
        var val1 = $("#fort1text").val();
        var val2 = $("#fort2text").val();
        if (val1 != '' && val2 != '') {
            if (val1 == val2) {
                var setthiscategory = '<input type="button" id="setthiscategory" class="saveclassbtn btn blue" id="sett1cat" value="Set This Category"/>';

                $("#validate").after(setthiscategory);

            } else {

            }
        }
    });

});

Please let me know how to resolve this ??
Thanks in advance .

A: use length in jquery ,to find that element was created or not
if($("#setthiscategory").length==0){
      $( "#validate" ).after(setthiscategory);
}

A: just add an if statement to verify that you perform the action only if #setthiscategory doesn't exist:
if (!$('#setthiscategory').length)
    $( "#validate" ).after(setthiscategory);

hope that helps.

A: try this..
<input type="text" id="fort1text" class="m-wrap span12" placeholder="">
    <input type="text" id="fort2text" class="m-wrap span12" placeholder="">
    <input type="button" id="validate" value="Validate">
    <script>

        $(function () {
            $("#setcategory").hide();
        });
        $(document).on('click', '#validate', function (event) {
            var val1 = $("#fort1text").val();
            var val2 = $("#fort2text").val();
            if(val1!=''&&val2!='')
            {
            if(val1==val2)
            {
        var setthiscategory = '<input type="button" id="setthiscategory" class="saveclassbtn btn blue" id="sett1cat" value="Set This Category"/>';
              if($("#setthiscategory").length==0)
                $( "#validate" ).after(setthiscategory);
            }
            else
            {
               $('#setthiscategory').remove();
            }
            }
        });

    </script>


text:
Q: Marklogic Cluster configuration issue - (xdmp:wrong-host ) I am creating the cluster in Marklogic AWS AMi instance.I initiated the host successfully and added the node to the Cluster. After that , I had verified the host status from the Node-1 Admin UI and its connected . However when i am accessing the url (http://node-2:8001) from the browser , i am getting the 504 error from the browser response. When i verified the logs /var/opt/marklogic/Logs/Errorlog.txt -node2 , i had seen the following error from the error logs.
ErrorLog.txt:2018-11-06 15:46:55.007 Error: AppRequestTask::run:XDMP-
WRONGHOST: Host 17757088108171649752(marklogic-node1) thinks it is
really host 6376803667935202073(marklogic-node2)

I am not really sure why i had this error and did not find any thing from the documentation other than xdmp:wrong-hsot message. Could some one provide some insight why i got the error and how to resolve it .

A: Somewhere along the line you ended up with either the DNS for 'marklogic-node1' and 'marklogic-node2' inconsistent when resolved on either host, or some portion of the configuration from node1 onto node2 (or visa versa).
Where did you get the AMI to create node2 ? If you got this by creating an image off an existing ML node you will run into this kind of problems.
Similarly if you copy any of the data between them, or change hostnames or IP addresses after the first launch of MarkLogic on a given host.
You can also end up like this if you are re-configing what was a managed-cluster without following the docs, and/or create a an AMI from such a cluster and use it elsewhere.
In general:
* All OS level configuration should be done before ML is started for the first time on any server

*

*AMI's should be 'clean' -- not made from a previous installation

*Managed Cluster hosts should only be updated, added to or removed from clusters using the documented external programs.

*The hostname that the OS uses should match the hostname you supply to ML and should match the DNS resolution -- and should resolve identically on all hosts in a cluster.

*Hosts should be attached directly to each other not through load balancers or proxies.
There are ways around these generalizations, but they require significant knowlege to get right.


text:
Q: iptables: How to allow only SSH and VPN traffic? I have a dedicated server with Ubuntu 14.10 installed.
The server should connect to an OpenVPN server and the traffic should only go through the VPN, except for SSH traffic.
My idea is to implement this with iptables, but I am not a specialist.
What exactly should be handled with iptables?
Supposing below are the basic conditions:

*

*Allow only traffic through VPN. When my server loses connection to the VPN, there should be no traffic leak.

*Allow SSH without VPN. I want to connect to my server with SSH and its normal IP from the server provider (but only SSH traffic).

*Since I am not the only user of the VPN, I want to hide my server in the VPN from other computers.
I started to create my iptables rules but it always blocks all my connections:
# flush old rules
iptables -F

# accept SSH traffic with non vpn connection
iptables -A INPUT -d X.X.X.X -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -s X.X.X.X -p tcp --sport 22 -j ACCEPT

# block everything except my rules
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

# allow loopback
iptables -A INPUT  -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# allow vpn
iptables -A INPUT  -j ACCEPT -p udp -s Y.Y.Y.Y --sport 1194
iptables -A OUTPUT -j ACCEPT -p udp -d Y.Y.Y.Y --dport 1194

X.X.X.X is the server IP from the provider.
Y.Y.Y.Y is the IP of the VPN server.
The rules always kick me out of my current SSH connection and I can't create new SSH connection, although it should accept traffic through the port 22.

A: Keep in mind on your -d option, if you wanna apply on all adapters just don't use this option, like
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

A: EDIT:

Allow only traffic through VPN. When my server loses connection to the VPN, there should be no traffic leak.

This should care for your VPN application. For instance PIA (Private Internet Access) calls this a Kill Switch, you can simply enable in the application.

Allow SSH without VPN. I want to connect to my server with SSH and its normal IP from the server provider (but only SSH traffic).

Well, this contradicts the Kill Switch above.
As a VPN user myself I solved it with not connecting to its local IP, say 192.168.0.xxx, but to its public address, and enabling a specific port for my server rather than using the 22, because I have several servers at home, so you might want to think about it too. This also means you will need to redirect that port from your router to that server and making iptables rule for this port.

Since I am not the only user of the VPN, I want to hide my server in the VPN from other computers.

As you haven't described your environment, I can only say, that I'd disable some services like samba etc.

ORIGINAL ANSWER:
According to the man page:

--sport is short for --source-port
--dport is short for --destination-port

In your case, I believe you shall use only --dport option.

A: If you are concerned about leaks, not just making the data available only through vpn available, then the safest way to do it is with separate machines. The machine running openvpn and ssh should be the only one that is directly on the internet; others must use a private address, and use a proxy or gateway through that one.
That way if you misconfigure something, such as dns, it'll just fail instead of going through the wrong network. You can achieve that with virtual machines if you don't want physical ones. But a VM also has more attack surface... a hacked VM might be able to exploit a bug to reach the host easier than another machine on the network.

A: There are several issues here.
First off, you need to allow a few more things.

*

*Traffic over the VPN.  It will be a specific named device, or class of named devices.  If the VPN is up, you should see it in the output of ip link or ifconfig.  This otherwise looks like your "allow loopback" entries.

*Related packets.  This allows ICMP messages for your connections.

You are probably better off allowing, in the first rule, the established connections.  This makes testing faster.  Combined with the second point above, that would be:
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

This also has the advantage that it will prevent your existing SSH connection being shut down.
While testing, don't set the policy rules until things seem to work.
Also, add a LOG rule to record what isn't being accepted:
iptables -A INPUT -j LOG
iptables -A OUTPUT -j LOG

You will see this output on the console, via dmesg, and via the system log.  These rules aren't needed once everything works.  (But they can show you how much you are being attacked.)
Once you can make a new SSH connection without getting anything logged, then it is time to set the policy rules.

The one other thing you may need to do is some careful routing work.  If the VPN is to the internet at large (not impossible), then the SSH and VPN data exceptions can become hairy.  Your VPN software should document or handle this for you.


text:
Q: stretch across the width of page for radio button in jqm 1.2.0 iOS device I want to make the horizontal radio button to full width of the screen and I am referring http://jquerymobile.com/demos/1.2.0/docs/forms/radiobuttons/ and my code is below:

 <fieldset data-role="controlgroup" data-type="horizontal">
 <input type="radio" name="radio-choice-1" id="spent_money_1" value="choice-1" checked="checked" /> Spent Some $
 <input type="radio" name="radio-choice-1" id="made_money_1" value="choice-2"/>
 Made Some $
 </fieldset>

and i tried to put style="width:100%" in both div, fieldset and input but doesn't help either. Appreciate any advice please. thanks !
Cheers,
Mark

A: I have been having the same problem. Adding the following CSS works for me.
This case is for 4 radio buttons, so I use 25% width for ui-radio.
.ui-controlgroup-controls
{
    width:100%;
}
.ui-radio {
    width:25%;
}

A: In the general case where you don't want to specify the widths (works in 1.3.0)
.ui-controlgroup-controls
{
    display: table;
    width: 100%;
}

.ui-controlgroup-controls .ui-radio
{
    display: table-cell;
    float: none;
}


text:
Q: The difference between gathering, get-together and meeting I've been googling to find the differences among the words: gathering, get-together, and meeting.
I found meanings of the three words from Collins:

A get-together is an informal meeting or party, usually arranged for a particular purpose.
A gathering is a group of people meeting together for a particular purpose.
A meeting is an event in which a group of people come together to discuss things or make decisions.

The dictionary definitions seem not much different but from the various articles, I gathered that three words might be ordered by the formality of the event:
meeting > gathering > get-together
And it seems also that gathering and get-together are not for the business world. In the business, it has to be meeting. I also think that get-together is a smaller scale than gathering.
But I'm not sure about my conclusions. Fix me if I'm thinking in the wrong way.
And here are some cases that I'm not sure of suitable words to call the events:

*

*If teenage students meet together to do homework home, is this gathering or meeting?

*If you go to drink with several of your friends, is this get-together?

*If you meet with your friends for lunch with homemade food, is this gathering or get-together?

*If you meet with your neighbors to discuss community problems, is this gathering or meeting?
Thanks.

A: In modern U.S. usage at least, the words do not indicate differing degrees of formality of conduct or usage. The dictionary is correct; what distinguishes the words is the implied purpose. A "gathering" may be for any purpose or no purpose. A "meeting" may be used in the same sense as "gathering" or, probably more frequently, in the more limited sense of a gathering for the purpose of discussing or deciding one or more issues. A "get-together" is used almost exclusively to describe a gathering for the primary purpose of being amicable. A get-together of bishops is likely to be a rather formal affair; a meeting of the local guild of jesters is likely to be anything but formal. It is purpose rather than conduct that is primarily in question.
EDIT Teenagers doing anything together will have some social aspects in my experience, but since the ostensible purpose is homework, "gathering" would be my choice. Did you go to the bar to decide upon whether to go into partnership? You would put down "business meeting" on an expense report. Did you go to relive old times? That is a get-together. The words have partially overlapping fields of meaning, and which word to use depends both on context and on the flavor that you want to imply.

A: Your impressions of the meanings of these phrases seem to be good.  But you expect there to be less overlap than there really is.

*

*It's a gathering, a get-together and a meeting, though I probably wouldn't use any of these terms as nouns.  I might well say "we are going to meet..." or "we are going to get together to do homework".

*It certainly can be a get-together. (but you might also say that you are meeting for for a drink)

*You could call that a gathering, or a get-together.  As you note, a gathering tends to be larger in scale.

*If you are discussing something then probably "meeting", though it is also a gathering.
Sorry that this is less clear-cut than you hoped. These words do overlap meanings.


text:
Q: Install VS Code Packages to work in Multiple Conda Environments I have several Python projects using different environments. These environments are managed using Conda and this works well, allowing the same environment to be used in production and dev/test for each project.
Conda yml files are used to define each environment.
There are a number of packages that I would like to use during development, such as autopep8. These don't need to be in the production environment so are not included in the yml file.
How can I install autopep8 and others so that they will work across any Python environment that I load in VS Code? So far I have had to manually install these packages as I switch environments.

A: Default Packages
One way of managing this without violating environment isolation1 would be to use Conda's default packages functionality. The idea would be to define default packages (such as autopep8) in a .condarc on only the development systems. The conda env create will respect these and add them to every env you create, so you can still keep a single YAML that describes only the essentials for the production version.
Note that there are multiple options for where to store this .condarc, and Conda can load settings in a nested fashion. If all environments for your user are categorized as "development", then a sensible place to define the default packages would be ~/.condarc. There is additionally a --no-default-packages flag, which can be used to disable such default package installation when you don't need it.

[1] While there are ways to include packages from outside a Conda environment (e.g., through PYTHONPATH), this should be regarded as substandard and only be used as a last resort. Conda is designed with an assumption of full isolation of environments - violating that can lead to undefined behavior.


text:
Q: Display back button in fragment with Toolbar I'm using fragment based navigation, each fragment has it's own toolbar.
When navigating to a fragment I want the back button to display in the toolbar.
I have overridden the OnCreateView method as follows:
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
   var ignored = base.OnCreateView(inflater, container, savedInstanceState);
   var view = this.BindingInflate(_fragmentId, null);
   _toolbar = view.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
   if (_toolbar != null)
   {
      ParentActivity.SetSupportActionBar(_toolbar);
      ParentActivity.SupportActionBar.Title = _title;
      ParentActivity.SupportActionBar.SetDisplayHomeAsUpEnabled(true);
      _drawerToggle = new MvxActionBarDrawerToggle(
         Activity,
         (ParentActivity as MainView).DrawerLayout,
         _toolbar,
         Resource.String.drawer_open,
         Resource.String.drawer_close);

      (ParentActivity as MainView).DrawerLayout.AddDrawerListener(_drawerToggle);
   }

   return view;
}

SetDisplayHomeAsUpEnabled(true) should be changing the button to the back button, according to numerous other stack overflow answers, However this is not working as can be seen in the following screenshot:

I have checked that the SetDisplayHomeAsUpEnabled(true) line is hit when I navigate to the fragment.
For reference I am using Xamarin with MvvmCross.
How do I make change the toolbar to the up/back button when using fragment based navigation?

A: Solved it:
The DrawerToggle was somehow overriding the toolbar settings. Adding the following line fixes the problem.
_drawerToggle.DrawerIndicatorEnabled = false;

A: I'm not very familiar with Xamarin. Try setting the indicator with ParentActivity.SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu_white_24dp);. This might help.


text:
Q: Visual Studio 2013 Ultimate breaking dependencies every code edit I am not sure why this is happening but no matter the app (even brand new ones) I get a multitude of errors stating that referenced assemblies/namespaces could not be found. The project still runs if I build it and if I clean it all the errors go away until I edit the code again. Here is a screen shot.

My packages seem to look fine.
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Antlr" version="3.4.1.9004" targetFramework="net45" />
<package id="bootstrap" version="3.0.0" targetFramework="net45" />
<package id="EntityFramework" version="6.1.1" targetFramework="net45" />
<package id="jQuery" version="1.10.2" targetFramework="net45" />
<package id="jQuery.Validation" version="1.11.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.Core" version="2.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.Owin" version="2.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="5.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.Razor" version="3.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebPages" version="3.1.2" targetFramework="net45" />
<package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.1.2" targetFramework="net45" />
<package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Cookies" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Facebook" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Google" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.MicrosoftAccount" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.OAuth" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Twitter" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
<package id="Modernizr" version="2.6.2" targetFramework="net45" />
<package id="Newtonsoft.Json" version="5.0.6" targetFramework="net45" />
<package id="Owin" version="1.0" targetFramework="net45" />
<package id="Respond" version="1.2.0" targetFramework="net45" />
<package id="WebGrease" version="1.5.2" targetFramework="net45" />
</packages>

And here is my web.config
 <runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
  </dependentAssembly>
</assemblyBinding>

Some things I have tried

*

*Checking each project to make sure it references .net 4.5

*Deleting the .suo file and restarting visual studio

*Cleaning the whole solution and rebuilding

*Restarting visual studio without doing any of the above

Each of these works temporarily but as soon as I change tabs in VS or edit a line of code problems come back. I am now even having issues with intellisense not popping up either.

A: I finally found an answer. It appears to be a bug in Visual Studio 2013 that gets triggered if you have "Get everything when a solution or project is open" under Tools>Options>Source Control>Environment. Deselect that and everything will be okay.
Reference
The type or namespace name 'Models' does not exist in the namespace 'PartyInvites'


text:
Q: NSThread presentviewcontroller call? How i can start an other viewcontroller in a thread?
My code don't work:
- (IBAction)btnGotoNextVC:(id)sender
{
    [self.isLoading startAnimating];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    [NSThread detachNewThreadSelector:@selector(gotoSecondController:)
                             toTarget:self
                           withObject:[NSArray arrayWithObjects:@"hello there", nil]];
}

and my thread:
- (void) gotoSecondController: (NSArray*) parameters
{
    NSString* data1 = parameters[0];

    NSLog(@"%@", parameters[0]);

    ViewController2 *VC2 = [self.storyboard instantiateViewControllerWithIdentifier:@"myView2"];
    VC2.global_myLabel = [NSString stringWithFormat:@"Hallo %@", data1];
    [self presentViewController:VC2 animated:YES completion:nil];
}

It's crashed by this line:
[self presentViewController:VC2 animated:YES completion:nil];

Error is:
-[NSStringDrawingContext animationDidStart:]: unrecognized selector sent to instance 0x8f983c0

What can i do? Thanks for answers!

A: No, anything that updates the UI has to be run on the main thread.
To fix your code, you will have to run in on the main thread. The easiest way would be to call the method directly, becasue IBActions are always invoked on the main thread:
[self gotoSecondController:@[@"hello there"]];

However, if you are not on the main thread already, you can make some code run on the main thread in a couple different ways. With blocks:
__block MyViewController *blockSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
    [blockSelf gotoSecondController:@[@"hello there"]];
});

Or by using the method
[self performSelectorOnMainThread:@selector(gotoSecondController:) withObject:@[@"hello there"] waitUntilDone:NO];


text:
Q: Prevent popup to stay on top of newly launched modal windows I have a window that uses popup. The popup is set to stay open as required by the specification. This window also launches a new modal window. The problem I am having is that the new modal window appears on top on the original window but not the popup. The popup appear on top of everything making it all look very weird.

A: I've had pretty good luck with the NonTopmostPopup that Adrian Faciu mentioned.  It is topmost only to its parent window, so, assuming your modal window is indeed a new Window (not just another control that looks like one), it should work well.  If I recall, the only slight issue with it was a very occasional flicker or refresh period depending on the Windows being dragged in front of it, etc (but it was not enough of an issue for me to not use it).

A: The Popup is a control that it is very useful in XBAP where you cannot (or if you do it someway you get a security warning) open a second window because of permissions and the Popup is a convienient way to display message box. If you are working in a normal WPF I recommend you to use a normal window (with WindowStyle.None if you want) instead of a Popup.
Said that, as far as I know the Popup is always shown on top and I didn't find anyway to avoid this.
Ref :: http://social.msdn.microsoft.com/Forums/en/wpf/thread/7467957a-08e9-4e9b-a03f-51c79a94bccb

A: public class PopupParentWindowFocusBehavior : Behavior<Popup>
{
    private bool _hidden;
    private UIElement _lastPlacementTarget;
    private System.Windows.Window _lastWindow;
    private PropertyChangeNotifier _placementTargetNotifier;

    protected override void OnAttached()
    {
        base.OnAttached();
        InitializeForPlacementTarget();

        _placementTargetNotifier = new PropertyChangeNotifier(AssociatedObject, Popup.PlacementTargetProperty).AddValueChanged(OnPlacementTargetChanged);
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        DetachWindowEvents();

        if (_lastPlacementTarget != null)
        {
            ((Control)_lastPlacementTarget).Loaded -= OnPlacementTargetLoaded;
        }
        _placementTargetNotifier.ValueChanged -= OnPlacementTargetChanged;
    }

    private void OnPlacementTargetChanged(object sender, EventArgs e)
    {
        InitializeForPlacementTarget();
    }

    private void InitializeForPlacementTarget()
    {
        if (_lastPlacementTarget != null)
        {
            ((Control)_lastPlacementTarget).Loaded -= OnPlacementTargetLoaded;
        }
        if (AssociatedObject.PlacementTarget != null)
        {
            ((Control)AssociatedObject.PlacementTarget).Loaded += OnPlacementTargetLoaded;
            AttachWindowEvents();
        }
        _lastPlacementTarget = AssociatedObject.PlacementTarget;
    }

    private void OnPlacementTargetLoaded(object sender, RoutedEventArgs e)
    {
        AttachWindowEvents();
    }

    private void OnWindowClosed(object sender, EventArgs e)
    {
        DetachWindowEvents();
    }

    private void AttachWindowEvents()
    {
        if (_lastWindow != null)
        {
            DetachWindowEvents();
        }

        System.Windows.Window window = System.Windows.Window.GetWindow(AssociatedObject.PlacementTarget);
        if (window != null)
        {
            window.Deactivated += OnWindowDeativated;
            window.Activated += OnWindowActivated;
            window.Closed += OnWindowClosed;
        }

        _lastWindow = window;
    }

    private void DetachWindowEvents()
    {
        if (_lastWindow != null)
        {
            _lastWindow.Deactivated -= OnWindowDeativated;
            _lastWindow.Activated -= OnWindowActivated;
            _lastWindow.Closed -= OnWindowClosed;
        }
    }

    private void OnWindowDeativated(object sender, EventArgs e)
    {
        System.Windows.Window window = System.Windows.Window.GetWindow(AssociatedObject.PlacementTarget);
        if (window != null && AssociatedObject.IsOpen)
        {
            _hidden = true;
            AssociatedObject.IsOpen = false;
        }
    }

    private void OnWindowActivated(object sender, EventArgs e)
    {
        if (_hidden)
        {
            _hidden = false;
            AssociatedObject.IsOpen = true;
        }
    }
}


text:
Q: How to allow PHP REST request via https with expired certificate Is there a way to allow PHP doing connections to https urls if the certificate is expired? Something like a security exception in a browser.
The following code will not work if the certificate is expired but it works well, if the certificate is valid.
<?php

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://myURL/...,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "authorization: Basic abcdefghijkl",
        "cache-control: no-cache",
    ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

A: <?php

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://myURL/...,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "authorization: Basic abcdefghijkl",
        "cache-control: no-cache",
    ),
    CURLOPT_SSL_VERIFYPEER => false
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);


text:
Q: Excel VBA For Loop ends prematurely Im currently trying to run some code that will open up a file, copy the contents, close and then open the next file.
Here is my code so far:
    Sub AddData()

    Dim i As Integer

    Set QD = Workbooks("Document " & Format(Date, "DD-MM-YY") & ".xlsx")

    For i = 6 To 0
        If i = 2 Or 3 Then
            GoTo Last
        Else
            Workbooks.Open Filename:="\\*************\Jeopardy Report " & Format(Date - i, "DD-MM-YY") & "AM .xlsm", local:=True

            Set JP = Workbooks("Jeopardy Report " & Format(Date - i, "DD-MM-YY") & "AM .xlsm")

            JP.Sheets("Document").Range("B2:B6").Copy
            QD.Sheets("Helpdesk").Cells(7, Columns.Count).End(xlToLeft).Offset(0, 1).PasteSpecial xlPasteValues

            JP.Close
        End If

    Last:
    Next i
End Sub

The problem, is that the code gets to For i =6 to 0 and then skips straight to end sub.
If i remove the loop and just have i = 6, then the rest of the code works fine.
I have also tried to 1, rather than to 0, and still the same.
Any help would be greatly appreciated.

A: You need to specify a negative step since the default is 1:
For i = 6 To 0 Step -1


text:
Q: How to add a ref to functional components that are created dynamically? I have an array of Items (divs with an input field) as well as a handleSaveItem function. Each Item has an itemId which should become the value that the user types into the input field (after they click the button). My question is how to get that information, which is in Item.js, up to its parent in App.js.
I can't use useRef in handleSaveItem because that wouldn't be calling the hook at the top-level. But if I used useRef at the top-level of the Item component I don't know how I would pass that ref up to App.
Codesandbox appears to be down right now but here's some demo code anyways (simplified): https://codesandbox.io/s/useref-add-new-item-zbqlk


text:
Q: Approximate a distribution as mixture of $K$ other (known, fixed) distributions I'd like to draw samples from some "target" probability density function $f(x)$. However, I don't have a way to do that -- instead I just have access to $N$ samples, each drawn from one of $K$ "sampling" distributions $g_k(x)$ (I know which draw corresponds to which distribution).
One solution is to keep all the samples, but to weight them all. This leads to the question: how to weight the samples in order to approximate my target distribution? I'd like to preserve that all samples from each sampling distribution have the same weight. That means that I am effectively approximating my target distribution as the mixture of the $K$ sampling distributions:
$$f(x) \approx \hat{f}(x) = \sum_{i=k}^K w_k g_k(x)$$
My question is, how can I compute the mixture weights $w_k$ corresponding to each of the sampling distributions? I'd like to avoid making distributional (e.g., Gaussian) assumptions if possible.


text:
Q: How to Define the command \ choice and the Ex environment to compile with the desired results I have a LaTeX file with the following content
\documentclass[12pt,a4paper]{article}
\usepackage{environ}
\def\choice ....??? %Help me define the \ choice command and ex environment
\NewEnviron{ex}{...???} %Help me define the \ choice command and ex environment
\begin{document}

\choice{2}
\begin{ex}
an example
\end{ex}
\begin{ex}
A question developed from the example above
\end{ex}
\choice{3}
\begin{ex}
another example
\end{ex}
\begin{ex}
A question develops from this second example
\end{ex}
\begin{ex}
A question develops from this second example
\end{ex}
\choice{5}
\begin{ex}
another example
\end{ex}
\begin{ex}
A question develops from this third example
\end{ex}
\begin{ex}
A question develops from this third example
\end{ex}
\begin{ex}
A question develops from this third example
\end{ex}
\begin{ex}
A question develops from this third example
\end{ex}

\end{document}

Define the command \ choice and ex environment to be able to compile the resulting .PDF file as follows
exam 1: an example
Question 1.1: A question developed from the example above
exam 2: another example
Question 2.1: A question develops from this second example
Question 2.1: A question develops from this second example
exam 3: another example
Question 3.1: A question develops from this third example
Question 3.2: A question develops from this third example
Question 3.3: A question develops from this third example
Question 3.4: A question develops from this third example

A: If I got it right, then \choice says how many of the following ex-environments are to be composed to an exam(ple).
The first of these following ex-environments is to be used for the exam(ple)-heading.
The second and more of these following ex-environments are to be used as questions that are numbered within the number of the exam(ple)-heading.
\documentclass[12pt,a4paper]{article}

\newtheorem{exthm}{exam}
\newtheorem{choicethm}{Question}[exthm]
\newcommand\WhichThm{}
\newcommand\choicerange{0 }%

\makeatletter
\newcommand\DoNotIgnoreChoice[1]{\@bsphack\xdef\choicerange{\number\numexpr#1-1\relax\space}\@esphack}
\newcommand\DoIgnoreChoice[1]{\@bsphack\@esphack}
\newcommand\choice{}%
\global\let\choice=\DoNotIgnoreChoice
\global\let\WhichThm=\@firstoftwo
\newcommand\nestingerror{}%
\newcommand\nestingerrormessage{%
    \GenericError{\space \space \space \@spaces \@spaces \@spaces }%
                 {Error:\space nested \@currenvir-environments}%
                 {Don't nest \@currenvir-environments.}%
                 {Nesting \@currenvir-environments is not a good idea.}%
}%
\newenvironment{ex}{%
  \nestingerror
  \let\nestingerror=\nestingerrormessage
  \WhichThm
  {%
    \global\let\choice=\DoIgnoreChoice
    \begin{exthm}%
  }%
  {\begin{choicethm}}%
}{%
  \WhichThm
  {%
     \end{exthm}%
     \global\let\WhichThm=\@secondoftwo
  }%
  {\end{choicethm}}%
  \ifnum\value{choicethm}<\choicerange
  \else
     \global\let\WhichThm=\@firstoftwo
     \global\let\choice=\DoNotIgnoreChoice
     \choice{1}%
  \fi
}%
\makeatother

\begin{document}

\choice{2}
\begin{ex}
an example
\end{ex}
\begin{ex}
A question developed from the example above
\end{ex}
\choice{3}
\begin{ex}
another example
\end{ex}
\begin{ex}
A question develops from this second example
\end{ex}
\begin{ex}
A question develops from this second example
\end{ex}
\choice{5}
\begin{ex}
another example
\end{ex}
\begin{ex}
A question develops from this third example
\end{ex}
\begin{ex}
A question develops from this third example
\end{ex}
\begin{ex}
A question develops from this third example
\end{ex}
\begin{ex}
A question develops from this third example
\end{ex}

\end{document}

\choice-commands between things that are treated as questions belonging to a previously initiated  example are ignored.
E.g., with
\choice{2}
\begin{ex}
an example
\end{ex}
\choice{6}
\begin{ex}
A question developed from the example above
\end{ex}

the command \choice{6} will be ignored as at the time of encountering that command not all ex-environments belonging to the example initiated by \choice{2} were processed yet.


text:
Q: Apache Beam Python SDK for Windowing with SQL The problem is, I want to make a windowing inside SqlTransform as
SELECT f_timestamp, line, COUNT(*)
FROM PCOLLECTION
GROUP BY
   line,
   HOP(f_timestamp, INTERVAL '30' MINUTE, INTERVAL '1' HOUR)

My Row transformation mapping is
| "Create beam Row" >> beam.Map(lambda x: beam.Row(f_timestamp= float(x["timestamp_date"]), line = unicode(x["line"])))

And I have an error on the Java side as
Caused by: org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.validate.SqlValidatorException:
Cannot apply 'HOP' to arguments of type 'HOP(<DOUBLE>, <INTERVAL MINUTE>, <INTERVAL HOUR>)'.
Supported form(s): 'HOP(<DATETIME>, <DATETIME_INTERVAL>, <DATETIME_INTERVAL>)'

The things I tried:

*

*Make the f_timestamp UNIX timestamp, as a float.

*Make the f_timestamp string timestamp as a unicode.

As I read, Java side uses java.util.Date on the timestamp, how can I work around this issue?

A: You should be able to use apache_beam.utils.timestamp.Timestamp for this.


text:
Q: Update Kendo Grid based On Search Form Post I've been doing alot of searching but haven't found a clear answer for this. I have a set up textboxes that and a submit button and a Kendo UI grid. I want to post the data to the grid's datasource so that it will return the results based on the criteria. I am not using the MVC wrappers.
EDIT:
I've gotten closer but I can't seem to get the datasource to send the post data when I click submit. I've debugged and in my $("#fmSearch").submit it is hitting the jquery plugin and I've confirmed that it is converting the form data to JSON properly, but it seems as though it it not sending the updated information to the server so that the Action can read it.
Javascript
var dsGalleryItem = new kendo.data.DataSource({
        transport: {
            read: {
                url: '@Url.Content("~/Intranet/GalleryItem/SearchGalleryItems")',
                type: "POST",
                data: $("#fmSearch").serializeFormToJSON(),
                cache: false
            }
        },
        schema: {
            model: {
                id: "galleryItemID",
                fields: {
                    galleryItemID: {
                        nullable: true
                    },
                    imageName: {},
                    collectionName: {},
                    categoryName: {},
                    lastUpdatedOn: { type: "date" }
                }
            }
        }
    });

    var gvResults = $("#gvResults").kendoGrid({
        autoBind:false,
            columns: [{
                field: "imageName",
                title: "Item Name",
                template: " #=imageName#"
            }, {
                field: "collectionName",
                title: "Collection"
            }, {
                field: "categoryName",
                title: "Category"
            }, {
                field: "lastUpdatedOn",
                title: "Last Updated",
                format: "{0:M/d/yyyy}"
            }
            ],
            selectable: "row",
            change: onRowSelect,
            dataSource: dsGalleryItem
        });

    $("#fmSearch").submit(
        function (event) {
            event.preventDefault();
            dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
    });

MVC Action
[HttpPost]
    public JsonResult SearchGalleryItems(string keyword, int? category, int? collection, DateTime? startDate, DateTime? endDate)
    {

        var galleryItemList = (from g in db.GalleryItems
                               //where g.imageName.Contains(keyword)
                               select new GalleryItemViewModel
                               {
                                   galleryItemID = g.galleryItemID,
                                   imageName = g.imageName,
                                   collectionName = g.collection.collectionName,
                                   categoryName = g.category.categoryName,
                                   lastUpdatedOn = g.lastUpdatedOn
                               });

        var galleryItemCount = Json(galleryItemList.ToList());

        return Json(galleryItemList.ToList()); ;
    }

The action is not setup to retrieve different data right now I just need to know how to connect the form to the grid.

A: Found the problem. I had this:
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });

It needed to be this:
dsGalleryItem.read($("#fmSearch").serializeFormToJSON());


text:
Q: Add labels to Gmail message while using /users.messages/send While sending an email using the /users.messages/send API, is it possible to assign the message with a label in the same API call?
I'm aware you can use modify to apply a label to the message but I cannot include the gmail.modify scope for this application so using that endpoint isn't an option for me. The documentation says that the send endpoint takes an instance of Message, which allows for a labelIds key.
I've tried making the API request with the JSON body below. It successfully sends the email but it does not assign the label. Since the email is sent, I'm confident the raw message is not the issue. I suspect this endpoint is just ignoring the labelIds part of the body instead.
Does anyone know if it's possible to set the label while using the send endpoint?
{
  "raw": "<RFC 2822 formatted and base64url encoded string>",
  "labelIds": [
    "Label_1"
  ]
}

I obtained the ID, Label_1, from the labels endpoint directly so the ID is correct.
These are the scopes that my client + user are approved to use. That being said, I also included extra scopes to test but the same issue occurs, the labels aren't set even if you have gmail.modify and gmail.compose scopes approved.
userinfo.email
userinfo.profile
https://www.googleapis.com/auth/gmail.labels
https://www.googleapis.com/auth/gmail.send
https://www.googleapis.com/auth/contacts.readonly

Edit: In case this is a bug, I filed a ticket with Google as well.

A: This is intended behaviour.
This was reported before in Issue Tracker, and the response was:

This behaviour is working as intended, labels can only added for inserted/imported messages. For sent messages, you can use users.messages.modify to update the labels after the message is sent.

Nevertheless, since setting labels when sending a message is possible via UI, I'd say this could be a valid feature request. I'd suggest you to file one.
Reference:

*

*Gmail API cannot add label IDs to messages being composed


text:
Q: Powershell string separation I have a string that has a value for example 22_ABCD
Now I only need the ABCD in my parameter. What is the best method to do this in powershell ?
Do I need to use a Split() and then take $stringvalue = Split[1] ? Or is there a function in powershell that does this?

A: Split is one way to do what you want and can be used like this... where the value between the brackets is the character that you want to use for the split.
$string = "22_ABCD"
$string.Split("_")

Running the above code outputs an array containing two items:
22
ABCD

You can then reference the second item in the array with [1] ([0] being the first item) like this:
$string.Split("_")[1]

Which outputs just the second item:
ABCD

A: Regex is a possibility if you are looking for alphanumeric characters rather than just the next set of characters after an underscore.
$x = '22_ABCD_FTG_3'
[regex]::match($x,'([A-Z)]+)').Groups[1].Value

A: #method 0, with split operator
$Elements="22_ABCD" -split "_"
$Elements[0]
$Elements[1]

#method 1, with split member
$Elements="22_ABCD".Split('_')
$Elements[0]
$Elements[1]

#method 2, with split member and direct affectation
$Element1, $Element2="22_ABCD".Split('_')
$Element1
$Element2

#method 3, with ConvertFrom-String
$Elements="22_ABCD" | ConvertFrom-String -Delimiter "_" -PropertyNames "Element1", "Element2"
$Elements.Element1
$Elements.Element2

#method 4, with ConvertFrom-Csv
$Elements="22_ABCD" | ConvertFrom-Csv -Delimiter "_" -Header "Element1", "Element2"
$Elements.Element1
$Elements.Element2

#method 5, with regex
$Elements=[regex]::split("22_ABCD", '_')
$Elements[0]
$Elements[1]


text:
Q: Percent Difference From T-Test I would like to obtain a percent difference between a physiologic measure from two groups (i.e., males and females).
Say I obtain a significant difference from an unpaired t-test in blood pressure between men and women. How can I find the percent difference from here? If women have a lower bp, I would like to say something to the effect of "women had 20% lower BP compaired to men P<.05"

A: Implicitly when you do the t-test, you assume that the observations of the two groups are generated from two distributions. When you say a random variable X > 0 with p < 0.05, you're saying that the mean of X is > 0 with probability 0.05.
Similarly, what you're actually trying to say is that the mean of the women's BP is 20% lower than the mean of men's BP. Say the sample mean of men's BP is 100, then this is equivalent to testing if BP from the women's group is equal to 80.


text:
Q: ExoPlayer - How to get source code for the default layout? I'm reading this tutorial on configuring the default exoplayer view's layout:
https://exoplayer.dev/ui-components.html
However it doesn't display the source code for the default player layout exo_player_control_view.xml
I've tried searching the entire project as well CTRL + SHIFT + F but that doesn't return anything

The bottom section is the layout im trying to get.

A: The layout you're looking for is here : https://github.com/google/ExoPlayer/tree/release-v2/library/ui/src/main/res/layout
As pointed out by mcc:
Note, the above is if you are using the Exoplayer release, if you are using the Jetpack/Media3 version of exoplayer then the exo_player_control_view.xml corresponding to your library is https://github.com/androidx/media/blob/release/libraries/ui/src/main/res/layout/exo_player_control_view.xml


text:
Q: taskserver: client connection handshake failed Issue
client$ task sync
Syncing with <hostname>.localdomain:53589

Handshake failed. The TLS connection was non-properly terminated.
Sync failed. Could not connect to the Taskserver

TL;DR I'm pretty sure this isn't an issue with certificates, but more likely something to do with the client/server interaction across the WSL implementation. I can connect via telnet and netcat, but the taskd debugger receives nothing when I try to sync from the client. I can however sync from a client on the same machine as the server. If anybody can share advice on how to progress or some debugging tips, I'd be very grateful!
Set-up
Server
OS: Ubuntu 20.04 LTS (running in WSL, Windows 10)
Verbatim result of $hostname -f referred to as <hostname>.localdomain
Private IP: 192.168.1.20
server$ taskd diagnostics

taskd 1.1.0
    Platform: Linux
    Hostname: <hostname>

Compiler
     Version: 9.3.0
        Caps: +stdc +stdc_hosted +200809 +200809 +LP64 +c8 +i32 +l64 +vp64 +time_t64
  Compliance: C++11

Build Features
       Built: Jun 16 2020 14:36:11
       CMake: 3.16.3
     libuuid: libuuid + uuid_unparse_lower
   libgnutls: 3.6.13
  Build type: release

Configuration
   TASKDDATA: /var/taskd
        root: /var/taskd (readable)
      config: /var/taskd/config (readable)
          CA: /var/taskd/ca.cert.pem (readable)
 Certificate: /var/taskd/server.cert.pem (readable)
         Key: /var/taskd/server.key.pem (readable)
         CRL: /var/taskd/server.crl.pem (readable)
         Log: /var/log/taskd.log (found)
    PID File: /home/rob/taskd.pid (found)
      Server: <hostname>.localdomain:53589
 Max Request: 1048576 bytes
     Ciphers:
       Trust: allow all

Client
This is a physically different machine than the server, on the same LAN
OS: Ubuntu 20.04 LTS (running in WSL, Windows 10)
client$ task diagnostics

task 2.5.1
   Platform: Linux

Compiler
    Version: 9.2.1 20200306
       Caps: +stdc +stdc_hosted +LP64 +c8 +i32 +l64 +vp64 +time_t64
 Compliance: C++11

Build Features
      CMake: 3.16.3
    libuuid: libuuid + uuid_unparse_lower
  libgnutls: 3.6.11
 Build type: None

Configuration
       File: /home/rob/.taskrc (found), 1622 bytes, mode 100666
       Data: /home/rob/.task (found), dir, mode 40755
    Locking: Enabled
         GC: Enabled
     Server: B160227-RBC.localdomain:53589
      Trust: allow all
Certificate: /home/rob/.task/rob_home.cert.pem, readable, 4015 bytes
        Key: /home/rob/.task/rob_home.key.pem, readable, 24742 bytes
    Ciphers: NORMAL
      Creds: Public/Rob Home/************************************

Hooks
     System: Enabled
   Location: /home/rob/.task/hooks
             (-none-)

Tests
      $TERM: xterm-256color (346x102)
       Dups: Scanned 0 tasks for duplicate UUIDs:
             No duplicates found
 Broken ref: Scanned 0 tasks for broken references:
             No broken references found

Troubleshooting

*

*I have read through the following

*

*Setup

*Troubleshooting guide

*GitHub

*And I have been trying to google the issues I'm encountering but have not found anything yet which has solved my specific problem.

*As a consequence of my own debugging, the system is currently in the following state:

*

*Firewalls disabled (server, client and router)

*taskd.trust = allow all (client and server)

*From the client, I can connect to server via telnet:
client$ telnet <hostname>.localdomain 53589
Trying 192.168.1.20...
Connected to <hostname>.localdomain.
Escape character is '^]'.

*

*I am also able to set up a simple "chat server" using netcat, on the same port.

server$ nc -vv -l 192.168.1.20 53589
Listening on 192.168.1.20 53589

and then running
client$ nc -vv 192.168.1.20 53589
Connection to 192.168.1.20 53589 port [tcp/*] succeeded!

I receive the following message on the server...
Connection received on 192.168.1.19 53885

I find it strange that the connection is received over port 53885 - shouldn't it be coming from 53589 on the client machine?

*

*I have tried running the task server in debug mode using taskd server --data $TASKDDATA. From this I am able to successfully connect from a second client on the server machine, and see the results in the log. However, nothing shows when I run task sync from the client machine.

*I have checked the pages specific to "Handshake Failed", and here are the results:
client$ openssl s_client -CAfile .task/ca.cert.pem -host 192.168.1.20 -port 53589
CONNECTED(00000003)

When I generated the certificates on the server,  in ~/taskd-1.1.0/pki/vars CN=.localdomain.
server$ certtool -i < server.cert.pem | grep Subject:
        Subject: O=Göteborg Bit Factory,CN=<hostname>.localdomain

*

*I get no response at all from running lsof -i TCP:53589 -s TCP:LISTEN or netstat -tl | grep 53589, but I think that is more to do with the complication of running the server on WSL.

Conclusion so far
From the debug log of the server, I guess that the taskwarrior client cannot "see" the taskserver at all. But what confuses me is that I have verified that the client and server machines can communicate over the right port (#53589).
I've been at this for a few days now and I'm fairly sure I must be missing something obvious. Any guidance would be really, really appreciated!


text:
Q: Webm (VP8 / Opus) file read and write back I am trying to develop a webrtc simulator in C/C++. For media handling, I plan to use libav. I am thinking of below steps to realize media exchange between two webrtc simulator. Say I have two webrtc simulators A and B.

*

*Read media at A from a input webm file using av_read_frame api.

*I assume I will get the encoded media (audio / video) data, am I correct here?

*Send the encoded media data to simulator B over a UDP socket.

*Simulator B receives the media data in UDP socket as RTP packets.

*Simulator B extracts audio/video data from just received RTP packet.

*I assume the extracted media data at simulator B are the encoded data only (am I correct here). I do not want to decode it. I want to write it to a file. Later I will play the file to check if I have done everything right.

To simplify this problem lets take out UDP socket part. Then my question reduces to read data from a webm input file, get the encoded media, prepare the packet and write to a output file using av_interleaved_write_frame or any other appropriate api. All these things I want to do using libav.
Is there any example code I can refer.
Or can somebody please guide me to develop it.
I am trying with a test program. As a first step, my aim is to read from a file and write to an output file. I have below code, but it is not working properly.
//#define _AUDIO_WRITE_ENABLED_

#include "libavutil/imgutils.h"
#include "libavutil/samplefmt.h"
#include "libavformat/avformat.h"

static AVPacket pkt;
static AVFormatContext *fmt_ctx = NULL;
static AVFormatContext *av_format_context = NULL;
static AVOutputFormat *av_output_format = NULL;

static AVCodec *video_codec = NULL;
static AVStream *video_stream = NULL;

static AVCodec *audio_codec = NULL;
static AVStream *audio_stream = NULL;

static const char *src_filename = NULL;
static const char *dst_filename = NULL;

int main (int argc, char **argv)
{
    int ret = 0;
    int index = 0;

    if (argc != 3)
    {
        printf("Usage: ./webm input_video_file output_video_file \n");
        exit(0);
    }

    src_filename = argv[1];
    dst_filename = argv[2];

    printf("Source file = %s , Destination file = %s\n", src_filename, dst_filename);

    av_register_all();

    /* open input file, and allocate format context */
    if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0)
    {
        fprintf(stderr, "Could not open source file %s\n", src_filename);
        exit(1);
    }

    /* retrieve stream information */
    if (avformat_find_stream_info(fmt_ctx, NULL) < 0)
    {
        fprintf(stderr, "Could not find stream information\n");
        exit(2);
    }

    av_output_format = av_guess_format(NULL, dst_filename, NULL);
    if(!av_output_format)
    {
        fprintf(stderr, "Could not guess output file format\n");
        exit(3);
    }

    av_output_format->audio_codec = AV_CODEC_ID_VORBIS;
    av_output_format->video_codec = AV_CODEC_ID_VP8;

    av_format_context = avformat_alloc_context();
    if(!av_format_context)
    {
        fprintf(stderr, "Could not allocation av format context\n");
        exit(4);
    }
    av_format_context->oformat = av_output_format;
    strcpy(av_format_context->filename, dst_filename);

    video_codec = avcodec_find_encoder(av_output_format->video_codec);
    if (!video_codec)
    {
        fprintf(stderr, "Codec not found\n");
        exit(5);
    }

    video_stream = avformat_new_stream(av_format_context, video_codec);
    if (!video_stream)
    {
        fprintf(stderr, "Could not alloc stream\n");
        exit(6);
    }

    avcodec_get_context_defaults3(video_stream->codec, video_codec);
    video_stream->codec->codec_id = AV_CODEC_ID_VP8;
    video_stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    video_stream->time_base = (AVRational) {1, 30};

    video_stream->codec->width = 640;
    video_stream->codec->height = 480;

    video_stream->codec->pix_fmt = PIX_FMT_YUV420P;
    video_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
    video_stream->codec->bit_rate = 400000;
    video_stream->codec->gop_size = 10;
    video_stream->codec->max_b_frames=1;

#ifdef _AUDIO_WRITE_ENABLED_
    audio_codec = avcodec_find_encoder(av_output_format->audio_codec);
    if (!audio_codec)
    {
        fprintf(stderr, "Codec not found audio codec\n");
        exit(5);
    }

    audio_stream = avformat_new_stream(av_format_context, audio_codec);
    if (!audio_stream)
    {
        fprintf(stderr, "Could not alloc stream for audio\n");
        exit(6);
    }

    avcodec_get_context_defaults3(audio_stream->codec, audio_codec);
    audio_stream->codec->codec_id = AV_CODEC_ID_VORBIS;
    audio_stream->codec->codec_type = AVMEDIA_TYPE_AUDIO;
    audio_stream->time_base = (AVRational) {1, 30};
    audio_stream->codec->sample_rate = 8000;
    audio_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
#endif

    if(!(av_output_format->flags & AVFMT_NOFILE))
    {
        if (avio_open(&av_format_context->pb, dst_filename, AVIO_FLAG_WRITE) < 0)
        {
            fprintf(stderr, "Could not open '%s'\n", dst_filename);
        }
    }

    /* Before avformat_write_header set the stream */
    avformat_write_header(av_format_context, NULL);

    /* initialize packet, set data to NULL, let the demuxer fill it */
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;

    pkt.stream_index = video_stream->index;

    ret = av_read_frame(fmt_ctx, &pkt);
    while (ret >= 0)
    {
        index++;

        //pkt.stream_index = video_avstream->index;
        if(pkt.stream_index == video_stream->index)
        {
            printf("Video: Read cycle %d, bytes read = %d, pkt stream index=%d\n", index, pkt.size, pkt.stream_index);
            av_write_frame(av_format_context, &pkt);
        }
#ifdef _AUDIO_WRITE_ENABLED_
        else if(pkt.stream_index == audio_stream->index)
        {
            printf("Audio: Read cycle %d, bytes read = %d, pkt stream index=%d\n", index, pkt.size, pkt.stream_index);
            av_write_frame(av_format_context, &pkt);
        }
#endif
        av_free_packet(&pkt);
        ret = av_read_frame(fmt_ctx, &pkt);
    }

    av_write_trailer(av_format_context);

    /** Exit procedure starts */
    avformat_close_input(&fmt_ctx);
    avformat_free_context(av_format_context);

    return 0;
}

When I execute this program, it outputs "codec not found". Now sure whats going wrong, Can somebody help please.
Codec not found issue is resolved by separately building libvpx1.4 version. Still struggling to read from source file, and writing to a destination file.
EDIT 1: After code modification, only video stuff I am able to write to a file, though some more errors are still present.
EDIT 2: With modified code (2nd round), I see video frames are written properly. For audio frames I added the code under a macro _AUDIO_WRITE_ENABLED_  , but if I enable this macro program crashing. Can somebody guide whats wrong in audio write part (code under macro _AUDIO_WRITE_ENABLED_).

A: I am not fully answering your question, but I hope we will get to the final solution eventually. When I tried to run your code, I got this error "time base not set".
Time base and other header specs are part of codec. This is, how I have this thing specified for writing into file (vStream is of AVStream):
#if LIBAVCODEC_VER_AT_LEAST(53, 21)
    avcodec_get_context_defaults3(rc->vStream->codec, AVMEDIA_TYPE_VIDEO);
#else
    avcodec_get_context_defaults2(rc->vStream->codec, AVMEDIA_TYPE_VIDEO);
#endif
#if LIBAVCODEC_VER_AT_LEAST(54, 25)
    vStream->codec->codec_id = AV_CODEC_ID_VP8;
#else
    vStream->codec->codec_id = CODEC_ID_VP8;
#endif
    vStream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
    vStream->codec->time_base = (AVRational) {1, 30};
    vStream->codec->width = 640;
    vStream->codec->height = 480;
    vStream->codec->pix_fmt = PIX_FMT_YUV420P;

EDIT: I ran your program in Valgrind and it segfaults on av_write_frame. Looks like its time_base and other specs for output are not set properly.
Add the specs before avformat_write_header(), before it is too late.


text:
Q: How do I turn a Firebase snapshot into an array of items? {
    "body": "Hello there",
    "viewers": {
        "1": {
            "user_id": 1
        },
        "2":{
            "user_id": 2
        }
    }
}

Above is the snapshot I received from Firebase.
        fireRef!.observeEventType(FEventType.Value) { [weak self] (snapshot: FDataSnapshot!) -> Void in
            if let stuff = snapshot.value as? [String:AnyObject] {
                print(stuff) //okay, it prints the snapshot correctly
                //Now, I need to access the "viewers" part, but how?
            }
        }

How can I loop through each viewer and print the user ID?

A: Popped open my last project with Firebase, I was solving this problem as follows:
if let viewers = stuff["viewers"] as? [String:[String:Int]] { //Firebase could deliver your numbers as strings, in that case try [String:[String:String]]
                for viewer in viewers {
                    let userID = viewer.1
                    print(userID.values.first)
                }
            }

There could be a cleaner way to do it


text:
Q: Trying to write to existing excel worksheet with Pandas ExcelWriter and getting bad zip file Am trying to delete and write over an entire excel spreadsheet called Data. The code below returns "BadZipFile: File is not a zip file". How would I fix this?
import pandas as pd
from openpyxl import load_workbook

file_loc = 'G:\\my_existing_excel_data.xlsx'

with pd.ExcelWriter(file_loc, datetime_format='m/d/yyyy') as writer:

    book = load_workbook(file_loc)
    writer = pd.ExcelWriter(file_loc, engine='openpyxl')
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

    date_format = workbook.add_format({'num_format': 'm/d/yyyy'})
    pct_format = workbook.add_format({'num_format': '0.00%'})
    wrap_fmt = workbook.add_format({'text_wrap': True})

    df.to_excel(writer, 'Data')

Full traceback as requested:
Traceback (most recent call last):

  File "C:\Users\AppData\Local\Temp\2/ipykernel_20416/3303582457.py", line 3, in <module>
    book = load_workbook(file_loc)

  File "C:\Anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,

  File "C:\Anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
    self.archive = _validate_archive(fn)

  File "C:\Anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
    archive = ZipFile(filename, 'r')

  File "C:\Anaconda3\lib\zipfile.py", line 1257, in __init__
    self._RealGetContents()

  File "C:\Anaconda3\lib\zipfile.py", line 1324, in _RealGetContents
    raise BadZipFile("File is not a zip file")

BadZipFile: File is not a zip file


text:
Q: Get message id after using /sendMail API I am using Microsoft Graph to authorize our app and send mail with authenticated details:
https://graph.microsoft.com/v1.0/me/sendMail

Everything works well but it only returns HTTP Status Code 202 without the message's id.
Is there a way to get the id of the the sent message?

A: After sending the message, you can find the message in the Send Items folder using /mailfolders/SentItems/messages. You can apply a $filter to limit the results to only the message in question.
There isn't however a way to get the id itself. To get around this you can use extensions to add your own unique id to the message.
Using your own ID allows you to instantly $filter out everything except the exact message you are looking for. To do this you first construct a draft message. You then add your custom data and send the draft message.


text:
Q: Is there a way to access history of Dolphin app browser on android from another application? This is done without root access. Is there a public content provider URI of dolphin app?
Thanks!

A: No, the Dolphin Browser doesn't have an SDK or a ContentProvider that you can access the data. The Android Browser is open-sourced and has more openness toward 3rd-Party Devs, unlike Dolphin.


text:
Q: Pasar información de xml a una tabla creada en oracle con sqldeveloper queria ver si me ayudan con un problema que estoy teniendo, lo que pasa es que tengo un archivo de xml y lo quiero pasar a una tabla que cree en oracle sql developer, la verdad no tengo idea de como empezar y hacerlo?
Comaparto un fragmento de mi xml, lo pongo en una foto, espero y me pueda dar a entender:

Y aqui pongo la estructura de mi tabla:

Quedo al pendiente de sus comentarios.
Saludos y excelente tarde

A: Ahora queda claro que quieres importar los datos desde un archivo XML a una tabla. Para efectuar esto, es necesario que el archivo se encuentre en el mismo server (File System) en que está ejecutandose el motor de Oracle. A grandes rasgos esto es lo que tendrías que hacer:

*

*Almacenar el archivo XML en una ruta del sistema de archivos del servidor Oracle.

*Crear un objeto Directory en Oracle para poder referenciar a la ruta en que se encuentra almacenado el archivo.

*Para poder acceder al contenido del archivo XML se debe utilizar dos funciones de Oracle: BFILENAME (permite recuperar el contenido de un archivo desde un directorio), y XMLType(te permite acceder al documento XML y manipular el contenido del mismo)...
El detalle lo puedes encontrar en la documentación de Oracle (en inglés) (https://docs.oracle.com/cd/B10500_01/appdev.920/a96620/xdb04cre.htm)...

Por acá hay un buen artículo con información que puede ser de utilidad (también en inglés)
https://slobaray.com/2013/03/04/loading-xml-file-into-oracle-tables/
Ahora bien, por las imágenes que compartes, veo que se trata de datos extraidos desde un SQL Server. Si tuvieras acceso a dicho server, podías analizar la alternativa de enviar la información directo a Oracle utilizando SQL Server Integration Services (SSIS) o algún otro ETL.
Espero la información te sea de utilidad....


text:
Q: How to combine 4 characters into 1 character This is driving me nuts because I don't know the magic words to search for to find a solution.
I initialize:
unsigned char foo[] = {'0', 'x', '1', '1'};
unsigned char bar[] = {'\0'};
Essentially I want bar[0] to be equal to the value 0x11. How do I do that? I feel stupid and I'm pretty sure there's a simple solution but I can't figure it out. I tried
memcpy(&bar[0], &foo[0], 1);
But that just makes bar[0] have the value of 0x30, which is the ascii value of the '0' character.
Any help/hints?

A: In case you want to convert text values to integer, that can be done via sscanf function:
char * string = "0x11";
int numeric;
sscanf(string, "%i", &numeric);
// numeric is now 0x11

Note that:

*

*string actually has five characters, as there is a terminating zero at the end. If you ran C-string-expecting function on unterminated array {'0', 'x', '1', '1'} you had above, if would continue processing data past the array, which is something you definitely do not want.

*In real world use with externally-supplied data, you'd have to check for return value of sscanf to make sure it really did the conversion you wanted to do.

A: The notation 'a' converts the character a to a number, as defined by the ASCII system
Therefore,
unsigned char foo[] = {'0', 'x', '1', '1'};

is actually
unsigned char foo[] = {48, 120, 49, 49};

or, in hex
unsigned char foo[] = {0x30, 0x78, 0x31, 0x31};

So, what you need is to simply
unsigned char bar[] = { 0x11 };

or
bar[0] = 0x11;

if you already have bar defined somewhere.

A: I think your question could be a bit wrong formulated and you may want the first alement of bar to have the value that you get when converting the string foo to an hexadecimal integer:
char foo[] = "0x11";
char bar[1];
bar[0] = (char)strtol(foo, NULL, 0);

In your original initialisation of foo you miss the trailing \0.

A: An easy way you can do it:(And there's more too)
If you want to convert: unsigned char foo[] = {'0', 'x', '1', '1'}; into 0x11 and store it in unsigned char bar[] = {'\0'}; Do this:
unsigned char foo[] = {'0', 'x', '1', '1', '\0'};//Add end of string character, to be sure
unsigned char bar[] = {'\0'};//Allocated 1 byte of memory
bar[0]=strtol(foo,NULL,16);//Include stdlib.h. Converts strings to long int and due to assignment, result downgraded to unsigned char


text:
Q: mysqldump include "use db_name" statement with single table dump I'm trying to use mysqldump to programmatically create exports of single tables for a system of exporting and importing tables from our production environment into local development environments.
I need the .sql file to include a "USE database_name" statement at the top. The production db name is different than our local db name (we prefix test_ on development). It is imperative I preserve the .sql dump files as they are used on docker container initialization.
I can achieve this by including the --databases database_name flag in the mysqldump command. The problem is, this dumps the entire database. I only want a single table.
Does anyone know if this is possible somehow - to dump a single table but also include the "USE data_basename" line?
Here's what I have in a bash script, so far - where $1 is the specific table name. This works, but I have to manually enter the "USE database_name" statement at the top of the generated .sql file.
mysqldump -h {host i.p.} -u {username} --password="{password}" db_name $1 > docker/local_mysql_db/files/docker-entrypoint-initdb.d/$1.sql
docker exec -i db_container_name mysql {test_db_name} < docker/local_mysql_db/files/docker-entrypoint-initdb.d/$1.sql


text:
Q: split a dataframe and create many data frames or list I want to create a list or many data.frame from a dataframe at the same time after splitting a matrix. I am using the function combn to create a matrix.
For instance:
 combos<-combn(1:3, 2)
 combos
 [,1] [,2] [,3]
 [1,]    1    1    2
 [2,]    2    3    3

After I have a data frame with 3 columns.
col1<-c(0,2,4);col2<-c(1,3,5);col3<-c(6,7,8)
df<-cbind.data.frame(col1,col2,col3)
df
      col1 col2 col3
 1    0    1    6
 2    2    3    7
 3    4    5    8

Using combos I would like to get this results in data frame or list:
 df1
      col1 col2
 1    0    1
 2    2    3
 3    4    5
df2
      col1  col3
 1    0      6
 2    2      7
 3    4      8
df3
      col2 col3
 1     1    6
 2     3    7
 3     5    8

After of that,
I would want to join these dataframe or list with other dataframes or list to get this result:
using this new data dfo
 col1<-c('a','c'); col2<-c('b','d')
 dfo<-cbind.data.frame(col1,col2)
      col1 col2
 1    a    b
 2    c    d

 df1o
      col1 col2
 1    0    1
 2    2    3
 3    4    5
 4    a    b
 5    c    d

 df2o
      col1  col3
 1    0      6
 2    2      7
 3    4      8
 4    a      b
 5    c      d

 df3o
      col2 col3
  1     1    6
  2     3    7
  3     5    8
  4     a    b
  5     c    d

I have 3000 df and 5000 dfo

A: Actually, you can use lapply to loop over a list.
combos <- combn(1:3, 2)

col1 <- c(0,2,4); col2 <- c(1,3,5); col3 <- c(6,7,8)
df <- cbind.data.frame(col1,col2,col3)

df.1 <- lapply(1:ncol(combos), function(i){df[, combos[,i]]})

col1 <- c('a','c'); col2 <- c('b','d')
dfo <- cbind.data.frame(col1,col2)

dfo.1 <- lapply(df.1, function(x){
  names(dfo) <- names(x)
  return(rbind(x, dfo))
})
# [[1]]
#   col1 col2
# 1    0    1
# 2    2    3
# 3    4    5
# 4    a    b
# 5    c    d
#
# [[2]]
#   col1 col3
# 1    0    6
# 2    2    7
# 3    4    8
# 4    a    b
# 5    c    d
#
# [[3]]
#   col2 col3
# 1    1    6
# 2    3    7
# 3    5    8
# 4    a    b
# 5    c    d


text:
Q: iOS Autolayout to set width and height according to screen size What constraints I should add to set width and height proportional to the Superview (in my case its the UIViewController's view) in iOS Autolayout, with Autoresizing we can do like the pic shown below.

A: if a uiview in a uiviewcontroller.

*

*you must add centre horizontally and vertically in container constraint for that uiview.

*you need to add equal height and equal width constraint for that uiview with your super view.

*select both equal height constraint and equal width constraint and add multiplier to that constraint as your needs.