text:
Q: React native 0.62.0 - Network request error on Android for file upload I have upgraded react-native to 0.62 and i got the problem of Network error for Android only, iOS works fine.
I use FormData object to populate data formated as
const data = new FormData();
// On Android i add file protocol to file path - file://...
data.append('photos', {
   uri: 'file:///data/.../my-image.jpeg',
   type: 'image/jpeg',
   name: 'my-image.jpeg'
});

and other textual data
data.append('description', 'my long description...');

Does anyone have the problem?
I have tried multiple Android SDKs 27, 28, 29, and got same problem on all :(
The things is if i do not upload images, but only textual data request works just fine :(
Any suggestion welcome :)?

A: It is happening because of Flipper network plugin.
Comment line number 43 in the file android/app/src/debug/java/com/<yourappname>/ReactNativeFlipper.java
38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

A: In Flipper version 0.39.0 and above this problem was fixed. I've just update Flipper to version 0.40.0 and it working fine.
https://github.com/facebook/flipper/issues/993#issuecomment-619823916

A: Posting this bec I made it work using react-native-ssl-pinning and react-native-image-crop-picker
FormData
file: {
    uri: image.path,
    type: image.mime,
    name: 'image.jpg',
    fileName: 'image.jpg',
    size: image.size,
  },

and the fetch
fetch(url, {
  method: 'POST',
  sslPinning: { certs: ['cert'] },
  body: {
    formData: formData,
  },
  headers: {
    Authorization:
      'Bearer Token',
    Accept: 'application/json; charset=utf-8',
    'Content-type': 'multipart/form-data; charset=UTF-8',
  },
})

A: *

*In android/app/src/main/java/com/{yourProject}/MainApplication.java
comment the below line :
initializeFlipper(this, getReactNativeHost().getReactInstanceManager())

*In android/app/src/debug/java/com/{yourProject}/ReactNativeFlipper.java
comment in line 43 :
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

*Code for image upload :
var formData = new FormData();
   formData.append('UserId', 'abc@abc.com');
   formData.append('VisitId', '28596');
   formData.append('EvidenceCapturedDate', '09/10/2019 13:28:20');
   formData.append('EvidenceCategory', 'Before');
   formData.append('EvidenceImage', {
     uri: Platform.OS === 'android' ? `file:///${path}` : `/private${path}`,
     type: 'image/jpeg',
     name: 'image.jpg',
   });
   axios({
     url: UrlString.BaseUrl + UrlString.imageUpload,
     method: 'POST',
     data: formData,
     headers: {
       Accept: 'application/json',
       'Content-Type': 'multipart/form-data'
     },
   })
     .then(function (response) {
       console.log('*****handle success******');
       console.log(response.data);

     })
     .catch(function (response) {
       console.log('*****handle failure******');
       console.log(response);
     });


text:
Q: Can I search for something on Google directly from Spotlight? Whenever I have to search for something, I have to open Safari and then type in it. Is there any way to search directly, like type it in Spotlight and press click something and Safari will open automatically and search whatever you typed in Spotlight?

A: Not sure if the feature exists for Spotlight.
However, Alfred is a replacement for Spotlight which does what you need and much more:

A: Haven't tested, but if you install Flashlight there is a plugin for Search on Google.

Add over 120 plugins to OS X's Spotlight search box. Check the weather, search the web, send an iMessage, find an emoji, and more.
For OS X Yosemite. Completely open-source. No crazy installer. Uninstall with one click.

Sample Google search using Flashlight plugin:

A: Type it in Spotlight, and hit ⌘B. (I found this by mistake!)

A: Spotlight can search your safari browsing history for webpages you have previously visited, and it can search wikipedia online for information, but without the above mentioned plugins you can't search google directly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Folder enumeration to identify a specific file leads to nothing The below code does not identify the filepath and store it in the variable "compare_conv_filepath". This is a bug.
The code is written to enumerate files in a folder and identify a file if the filename is identical to "1.xlsx" and then store the entire filepath in a string variable.
The folder it enumarates will always ONLY have 1 file identical to "1.xlsx", but the folder might NOT have a file identical to "1.xlsx". Then the foreach should do nothing or a null value be given. The folder will always have ONE file called "orgFile_[some_filename]" and this filename could be "orgFile_1.xlsx".
Can you help?
using System.IO.Enumeration;

                // Identify converted spreadsheet in folder
                var conv_file = from file in
                Directory.EnumerateFiles(folder)
                            where file.Equals("1.xlsx")
                            select file;
                foreach (var file2 in conv_file)
                {
                    compare_conv_filepath = file2.ToString();

                    // Inform user of comparison
                    Console.WriteLine(compare_conv_filepath);
                    Console.WriteLine($"--> Comparing to: {compare_org_filepath}");
                }

A: You're comparing the file path with it's name. try isolating the name using Path.GetFileName():
 where Path.GetFileName(file).Equals("1.xlsx")


text:
Q: Change the AllowedNetworkTypes for requests in queue or already running in download manager I have a setting in my app that allow the user to choose to download things using WiFi only or also on Mobile Data.
I want when the user changes this setting, to reflect it immediately on the requests currently being downloaded or pending waiting to be downloaded.
EDIT
I am using the DownloadManager class, what I am asking for is to change the allowed networks for items with status STATUS_PENDING or STATUS_RUNNING in DownloadManager.

A: I expect that you are executing this download in a service. If not, please change for it following the android services tutorial: https://developer.android.com/guide/components/services.html
After using a service you should have a configuration (a boolean should do the job) that you will check when executing the download. Following this approach you have a lot of options to change this configuration, in my option that are two good ones:
1: bind the service in the activity that has the option to change the wifi and call a method in the service to change the configuration
2: launch an intent to the service with the new configuration in the bundle. I would follow this one since you do not have to implement all the bind interface methods.
If you want more info, please post the important parts of your code in your question.


text:
Q: Azure Media Services - Secure Asset I'm doing some tests with Azure Media Services. I would like to publish an asset, however it only asks for the start date / end date. There's no option to restrict the access to a particular IP address. What are the options to secure the access of an asset since it's using SAS tokens.

A: I don't think there is option to restrict asset with IP address. The asset owner should keep SAS secret.
The Azure Media Service has IP access control on Streaming Endpoint, but not asset itself.

A: Some further clarifications. I assume that you are trying to publish an encoded Asset for streaming via HLS or DASH protocols, via the Azure Portal. As my colleague already responded, we do not offer IP-address restriction on an Asset by Asset basis. However, you can apply IP address restriction to the streaming endpoint, which will apply to all videos you publish.
The attached screenshot of the Portal shows how you would adjust this. To get to this page, click on the desired streaming endpoint, and then click on Settings.Settings for the streaming endpoint


text:
Q: Display error messages from unique field error We have a unique field on an object, populated by workflow (datestamp + userId), which prevents a user from submitting two records on the same day. I'd like to display an error message on the visualforce input page, but the normal error message approaches don't seem to be working. Is there some special way I need to display this error? Here is my controller:
    public class NewDailyForecast {

        public Daily_Forecast__c fc {get;set;}
        public String userId {get;set;}
        public Date todayDate {get;set;}
        public String dailyType {get;set;}
        public String weeklyType {get;set;}
        public String fName {get;set;}
        public double fAmount {get;set;}
        public String recType {get;set;}
        public List<Daily_Forecast__c> thisWeekDaily {get;set;}
        public List<Daily_Forecast__c> thisWeekWeekly {get;set;}
        public List<Daily_Forecast__c> checkUnique {get;set;}

        //set up controller & extension for vf page
        ApexPages.StandardSetController setCon;

        public NewDailyForecast(ApexPages.StandardSetController controller) {
            setCon = controller;
        }

        public void getValues(){
            //get logged in user
            userId = UserInfo.getUserId();
            system.debug('userId '+userId);

            //get today's date
            todayDate = system.today();
            system.debug('todayDate '+todayDate);

            //get record type
            dailyType = [SELECT Id FROM RecordType WHERE Name = 'Daily Forecast'].Id;
            weeklyType = [SELECT Id FROM RecordType WHERE Name = 'Weekly Forecast'].Id;
            system.debug('dailyType '+dailyType);
            system.debug('weeklyType '+weeklyType);

            fName = userId + todayDate;

            fAmount=0;

            //new forecast record on page
            fc = new Daily_Forecast__c (RecordTypeId = dailyType, Date__c = todayDate, Forecast_Amount__c = fAmount, User__c = userId);
            system.debug('fc '+fc);

            //list of related forecast records
            thisWeekDaily = new List<Daily_Forecast__c>([SELECT Id, Date__c, User__c, User__r.UserRole.Name, User__r.Territory__c, Forecast_Amount__c, RecordTypeId, RecordType.Name
                    FROM Daily_Forecast__c WHERE User__c = :userId AND Date__c = THIS_WEEK AND RecordTypeId = :dailyType ORDER BY Date__c ASC]);
            system.debug('thisWeekDaily '+thisWeekDaily);
            thisWeekWeekly = new List<Daily_Forecast__c>([SELECT Id, Date__c, User__c, User__r.UserRole.Name, User__r.Territory__c, Forecast_Amount__c, RecordTypeId, RecordType.Name
                    FROM Daily_Forecast__c WHERE User__c = :userId AND Date__c = THIS_WEEK AND RecordTypeId = :weeklyType ORDER BY Date__c ASC]);
            system.debug('thisWeekWeekly '+thisWeekWeekly);
        }

        public PageReference saveRecord(){
        //error catching method 1: build list to match existing and throw error if list>0
        //this doesn't work
            checkUnique = new List<Daily_Forecast__c>([SELECT Id, Date__c, User__c FROM Daily_Forecast__c WHERE Date__c = :fc.Date__c AND User__c = :fc.User__c]);
    /*        if(checkUnique.size()>0){
                system.debug('checkUnique '+checkUnique);
                ApexPages.Message myFatalMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Duplicate record created. Please try again');
                ApexPages.addMessage(myFatalMsg);
                system.debug('fatal error '+myFatalMsg);
                ApexPages.Message myErrorMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error Message');
                ApexPages.addMessage(myErrorMsg);
                system.debug('error '+myErrorMsg);
            }
            insert fc;
    */
            //error catching method 2: try insert and catch exception
            //This doesn't work either
            try {
                insert fc;
            }
            catch(DMLException e)
            {
                for(Daily_Forecast__c df :thisWeekDaily){
                    df.addError('Duplicate entry not allowed');
                }
                system.debug(e);
                ApexPages.addMessages(e);
                ApexPages.Message myFatalMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Duplicate record created. Please try again');
                ApexPages.addMessage(myFatalMsg);
                return null;
            }
            return new pageReference( '/' + fc.id );
        }
    }

And vf page:
<apex:page standardController="Daily_Forecast__c" extensions="NewDailyForecast" recordSetVar="forecasts" tabStyle="Daily_Forecast__c" sidebar="false" action="{!getValues}">
        <apex:form >
        <apex:pageblock >
          <apex:messages />

        </apex:pageblock>
        <apex:pageBlock title="Create New Forecast" mode="edit">
                <apex:pageBlockButtons >
                    <apex:commandButton value="Save" action="{!saveRecord}" rerender="error"/>
                    <apex:commandButton value="Cancel" action="{!cancel}"/>
                </apex:pageBlockButtons>
            <apex:pageBlockSection >
                <apex:inputField label="Forecast Type" value="{!fc.RecordTypeId}" id="recType" />
                <apex:inputField label="Amount" value="{!fc.Forecast_Amount__c}" id="fAmount" />
                <apex:inputField label="User Name" value="{!fc.User__c}" id="fUser" />
                <apex:inputField label="Date" value="{!fc.Date__c}" id="fDate" />
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock title="This Week's Forecast">
            <apex:pageBlockSection >
                <apex:pageBlockTable id="thisWeek" value="{!thisWeekDaily}" var="d" >
                    <apex:column headerValue="Day"><apex:outputText value="{0, date, EEEE}">
                            <apex:param value="{!d.Date__c}" />
                        </apex:outputText></apex:column>
                    <apex:column headerValue="Forecast Amount"><apex:outputField value="{!d.Forecast_Amount__c}"/></apex:column>
                    <apex:column headerValue="Type"><apex:outputField value="{!d.RecordType.Name}" /></apex:column>
                </apex:pageBlockTable>
                <apex:pageBlockTable id="thisWeekWeekly" value="{!thisWeekWeekly}" var="w" >
                    <apex:column headerValue="Day"><apex:outputText value="{0, date, EEEE}">
                            <apex:param value="{!w.Date__c}" />
                        </apex:outputText></apex:column>
                    <apex:column headerValue="Forecast Amount"><apex:outputField value="{!w.Forecast_Amount__c}"/></apex:column>
                    <apex:column headerValue="Type"><apex:outputField value="{!w.RecordType.Name}" /></apex:column>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
        </apex:form>
    </apex:page>

What is the correct way to catch and display the unique/duplicate error message on the vf page? Without any error handling i get the expected INSERT FAILED error screen, which is not user-friendly. With the exception catching above, no message shows at all. How can I program the exception handling to display a user-friendly error message? Thanks in advance.

A: The <apex:commandButton> that calls your save method, where you trap exceptions and present them as page messages, has a rerender attribute pointed at an id that doesn't exist ("error"). This will rerender nothing, so your page doesn't react to the addition of error messages.
If you ensure that your <apex:pageMessages /> element is within a rerendered entity, or simply remove the rerender and return null from your save method, you should see messages appear.
Adding error messages using addMessage() and rendering them with an <apex:pageMessages /> component is a good, standard approach that's very user-friendly.


text:
Q: Which is the lesser of two evils? Markup in the ViewModel or logic in the View? I am working on a WCAG AA compliant site.  This means that input forms should have the following attributes if they are no null or empty:
required='required'
value='{the value}'

If they are null or empty then those attributes should not be present.  Hence the following will fail WCAG on two accounts.
<input type='date' required='false' value='' />

I started off with an if statement in the razor view:
@if (Model.HasValue)
{
<input type="date" id="@Model.Name" name="@Model.Name" min="1990-01-01" max="2100-01-01" value="@Model.CoercedValue" />
}
else {
<input type="date" id="@Model.Name" name="@Model.Name" min="1990-01-01" max="2100-01-01" />
}

but this starts to get ugly real fast when other optional attributes are added.  It becomes four statements when the required attribute is added.

I feel there are two ways to go on this, either push the logic to the ViewModel so it returns an attribute string:
public string this[string key]
{
    get {
        switch (key){
            case "Required":
                return IsRequired?"required='required'":String.Empty;
            case "Value":
                return HasValue ? String.Format("value='{0}'", CoercedValue) : String.Empty;
            default:
            return String.Empty;
        }
    }
}

The View then looks like this:
<input type='date' @Model["Required"] @Model["Value"] />

The alternate is to put this logic in a code block in the View
@{
   RequiredAttr = IsRequired?"required='required'":String.Empty;
   ValueAttr = HasValue ? String.Format("value='{0}'", CoercedValue) : String.Empty;
}

and the rest of the view markup:
<input type='date' @RequiredAttr @ValueAttr />

I am leaning to the markup in the ViewModel, but is that the best place for it?  Am I missing a pattern that would solve this?

A: My personal take is that "no code in the View" is a strong guideline, but not absolute gospel.  I have used code in my Views on occasions where the logic is

*

*Simple

*Intended to affect only the HTML in the View, not directly affecting the state of the model.

I think Matthew's comment that an extension to make a custom WCAG-compliant input field would work well.  It's repeatable, consistent, and encapsulates the concern cleanly.


text:
Q: Windows Docker install oracle DB Is there are possible way to install oracle DB in a native Windows docker container ?
FROM microsoft/windowsservercore
COPY /WINDOWS.X64_180000_db_home.zip c:/data/db_home.zip
RUN powershell -command Expand-Archive c:\\data\\db_home.zip -DestinationPath c:\\data\\db_home
RUN setx path ".;c:\data\db_home\Bin;%path%;"
ENV ORACLE_HOME c:\\data\\db_home
COPY /vcredist_x64.exe c:/vcredist_x64.exe
RUN powershell.exe -Command \
$ErrorActionPreference = 'Stop'; \
Start-Process c:\vcredist_x64.exe -ArgumentList '/install /passive /norestart ' -Wait ; \
Remove-Item c:\vcredist_x64.exe -Forc
COPY db.rsp c:\\data\\db.rsp
RUN c:\data\db_home\setup.bat -silent -responseFile c:\data\db.rsp
ENV ORACLE_HOME c:\\data\\db_home
ENV ORACLE_SID orclcdb
ENV CLASSPATH c:\\data\\db_home\\jlib;c:\\data\\db_home\\rdbms\\jlib;
EXPOSE 5500 1521
COPY /scripts C:/data/app/myhome/admin/orclcdb
RUN c:/data/app/myhome/admin/orclcdb/scripts/orclcdb.bat
COPY post_install.bat c:/data/post_install.bat
CMD ["c:/data/post_install.bat"]

This is my current docker file. Have not managed to get the DB running.

A: Yes, there is. See this posting from an Oracle employee. He also links to a presentation he did which has his Dockerfile.
The key point is that you must use Oracle Database 19.7 or later to get the bug fixes pertinent to Windows containers and silent installs. However for the Oracle client I have had success installing the Oracle 18 instantclient.


text:
Q: importing xml document into entity structure created by jaxb I am trying to use jaxb to import an xml document into an entity structure that was created by jaxb. I downloaded jaxb 2.2.7 and am using the create-marshal sample included in that download, but I changed the content of po.xsd to the following:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="businessDocument" type="BusinessDocument"/>

  <xsd:complexType name="CompoundId">
    <xsd:attribute name="root"  type="xsd:string"/>
    <xsd:attribute name="extension" type="xsd:string"/>
  </xsd:complexType>

  <xsd:complexType name="EntityType1">
    <xsd:sequence>
        <xsd:element name="typeId" type="CompoundId"/>
        <xsd:element name="entityTitle" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>

  <xsd:complexType name="BusinessDocument">
    <xsd:sequence>
        <xsd:element name="typeId" type="CompoundId"/>
        <xsd:element ref="documentTitle" minOccurs="1"/>
        <xsd:element name="entity1" type="EntityType1"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

I then created po.xml with the following structure, which is intended to match po.xsd:
<?xml version="1.0"?>
<businessDocument>
    <typeId root="docroot1" extension="docext1"/>
    <documentTitle>first document</documentTitle>
    <entity1>
        <typeId root="innerroot1" extension="innerext1"/>
        <entityTitle>inner title</entityTitle>
    </entity1>
</businessDocument>

I changed Main.java to the following form in order to import po.xml into the entity structure that was created from po.xsd using the create-marshal sample build.xml file:
package mainpackage;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import primer.po.*;
import java.io.*;

public class Main {

    public static void main( String[] args ) {
        String filename = "C:\\Temp\\jaxb\\apps\\create-marshal\\po.xml";
        InputStream is = getInputStream(filename);
        try { unmarshal(BusinessDocument.class, is);}
        catch (JAXBException e) {e.printStackTrace();}
    }

    public static InputStream getInputStream(String filename){
        InputStream is = null;
        try {
            is = new FileInputStream(filename);
            is.close();
        }
        catch (FileNotFoundException e) {e.printStackTrace();}
        catch (IOException e) {e.printStackTrace();}
        return is;
    }

    public static <T> T unmarshal( Class<T> docClass, InputStream inputStream )throws JAXBException {
        String packageName = docClass.getPackage().getName();
        JAXBContext jc = JAXBContext.newInstance( packageName );
        Unmarshaller u = jc.createUnmarshaller();
        JAXBElement<T> doc = (JAXBElement<T>)u.unmarshal( inputStream );
        return doc.getValue();
    }
}

The compile portion of build.xml is:
<!--compile Java source files-->
  <target name="compile" description="Compile all Java source files">
    <echo message="Compiling the schema..." />
    <mkdir dir="gen-src" />
    <mkdir dir="gen-src/primer/po" />
    <xjc schema="po.xsd" package="primer.po" destdir="gen-src">
      <produces dir="gen-src/primer/po" includes="**/*.java" />
    </xjc>
    <echo message="Compiling the java source files..." />
    <mkdir dir="classes" />
    <javac destdir="classes" debug="on">
      <src path="src" />
      <src path="gen-src" />
      <classpath refid="classpath" />
    </javac>
  </target>

But I am getting the following stack trace:
javax.xml.bind.UnmarshalException
 - with linked exception:
[java.io.IOException: Read error]
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:203)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:173)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:184)
    at mainpackage.Main.unmarshal(Main.java:39)
    at mainpackage.Main.main(Main.java:17)
Caused by: java.io.IOException: Read error
    at java.io.FileInputStream.read(Native Method)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager$RewindableInputStream.read(XMLEntityManager.java:2932)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:704)
    at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:186)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:772)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:200)
    ... 5 more

A: Your issue is here:
is = new FileInputStream(filename);
is.close();

So, you try to unmarshal XML from file using FileInputStream for that, but you close is before unmarshal not after ?
UPDATE
I have never used XSD for JAXB, just its annotations on domain classes, but your XSD is stil wrong. Try remove documentTitle element from the beginning of your XSD.


text:
Q: how to bind bootstrap dropdown to html created in jquery and then appended I am attempting to build some drop downs in jquery.  I am struggling with getting the
$('.dropdown-toggle').dropdown()  bound to my added html.
I created a fiddle here demonstrating the problem.
I would like the bottom drop downs to be identical to the upper drop downs.
I created the upper drop downs using plain html markup.
I created the bottom drop downs via jquery.
here is the fiddle http://jsfiddle.net/hLqkLxrm/
fiddle describing problem
here is the javascript

A: On the 2nd line of your $.each function the html is not correctly formed..
Change:
myhtml += '
';

To:
myhtml += '
';

Also, you don't need to the body 'change' handler since Bootstrap data attributes will enable to dropdown to toggle.
Demo: http://www.bootply.com/kzXvjXuE5P


text:
Q: Not able to send put request with postman what I am sending is
http://localhost:3000/accounts?user_id=62139fbf-ce6a-4827-8fe8-f1c3197bff82
  // params
user_id   62139fbf-ce6a-4827-8fe8-f1c3197bff82

My Api in node Js inside account.js is
router.route('/:user_id').put(function(req, res) {
console.log("hello")

It works when I change the route to the following( i.e I remove the params user_id and also from the postman.
router.route('/').put(function(req, res) {
    console.log("efwe")

So the problem is with sending params any help.

A: I believe your URL should be like -
http://localhost:3000/accounts/62139fbf-ce6a-4827-8fe8-f1c3197bff82
for route - router.route('/accounts/:user_id').
For query parameters you need to do something like this - http://localhost:3000/accounts?user_id=62139fbf-ce6a-4827-8fe8-f1c3197bff82
router.route("/accounts",function(req,res){
    var id = req.query.user_id; // Check syntax for framework you are using
});


text:
Q: explanation of MCMC and bayesian estimation I have some questions about bayesian methods.
First of all I have a set of iid observations, calling $y_1,\ldots,y_n$ that come from a certain distribution $f$ with unknown parameters(for example Normal distribution). Then I can form likelihood by $P(D|\vec{\theta})=\prod_i^n f(y_i)$. Now I am going to use bayesian inference to estimate unknown parameters of posterior.
My questions are,

*

*How to choose prior?

*Given a prior (for example a gamma distribution) how can I estimate parameters?

Let denote parameters and data by $\theta=(\theta_1,\ldots,\theta_p)$, $D=(y_1,\ldots,y_n)$ respectively. As far as I realize the posterior is
$$
Pos(\theta|D)\propto P(\theta)P(D|\theta)
$$
Because $\theta$ is unknown, how can I compute $P(\theta)$ and $P(D|\theta)$?
I would be very thankful If somebody give me an explanation of MCMC and connection to above paragraphs.
I want to appreciate all of you for your help: I also found a nice tutorial for bayesian and MCMC algorithm here :https://theoreticalecology.wordpress.com/2010/09/17/metropolis-hastings-mcmc-in-r/

A: I sympathize with your struggle because I was formally trained frequentist and had to pick up a lot of the Bayesian material on my own.  What you should realize is that unlike the frequentist approach, the Bayesian approach does not produce point estimates for model parameters but rather a distribution for them conditional on the data.  That is the posterior distribution $\theta|D \sim Pos(\theta\,|\,D)$ using your notation.  So where we would ordinarily have standard errors that approach zero asymptotically as the number of observations increases, we instead have a posterior distribution who's tails will get thinner and thinner as the number of observations increase, converging on single values asymptotically.
When it comes to actually doing Bayesian inference, MCMC is the most popular tool.  This is because MCMC can produce a sample from the posterior even when the mathematical form for the posterior is not known (which is the case when one is using non-conjugate priors).  In other words for $G$ iterations of MCMC we can simulate $\theta^{(1)},\theta^{(2)},...\theta^{(G)} \stackrel{iid}{\sim} Pos(\theta\,|\,D)$.  This posterior sample can then be used to calculate the probability of any hypothesis, i.e. $Pr(\theta_1<0)$.
I will use the Metropolis algorithm to exemplify how MCMC works as this was how I came to understand it.  (Gibbs sampling is the other popular MCMC algorithm, and there are some others too).   To begin we must specify both the likelihood and the prior.  For this example say we are trying to gather information on the parameters of a variable we know is normally distributed, so the parameters, $\theta_1$ and $\theta_2$ are the mean and variance respectively.  The likelihood can then be written as
$$
P(y_1...y_n|\theta_1,\theta_2)=\prod_{i=1}^{n}f(y_i|\theta_1,\theta_2)
$$
where $f(y_i \; | \; \theta_1, \theta_2) = \frac{1}{\sqrt{2\pi\theta_2} } \; e^{ -\frac{(y_i-\theta_1)^2}{2\theta_2} }$
A prior must also be specified for $\theta_1$ and $\theta_2$.  There are many different priors we can use, for this example assume $\theta_1$ and $\theta_2$ to be independent and that $\theta_1$ is distributed normal with a known mean $\mu$ and variance $\sigma^2$ and $\theta_2$ is distributed chi-squared with known degrees of freedom $k$.  So
$$\theta_1 \sim P_1(\theta_1) \equiv \frac{1}{\sigma\sqrt{2\pi} } \; e^{ -\frac{(\theta_1-\mu)^2}{2\sigma^2} }$$
and
$$
\theta_2 \sim P_2(\theta_2) \equiv \begin{cases} \frac{\theta_2^{(k/2-1)} e^{-\theta_2/2}}{2^{k/2} \Gamma\left(\frac{k}{2}\right)},  &if\;\; \theta_2 \geq 0; \\ 0, &if\;\; \text{otherwise}.
\end{cases}
$$
There is nothing entirely special about these priors, other than my needing to choose something for this example.  In research, priors should always be developed in a thoughtful manner.
We can then write the posterior as being proportional to the product of the likelihood and prior, although I will use different notation here then you did in your question
$$
P(\theta_1,\theta_2|y_1...y_n) \propto P(y_1...y_n|\theta_1,\theta_2)P(\theta_1,\theta_2)=P(y_1...y_n|\theta_1,\theta_2)P_1(\theta_1)P_2(\theta_2)
$$
For ease of notation, define $\boldsymbol{\theta}=(\theta_1,\theta_2)$.
Notice that if I get values for $\boldsymbol{\theta}$ I can plug them into the likelihood and priors to get a value for $P(y_1...y_n|\boldsymbol{\theta})P(\boldsymbol{\theta})$
For the Metropolis algorithm, we must define yet another distribution $J(\boldsymbol{\theta}_i\,|\,\boldsymbol{\theta}_j)$ called a jump or proposal distribution where we can draw a parameter vector $\boldsymbol{\theta}_i$ conditional on a previous draw $\boldsymbol{\theta}_j$.  This distribution will usually be symmetric (for non-symmetric cases we must use the more general Metropolis-Hastings algorithm) and should be a close approximation to the posterior.  A common choice for the proposal is a multivariate normal with mean vector $\boldsymbol{\theta}_j$.
The Metropolis algorithm then proceeds as follows:

*

*Choose an initial starting value $\boldsymbol{\theta}_0$ for which the likelihood and priors are both positive

*For $t \in \{1,2,3,...\}$ draw $\boldsymbol{\theta}_{*}$ from $J(\boldsymbol{\theta}_t\,|\,\boldsymbol{\theta}_{t-1})$ and calculate the ratio
$$
r=\frac{P(\boldsymbol{\theta}_{*}\,|\,y_1...y_n)}{P(\boldsymbol{\theta}_{t-1}\,|\,y_1...y_n)}=\frac{P(y_1...y_n\,|\,\boldsymbol{\theta}_{*})P(\boldsymbol{\theta}_{*})}{P(y_1...y_n\,|\,\boldsymbol{\theta}_{t-1})P(\boldsymbol{\theta}_{t-1})}
$$

*Set
$$
\boldsymbol{\theta}_t = \left\{
     \begin{array}{lr}
      \boldsymbol{\theta}_{*} \;\;\mathrm{with\;\;probability}\;\;\min\{r,1\}\\
       \boldsymbol{\theta} \;\;\mathrm{otherwise}
     \end{array}
   \right.
$$
The sequence $\{\boldsymbol{\theta}_t\}$ converges in distribution to $P(\boldsymbol{\theta}\,|\,y_1...y_n)$.  This sequence forms the Monte Carlo sample discussed above which you can use to calculate the probabilities of hypotheses about $\boldsymbol{\theta}$.  There are many proofs available so instead of hacking up my own google "Metropolis-Hastings Algorithm".

Anyway that is a really long answer, but I hope it helps to answer your question.

A: If the data have a normal distribution, and you're estimating the mean, putting a mostly uninformative normal prior on the mean and inverse gaussian prior on the variance gives you a conjugate  prior. Many commonly estimated types of parameters have conjugate priors to simplify estimation... like a Bernoulli probability with a beta prior.
We are not bound by law to use conjugate  priors. They're not always available, and sometimes it's much easier to throw an "easy to digest" prior at everything rather than going through complex derivations. Easy to digest priors might include a Jeffrey's prior.
That introduces the other error. In Bayesian statistics, we know quite a bit about the parameter after data have been observed, we are not just using approximate confidence intervals to summarize our uncertainty, but we have a whole probability distribution for the posterior which needs to be estimated and described ... and done so reliably!
MCMC refers to any numerical routine, including direct integration, for obtaining the posterior density. The easiest routines to understand are rejection sampling or the Metropolis-Hasting algorithm. The most commonly used routine is Gibbs sampling. The routine is easy to understand, but somewhat techincal. You can read wiki and try it out in R with the mcmc package.

A: You should read Doing Bayesian Data Analysis 2e from John K. Kruschke:
https://sites.google.com/site/doingbayesiandataanalysis/
It is easy to read, and easy to understand. In the Bayes Rule (chapter 4, page 106), you read:
$$\underbrace{p(\theta|D)}_{\large\text{posterior}} = \underbrace{p(D|\theta)}_{\large\text{likelihood}} \quad \underbrace{p(\theta)}_{\large\text{prior}} \; / \quad\underbrace{p(D)}_{\large\text{evidence}}$$
I am quoting from the same page:

The "prior,", $p(\theta)$ is the credibity of the $\theta$ values
  without the data $D$. The "posterior," $p(\theta|D)$ is the
  credibility of $\theta$ values with the data $D$ taken into account.
  The "likelihood," $p(D|\theta)$, is the probability that the data
  could be generated by the model with parameter value $\theta$. The
  "evidence" for the model, $p(D)$, is the overall proability of the
  data according to the model, determined by averaging across all
  possible parameter values weighted by the strength of belief in those
  parameter values.


text:
Q: MySQL optimisation needs explaination I needed to get values from the "latest" (i.e. highest record id) record for each value of a field (server_name in this case).
I had already added a server_name_id index on server_name and id.
My first attempt took minutes to run.
SELECT server_name, state
FROM replication_client as a
WHERE id = (
  SELECT MAX(id)
  FROM replication_client
  WHERE server_name = a.server_name)
ORDER BY server_name

My second attempt took 0.001s to run.
SELECT rep.server_name, state FROM (
  SELECT server_name, MAX(id) AS max_id
  FROM replication_client
  GROUP BY server_name) AS newest,
replication_client AS rep
WHERE rep.id = newest.max_id
ORDER BY server_name

What is the principle behind this optimisation?  (I'd like to be able to write optimised queries without trial and error.)
P.S. Explained below:
mysql> EXPLAIN
    ->
    ->   SELECT server_name, state
    ->   FROM replication_client as a
    ->   WHERE id = (SELECT MAX(id) FROM replication_client WHERE server_name = a.server_name)
    ->   ORDER BY server_name
    -> ;
+----+--------------------+--------------------+------+----------------+----------------+---------+-------------------+--------+-----------------------------+
| id | select_type        | table              | type | possible_keys  | key            | key_len | ref               | rows   | Extra                       |
+----+--------------------+--------------------+------+----------------+----------------+---------+-------------------+--------+-----------------------------+
|  1 | PRIMARY            | a                  | ALL  | NULL           | NULL           | NULL    | NULL              | 630711 | Using where; Using filesort |
|  2 | DEPENDENT SUBQUERY | replication_client | ref  | server_name_id | server_name_id | 18      | mrg.a.server_name |  45050 | Using index                 |
+----+--------------------+--------------------+------+----------------+----------------+---------+-------------------+--------+-----------------------------+

mysql> explain
    ->   SELECT rep.server_name, state FROM (
    ->     SELECT server_name, MAX(id) AS max_id
    ->     FROM replication_client
    ->     GROUP BY server_name) AS newest,
    ->   replication_client AS rep
    ->   WHERE rep.id = newest.max_id
    ->   ORDER BY server_name
    -> ;
+----+-------------+--------------------+--------+---------------+----------------+---------+---------------+------+---------------------------------+
| id | select_type | table              | type   | possible_keys | key            | key_len | ref           | rows | Extra                           |
+----+-------------+--------------------+--------+---------------+----------------+---------+---------------+------+---------------------------------+
|  1 | PRIMARY     | <derived2>         | ALL    | NULL          | NULL           | NULL    | NULL          |    2 | Using temporary; Using filesort |
|  1 | PRIMARY     | rep                | eq_ref | PRIMARY       | PRIMARY        | 4       | newest.max_id |    1 |                                 |
|  2 | DERIVED     | replication_client | range  | NULL          | server_name_id | 18      | NULL          |   15 | Using index for group-by        |
+----+-------------+--------------------+--------+---------------+----------------+---------+---------------+------+---------------------------------+

A: Well, the whole thing is quite self-explaining, when you look at two words in your first explain plan: DEPENDENT SUBQUERY
This means, that for every row, your where condition examines, the subquery is executed. Of course this can be slow as hell.
Also note, that there's an order of operations when executing a query.
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
ORDER BY clause
SELECT clause

When you can filter in FROM clause, it's better than filtering in WHERE clause...


text:
Q: WPF Bind to sys:Boolean not updating I need to update a Resource Value every now and then, however the binding is not updating, how can I go about implementing the Notify method?
This is how I update the Resource, using a timer, the CheckInternet.Status returns a Boolean.
_timer.Tick += (sender, args) =>
            {
                if (t < 10)
                {
                    t++;
                }
                else
                {
                    Application.Current.Resources["InternetConnected"] = new CheckInternet().Status;
                    t = 0;
                }
                CurrentTime = DateTime.Now.ToLongTimeString();
            };

I'm assuming I need something like the following, however I don't really want to add an additional property to bind to, could I not just create an instance of NotifyBoolean and have it set and unset a value and Notify the update without needing an additional property?
public class NotifyBoolean : Common.NotifyUIBase
    {

    }

Edit - The Binding
<TextBlock Text="{Binding Source={StaticResource InternetConnected}, Converter={StaticResource BooleanToStringConverter}, StringFormat=Internet: {0}}" />

A: ResourceDictionary doesn't have any events that are raised when a resource is changed, and generally speaking, you don't use resources for this purpose. Usually, resources are used for things you want to create once and share, like styles, or things like images, brushes, etc. I would even go so far as to say you generally don't want to put something in your ResourceDictionary that could change at some point.
Recommendation: use INotifyPropertyChanged
WPF relies on two interfaces for change notification: for properties, you need to implement INotifyPropertyChanged. For collections, implement INotifyCollectionChanged (or more simply, just use an ObservableCollection<T>, which handles it all for you).
So you create a class:
public class CheckInternetModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool m_InternetConnected;
    public bool InternetConnected
    {
        get { return m_InternetConnected; }
        set
        {
            m_InternetConnected = value;
            OnPropertyChanged();
        }
    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

You can make this your control's DataContext and change your binding to {Binding InternetConnected}.
If you really want to use resources, you could add an instance of this class to your Resources:
<Window.Resources>
    <vm:CheckInternetModel x:Key="CheckInternetModel"/>
</Window.Resources>

Your binding becomes...
<TextBlock Text="{Binding InternetConnected Source={StaticResource CheckInternetModel}, Converter={StaticResource BooleanToStringConverter}, StringFormat=Internet: {0}}" />

Your timer.Tickbecomes...
((CheckInternetModel)Application.Current.Resources["CheckInternetModel"]).InternetConnected = new CheckInternet().Status;

Workaround: manually invalidate the binding
If you insist on storing this as a boolean in the resource dictionary, the only solution left is to manually invalidate the binding using DependencyObject.InvalidateProperty. So you'll have to give your TextBlock a name and then from within your timer.Tick handler, add:
textBlock.InvalidateProperty(TextBlock.TextProperty);

That's not enough though. Your binding is to a StaticResource, so it will not query the ResourceDictionary to get the resource again. You'll have to change the binding to:
<TextBlock Text="{Binding Source={DynamicResource InternetConnected}, Converter={StaticResource BooleanToStringConverter}, StringFormat=Internet: {0}}" />

A DynamicResource forces the binding to look up the resource again each time it's requested, so when you invalidate the TextProperty, it'll retrieve InternetConnected from the dictionary again and it'll have the new value.


text:
Q: meaning of "if part of $A$ iff $B$"? Here I am just wondering if there is some generally accepted convention (or if I have if and only if backwards?)
Specifically, I often see things like "THM: $A$ iff $B$" and then "PF (if part): Assume $A$. Show that $B$ is true"
That is, I often see people calling the "if" part of "A iff B" $A\implies B$. But I thought $A$ if $B$ means $B\implies A$ ? (as in If B is true then A must be true)
I realize that "A iff B" implies "B iff A". So if people often take $A\implies B$ to be the "if part of "A iff B", does than mean that it is convention to prove "A iff B" as "B iff A", or are people just using confusing notation?

A: This is just an error.  There is a natural tendency to think of $A\Rightarrow B$ as the "first part" of $A\Leftrightarrow B$, and also a natural tendency to think of "if" as the "first part" of "if and only if".  Since these conflict, people sometimes erroneously identify which part of $A\Leftrightarrow B$ is "if" and which part is "only if".


text:
Q: How can I reinitialize Apache on my Mac running OS 10.6.4 I got in a bit over my head and probably entered some wrong commands into terminal. Now I can't get my local webpages to work display. I'd like to start from scratch.

A: Find the config file and delete it.  As for the location, you can Google it.


text:
Q: Autolayout labels with UIView and Labels inside UIView I am new to the autolayout thing, was trying to design the given screen for Compact Width|Regular Height via Storyboard. It seems Very simple cause there is none dynamic fields. I was following apple documentation, and setting constraints for each UIView. Its working fine if there would be no View(shown in purple color). But there is some requirement(have to hide the View based on star rating), thats why added this UIView containing dispatch details, complaint category, screenshot etc. e.g- For Invoice Number I set Top Space,Leading Space, Trailing Space and  for the label(shown in green color) Top Space, Leading Space, Trailing Space so that height of invoice Number wouldn't be ambiguous rep, Repeated same for all Views. UIView(purple) constraints are Trailing Space to:SuperView, Bottom space to:SuperView, Bottom space to:Remarks Equals:15, Top Space Equals to:StarRating Equals:8. After that I have added constraints for the fields inside the purple View same as the other Views like Invoice Number. But not getting the desired result for different screen size. Any help would be much appreciated.

A: Use a UITableView to lay out this screen. You can use a static content table view, laid out entirely in the storyboard. Make the purple part its own section. In your UITableViewController subclass, you don't need to implement most data source / delegate methods (because you're using static content). Just override tableView:numberOfRowsInSection: to return 0 for the optional section if you don't want to show it, and use -[UITableView reloadSections:withRowAnimation;] to update the table view. Here's my test code:
#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UITableViewCell *topMarginCell;
@property (strong, nonatomic) IBOutlet UIButton *star1;
@property (strong, nonatomic) IBOutlet UIButton *star2;
@property (strong, nonatomic) IBOutlet UIButton *star3;
@property (strong, nonatomic) IBOutlet UIButton *star4;
@property (strong, nonatomic) IBOutlet UIButton *star5;

@property (strong, nonatomic) NSArray<UIButton *> *starButtons;

@property (nonatomic) NSInteger rating;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.starButtons = @[ self.star1, self.star2, self.star3, self.star4, self.star5 ];
    self.tableView.backgroundColor = self.topMarginCell.backgroundColor;
}

- (void)reloadDispatchSection {
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
}

- (IBAction)starButtonWasTapped:(UIButton *)button {
    NSInteger buttonIndex = [self.starButtons indexOfObject:button];
    if (buttonIndex == NSNotFound) { return; }
    self.rating = buttonIndex + 1;

    [self.starButtons enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj setTitle:(idx <= buttonIndex ? @"★" : @"☆") forState:UIControlStateNormal];
    }];

    [self reloadDispatchSection];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1 && (self.rating == 0 || self.rating >= 4)) {
        return 0;
    } else {
        return [super tableView:tableView numberOfRowsInSection:section];
    }
}

@end

Result:


text:
Q: Responsive design bug I am really desperate about DIV elements positioning bug when trying to create a template for a new responsive layout web design.
The URL is: http://cs.renault-club.cz/responsive_005_bug.php
The problem: when you resize the window to be less than 800px, the "sidebar_right" (online users) DIV element displays not directly under the "obsah" (content) DIV, but bounced under the "sidebar_left" (menu) DIV element.
Please HELP! I spent already 2 hours trying anything, but without any success :(
In less than 500px it works fine, as well bigger than 800px. The current window width is displaying on the top left corner.

A: You have a 2 media queries causing it to push down: if you remove this
@media screen and (max-width: 800px)
#obsah {
    width: 80%;
}

and also remove this
@media screen and (max-width: 800px)
#sidebar_right {
    width: 50%;
}

it will work as you see below:

A: well, between 500 and 800px #sidebar_right has a with of 50% - that's too much to fit right of the other elements (seems like this is defined inline, in the style tag at the top of that page)

A: that's not a bug. it is how the box model works. try:
#sidebar_left { float:left; }


text:
Q: how to get stats for twitter ad campaign I'm new here and looking for some help. I am using twitter in the company I work for(we run Facebook ad campaigns) and we are shortly moving to twitter as well. I am trying to access ad stats for a specific ad using the ad id, such as impressions or clicks.
[https://ads-api.twitter.com/0/stats/accounts/4cury/campaigns/e25e?granularity=DAY&start_time=2013-04-13T07:00:00Z&end_time=2013-04-16T07:00:00Z][1]
This is the example query from the documentation, but I cannot edit this without getting an error. I am able to run queries for campaigns, but the /stats/ endpoint will not work for me.
In the above query I insert the campaign id and ad id, which is ok, but any changes to the time result in an error of INVALID_TIME_WINDOW.
I also change the colons to a character code %3A. I am now stuck on this and cant go any further. I am using postman for chrome to test these queries.
thanks in advance

A: You can use only date in start_date and end_date params.
https://ads-api.twitter.com/0/stats/accounts/4cury/campaigns/e25e?granularity=DAY&start_time=2013-04-13&end_time=2013-04-16

If you want to use the time also, than start_time must be midnight in the timezone of the account, relative to UTC.


text:
Q: Generate a new key name if key exists in dictionary I have code similar to this. Thing is, I have a dictionary containing key, value pairs obtained from some data processing. BUT sometimes the obtained key is empty, and a placeholder has to be created for each value with an empty key, consisting on a prefix and a numeric suffix.
No, I can't use an array because all the data has to be stored on the dictionary, and 99% of the time there will be proper keys, it's just that sometimes a key cannot be retrieved and since it cannot be empty a name has to be generated.
index = 0
keyname_pattern = '[prefix_{0:02d}]'
while keyname_pattern.format(index) in some_dictionary:
    index += 1
self.current_key = keyname.format(index)
# They value is stored in the dictionary at other point in the code.

Thing is, this works perfectly, but for me looks… unpythonic, I can't explain why.
Can this be written in a more compact, explicit, pythonic or just better way?
Thanks a lot!

A: You could use a control value in the dictionary that contains the next value to be used when creating a "special" key.
For example:
some_dictionary = {}

CONTROL_KEY = '__CONTROL__'

def make_placeholder(dict_):
    dict_[CONTROL_KEY] = dict_.get(CONTROL_KEY, -1) + 1
    return f'[prefix_{dict_[CONTROL_KEY]:02d}]'

for _ in range(5):
    print(make_placeholder(some_dictionary))

In this way you don't have to keep searching for the next possible key. If it's likely to interfere with subsequent processing, you could always delete the control key once the dictionary is fully populated.
Output:
[prefix_00]
[prefix_01]
[prefix_02]
[prefix_03]
[prefix_04]


text:
Q: Setting Up Magento ver. 1.7 For Two Domains I am setting up Magento for two separate domains. I want to install two separate versions of Wordpress on each site, so I followed Magento's advice for a "Multiple Website Setup with Different Document Roots": http://www.magentocommerce.com/wiki/multi-store_set_up/multiple_website_setup_with_different_document_roots

*

*I have installed Magento at /public_html and that version is working for the first site.

*I have created another folder called public_html/bluewidgets.com.br/ and I have pointed bluewidgets.com.br at that domain.

*I have a version of the .htaccess file and the index.php file at public_html/bluewidgets.com.br

index.php file changes:
$compilerConfig = MAGENTO_ROOT . '/includes/config.php';
$mageFilename = '/home/bluewidgets/public_html/app/Mage.php';
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] :      'bluewidgets_com_br';
$mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'website';

.htaccess changes:
RewriteBase /bluewidgets\.com\.br/

At this point I feel I am possibly making a mistake with the .htaccess file. When I comment out the line below, all of the pages load but the theme and images don't work. When I run the code below, the homepage loads but nothing else.
RewriteBase /bluewidgets\.com\.br/

I am also wondering if I possibly need to make a change to the configuration of the theme. So far I haven't.
Please could you suggest what I could try?

A: to set up two domains with two hosts you would use Manage Stores in Backend Configuration, you create additional store and assign a new store code to it (lets assume it's bluewidgets_br) then, in your vhost config for bluewidgets.br domain use:
SetEnv MAGE_RUN_CODE bluewidgets_br
also, in Configuration of br store go to system ->configuration -> design, switch to br store view, and update store details to point to different style folders (assuming you have different design/(...) folders prepared for both stores)


text:
Q: How to reformat a timestamp in Python I have some text below that needs to handled. The timestamp is currently listed and then the value. The format for the timestamp is yyyymmdd and I want to be able to alter it to yyyy-mm-dd or some other variation: yyyy/mm/dd, etc. I can't seem to find a string method that inserts characters into strings so I'm unsure of the best way to do go about this. Looking for efficiency here and general advice on slicing and dicing text in python. Thanks in advance!
19800101,0.76
19800102,0.00
19800103,0.51
19800104,0.00
19800105,1.52
19800106,2.54
19800107,0.00
19800108,0.00
19800109,0.00
19800110,0.76
19800111,0.25
19800112,0.00
19800113,6.10
19800114,0.00
19800115,0.00
19800116,2.03
19800117,0.00
19800118,0.00
19800119,0.25
19800120,0.25
19800121,0.00
19800122,0.00
19800123,0.00
19800124,0.00
19800125,0.00
19800126,0.00
19800127,0.00
19800128,0.00
19800129,0.00
19800130,7.11
19800131,0.25
19800201,.510
19800202,0.00
19800203,0.00
19800204,0.00

A: I'd do something like this:
#!/usr/bin/env python

from datetime import datetime

with open("stuff.txt", "r") as f:
    for line in f:
        # Remove initial or ending whitespace (like line endings)
        line = line.strip()

        # Split the timestamp and value
        raw_timestamp, value = line.split(",")

        # Make the timestamp an actual datetime object
        timestamp = datetime.strptime(raw_timestamp, "%Y%m%d")

        # Print the timestamp separated by -'s. Replace - with / or whatever.
        print("%s,%s" % (timestamp.strftime("%Y-%m-%d"), value))

This lets you import or print the timestamp using any format allowed by strftime.

A:
general advice on slicing and dicing text in python

The slice operator:
str = '19800101,0.76'
print('{0}-{1}-{2}'.format(str[:4], str[4:6], str[6:]))

Read: strings (look for the part on slices), and string formatting.

A: Strings are not mutable so inserting characters into strings won't work. Try this:
date = '19800131'
print '-'.join([date[:4],date[4:6],date[6:]])


text:
Q: Develop in a non local environment I have set up a reactJS environment on digitalocean just to start learning developing with react and graphQL and i was wondering if there is a text editor that can connect to connect on the internet and retrieve the files of the project.
Im not really sure if something like this is doable but in my head is like i will code the files on the VPS with a proper text editor and save them so i can have some sort of live preview.
I have already tried with sublime and brackets but im not really sure how to connect them on the project folder in my vps.

A: If your VPS has SFTP set up, you can use your SSH login details to connect and edit code live through an editor such as sublime text.
( I would recommend using FTP if the SSH access is through root or anything with authority on the server, if you do not care about security then feel free to use root )
https://www.sublimetext.com/
An SFTP / FTP plugin exists for what you require, please see below:
https://wbond.net/sublime_packages/sftp
Example usage of the plugin is as follows

*

*Create a project folder

*CTRL+SHIFT+P > "sftp" > SFTP -> Setup Server

*Edit the login details within your sftp-config.json file

*Make sure the remote path is correct and your credentials are correct

*"upload on save" - change to true inside your sftp-config.json file

*Save the sftp-config.json file, CTRL+SHIFT+P > "sftp" > SFTP Sync remote -> local

I'd recommend adding node_modules inside your ignore_regexes, as it can take up to 10-15 minutes to download these.
Now it should ( if set up correctly ) download the files specified in your "remote_path" folder. Saving future files will upload them to the server on save.
I hope this helps!


text:
Q: HijriCalendar calculate Ramadan Feast I try to calculate the ramadan feast. I use the HijriCalendar for this issue.
I have check wikipedia and ramadan feast is on the end of the islamic month Ramadan.
Some dates are good but other on the wrong day (1 day deferred)
var hijriCalendar = new HijriCalendar();

for (var i = 1431; i <= 1438; i++)
{
    var dateTime = new DateTime(i, 10, 1, hijriCalendar);
    Console.WriteLine(dateTime.ToString("yyyy-MM-dd"));
}

Public Holiday Ramadan Feast
First value calculated, second the correct value

*

*2010-09-09 (2010-09-09)

*2011-08-30 (2011-08-30)

*2012-08-18 (2012-08-19) WRONG +1

*2013-08-07 (2013-08-08) WRONG +1

*2014-07-28 (2014-07-28)

*2015-07-17 (2015-07-17)

*2016-07-06 (2016-07-05) WRONG -1

*2017-06-25 (2017-07-25)

Source of correct date
https://www.timeanddate.com/holidays/turkey/ramadan-feast

A: It looks like the C# HijriCalendar acknowledges that the dates of Ramadan can be off and offers a HijriCalendar.HijriAdjustment Property to account for variances from year to year.

This implementation of the HijriCalendar class adjusts the calendar
  date by adding or subtracting a value from zero to two days to
  accommodate the variances in the start and the end of Ramadan and to
  accommodate the date difference between countries/regions

Check out this page for more information about it.
https://msdn.microsoft.com/en-us/library/system.globalization.hijricalendar.hijriadjustment(v=vs.110).aspx


text:
Q: thrust set difference fails to compile with calling a __host__ function from a __host__ __device__ function is not allowed I have a two sets A & B of 20 & 10 integers respectively. B is a subset of A. I need to find the complimentary set of B. I use thrust::set_difference to find the set difference, However it fails to compile with message: warning: calling a __host__ function from a __host__ __device__ function is not allowed
My code is as below. I dont know why this simple code fails to compile.
#include <thrust/sequence.h>
#include <thrust/execution_policy.h>
#include <thrust/set_operations.h>
#include <thrust/device_vector.h>

        thrust::device_vector<int> find_complimentary_set(thrust::device_vector<int> A, thrust::device_vector<int> B)
        {

        thrust::sort(thrust::device, A.begin(), A.end());
        thrust::sort(thrust::device, B.begin(), B.end());

        int N=A.size()-B.size();
        thrust::device_vector<int> complimentary_set(N);

        **// the following line causes the compilation error**
        thrust::set_difference(thrust::device, A.begin(), A.end(), B.begin(), B.end(), complimentary_set);

        return complimentary_set;

        }
            int main(int argc, char * argv[])
            {
            int N=20;
            thrust::device_vector<int> A(N);
            thrust::sequence(thrust::device, A.begin(), A.end(),0);

            thrust::device_vector<int> B(10);
            B[0]=2;B[1]=4;B[2]=8;B[3]=10;B[4]=11;B[5]=13;B[6]=15;B[7]=17;B[8]=19;B[9]=6;

            find_complimentary_set(A, B);

            return 0;
            }

My compilation error is huge. I found the 8 errors in them which i list below:
    /usr/local/cuda/bin/../targets/x86_64-linux/include/thrust/system/cuda/detail/detail/set_operation.inl(517): error: no operator "+" matches these operands
                operand types are: thrust::device_vector<int, thrust::device_malloc_allocator<int>> + thrust::reference<signed long, thrust::pointer<signed long, thrust::system::cuda::detail::par_t, thrust::use_default, thrust::use_default>, thrust::use_default>

    /usr/local/cuda/bin/../targets/x86_64-linux/include/thrust/system/cuda/detail/detail/set_operation.inl(648): error: no operator "+" matches these operands
                operand types are: thrust::device_vector<int, thrust::device_malloc_allocator<int>> + signed long

/usr/local/cuda/bin/../targets/x86_64-linux/include/thrust/system/detail/sequential/set_operations.h(64): error: no operator "*" matches these operands
            operand types are: * thrust::device_vector<int, thrust::device_malloc_allocator<int>>

/usr/local/cuda/bin/../targets/x86_64-linux/include/thrust/system/detail/sequential/set_operations.h(66): error: no operator "++" matches these operands
            operand types are: ++ thrust::device_vector<int, thrust::device_malloc_allocator<int>>

/usr/local/cuda/bin/../targets/x86_64-linux/include/thrust/iterator/iterator_traits.h(49): error: class "thrust::device_vector<int, thrust::device_malloc_allocator<int>>" has no member "iterator_category"

/usr/local/cuda/bin/../targets/x86_64-linux/include/thrust/system/detail/sequential/general_copy.h(106): error: no operator "++" matches these operands
            operand types are: ++ thrust::device_vector<int, thrust::device_malloc_allocator<int>>

/usr/local/cuda/bin/../targets/x86_64-linux/include/thrust/system/detail/sequential/general_copy.h(76): error: no operator "*" matches these operands
            operand types are: * thrust::device_vector<int, thrust::device_malloc_allocator<int>>

A: While using thrust::set_difference the arguments are iterators and not the device_vectors. the last argument to the set_difference has to be complimentary_set.begin() instead of complimentary_set.
the entire correct statement now reads:
thrust::set_difference(thrust::device, A.begin(), A.end(), B.begin(), B.end(), complimentary_set.begin());


text:
Q: $setPristine() not working. **** Note I cut out some of my other functions so that the code could be read through faster.  I cannot clear the form. when i click the button with the cancel function.  I thought I could set a default form, but this doesn't make a difference.
<form  name="myForm" novalidate ng-submit="submit()">

             Base Meal Price:
            <input type="number" name="price" ng-model="mealPrice" required>

             Tax Rate: %
            <input type="number" step="0.01" name="tax" ng-model="mealTax" required>

             Tip Percentage: %
            <input type="number"  name="tip" step="0.01" ng-model="tipPercent" required>

    <input type="submit" value="Submit">

    <button ng-click="cancel()">Start Over</button>

</form>

Here is my javascript  I am trying to set my form to $setPristine using the button command wiht ng-click.  I though that setting a default form would help but nothing happens on submit
var app = angular.module('myApp',[]).
    controller('costController', function($scope) {
        // $scope.ready= false;
        $scope.mealPrice ="" ;
        $scope.mealTax = 0.05;
        $scope.tipPercent =0.05;
        //  possibly could do

        var defaultForm={
            price: "",
            tax: "",
            tip:""
        }

$scope.cancel = function() {
            $scope.myForm.$setPristine();
            $scope.user = angular.copy(defaultForm);
            console.log('empty');
        }

A: $scope.master = {};

$scope.reset = function(form) {

      if (form) {
          form.$setPristine();
           $scope.user = angular.copy($scope.master);
         form.$setUntouched();
      }

A: I think you're using it wrong.
$setPristine:
"This method can be called to remove the 'ng-dirty' class and set the form to its pristine state (ng-pristine class). This method will also propagate to all the controls contained in this form."
So this only clears classes but not the $scope variables.
You do reset a $scope.user variable, could say:
Add 'user.' in front of every model in the Html
ng-model="user.tipPercent"
ng-model="user.mealTax"
ng-model="user.mealPrice"

And replace this in your JS:
// $scope.ready= false;
$scope.mealPrice ="" ;
$scope.mealTax = 0.05;
$scope.tipPercent =0.05;
//  possibly could do

var defaultForm={
    price: "",
    tax: "",
    tip:""
}

$scope.cancel = function() {
    $scope.myForm.$setPristine();
    $scope.user = angular.copy(defaultForm);
    console.log('empty');
}

to this:
var defaultForm = {
    mealPrice : "",
    mealTax : 0.05,
    tipPercent : 0.05
}

$scope.user = angular.copy(defaultForm);

$scope.cancel = function () {
    $scope.myForm.$setPristine();
    $scope.user = angular.copy(defaultForm);
    console.log('empty');
}

A: This would work if the ng-model were bound to $scope.user.price, $scope.user.tax and $scope.user.tip. However, they are bound to $scope.price, $scope.tax and $scope.tip.
Setting the form $pristine only marks the values as not modified by user. It doesn't actually change the values.
Solution A:
Bind the models to user.* and replace
$scope.mealPrice = '';
$scope.mealTax = 0.05;
$scope.tipPercent = 0.05;

with
$scope.user = {
    mealPrice: '',
    mealTax: 0.05,
    tipPercent: 0.05
};

Solution B:
Replace:
$scope.user = angular.copy(defaultForm);

with
$scope.mealPrice = defaultFrom.mealPrice;
$scope.mealTax = defaultFrom.mealTax;
$scope.tipPercent = defaultFrom.tipPercent;


text:
Q: I have 10 PDFs open in a Chrome window: how can I save all the PDFs on my disk at once? I have 10 PDFs open in a Chrome window: how can I save all the PDFs on my disk at once? I don't want to manually go on each tab and save PDF one by one.

A: You can use an extension named TabSave. Install it and open the extension. You will get all the URLs of the tabs and if you click the cloud looking button, all tabs will start to download. Or you can edit the URL list.


text:
Q: mysqldump from within python script but command not found I need to execute mysqldump from within a django function. I can do so easily enough from the terminal command line, but when I try to run it from within the python script, I get an error:
sh: mysqldump: command not found

when running the following.
filestamp = date.today()
dumpcmd = "mysqldump -u root appdb > appdb%s.out" % (filestamp)
os.system(dumpcmd)

I think the problem has something to do with the Path in either the django application or Eclipse, but I can't figure out why mysqldump can't be found from within the django app but it can be from the command line / virtualenv

A: make sure mysqldump is in your path
$ whereis mysqldump; echo $PATH
mysqldump: /usr/bin/mysqldump /usr/share/man/man1/mysqldump.1.gz
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

and/or
using mysqldump and mysql inside python
import subprocess
subprocess.Popen('mysqldump -h localhost -P 3306 -u -root appdb > appdb.sql', shell=True)

Or use the full path in the Python statement. e.g. /usr/bin/mysqldump


text:
Q: Is there any shortcut to I select the entire text in Dragon NaturallySpeaking's Advanced Scripting editor? I would like to select the the entire text in Dragon's Advanced Scripting editor. Ctrl + A doesn't work. Is there any shortcut to do it?

I use Dragon NaturallySpeaking 12.5 Professional on Windows 7 x64 SP1.

A: Franck, your approach is somewhat cumbersome. Here is a shorter solution that does all you want with two simple shortcuts.
Sub Main
    ' generalized solution for selecting the entire contents of a text or text box when Ctrl-A does not work
    SendKeys "^{home}", True 'to go to the beginning of the document, press Ctrl-Home
    SendKeys "^+{end}", True 'to select everything, press Ctrl-Shift-End
End Sub

A: I haven't found any such shortcut. I simply hold Page UP for a while to place the mouse cursor at the beginning of the box, then hold SHIFT + Page DOWN till it reaches the end.

A: Ctrl+Home/End goes to the Start/End of document. Using the hotkeys go to the start first, then hold down shift, then go to the end.
See https://en.wikipedia.org/wiki/Table_of_keyboard_shortcuts for more hotkeys you might find useful and never knew about.


text:
Q: Why routerLink and router.navigate() act differently? When using this code in HTML:
 <button [routerLink]="[{ outlets: { flow: ['step1'] } }]">click me to show step1</button>

it navigates correctly to '/child/(flow:step1)'!!!
When trying to use this code in Typescript:
this.router.navigate([{ outlets: { flow: ['step1'] } }]);

it trying to navigate to wrong path '/child(flow:step1)'!!!
It just missing the slash.
Service:
import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { EventBusService } from '../../../services/eventBus/eventBus.service';
import { RouterService } from '../../../services/router.service';

@Injectable()
export class FlowManagerService {
  constructor(private router: Router, private r: ActivatedRoute, private     eventBus: EventBusService, private routerService: RouterService) {
  }

  initValidStep() {
    return     (parseInt(this.routerService.currentUrlName.substr(this.routerService.currentUrlName.indexOf('step'), 5).replace('step', ''), 10) === 1);
  }

  goToFirstStep() {
    this.router.navigate([{ outlets: { flow: ['step1'] } }], {relativeTo: this.r});

    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_NEXT);
    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_BACK);
  }

  next(params) {
    const currentStep = this.routerService.currentUrlName.substr(this.routerService.currentUrlName.indexOf('step'), 5).replace('step', '');

    this.eventBus.emit(this.eventBus.globalEvents.FLOW.FLOW_STEP_CHANGE, ({
      type: 'NEXT'
    }));
    this.router.navigate([{ outlets: { flow: [`step${parseInt(currentStep, 10) + 1}`, params] } }], {relativeTo: this.r});

    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_NEXT);
    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_BACK);

  }

  back(params) {
    const currentStep = this.routerService.currentUrlName.substr(this.routerService.currentUrlName.indexOf('step'), 5).replace('step', '');

    this.eventBus.emit(this.eventBus.globalEvents.FLOW.FLOW_STEP_CHANGE, ({
      type: 'NEXT'
    }));
    this.router.navigate([{ outlets: { flow: [`step${parseInt(currentStep, 10) - 1}`, params] } }], {relativeTo: this.r});

    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_NEXT);
    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_BACK);
  }

}

Here is the Module using the Service above:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { FlowManagerService } from './service/flowManager.service';
import { CommonModule } from '@angular/common';

@NgModule({
  providers: [FlowManagerService],
  imports: [
    RouterModule,
    CommonModule
  ]
})
export class FlowManagerModule {

}

A: Because routerLink uses relativeTo option implicitly:
export class RouterLink {
  ...
  get urlTree(): UrlTree {
    return this.router.createUrlTree(this.commands, {
      relativeTo: this.route, <----

You need to provide it explicitly in router.navigate:
constructor(private route: ActivatedRoute)

this.router.navigate([{ outlets: { flow: ['step1'] } }], {relativeTo: this.route});

Here is plunker and the complete working code:
import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { RouterModule, Routes, Resolve, Router, ActivatedRoute } from '@angular/router';
import { APP_BASE_HREF } from '@angular/common';

@Component({
  selector: 'my-app',
  template: `

          <router-outlet></router-outlet>

  `,
})
export class App {
  constructor() {
  }
}

@Component({
  selector: 'master-page',
  template: `

Master Component

          <button (click)='clickFirst()'>Inner Section 1</button>
          <button (click)='clickSecond()'>Inner Section 2</button>
          <router-outlet name='child'></router-outlet>

  `
})
export class Master {
  constructor(private router: Router, private activeRouter: ActivatedRoute) {
  }

  clickFirst() {
    this.router.navigate([{outlets: {child: 'details1'}}], {relativeTo: this.activeRouter});
  }

  clickSecond() {
    this.router.navigate([{outlets: {child: 'details2'}}], {relativeTo: this.activeRouter});
  }
}

@Component({
  template: `

          This content is in the "Inner" page (1)

  `
})
export class Details1 {
  constructor() {
  }
}

@Component({
  template: `

          This content is in the "Inner" page (2)

  `
})
export class Details2 {
  constructor() {
  }
}

const routes: Routes = [
  {
    path: 'master',
    component: Master,
    children: [
      {
        path: 'details1',
        component: Details1,
        outlet: 'child'
      },
      {
        path: 'details2',
        component: Details2,
        outlet: 'child'
      }
    ]
  },
  {
    path: '',
    pathMatch: 'prefix',
    redirectTo: 'master'
  }
];

@NgModule({
  imports: [BrowserModule, RouterModule.forRoot(routes)],
  declarations: [App, Master, Details1, Details2],
  providers: [{
    provide: APP_BASE_HREF,
    useValue: '/'
  }],
  bootstrap: [App]
})
export class AppModule {
}


text:
Q: Check if array contain an array I have a dataset:
number  |  matricule<array>   | name<array>  |    model <array>
----------------------------------------------------------------
AA      |  []                 |  [7]         |     [7]
----------------------------------------------------------------
AA      |  [9]                |  [4]         |     [9]
----------------------------------------------------------------
AA      |  [8]                |  [2]         |     [8, 2]
----------------------------------------------------------------
AA      |  [2]                |  [3, 4]      |     [3,4]

I would like to add a new column "Falg" that contain true or false according the comparison result.
Comparison rule:
if model column contain all values of name columns and not contain matricule array ==> Flag = True
else false.

In case if model contain matricule and contain name (like in line 3 in the dataframe example) ==> Flag = False.

I tried by this code bellow:
def is_subset(a, b):
        if F.size(F.array_except(a, b)) == 0:
            return "True"
        else:
            return "False"
    validate = F.udf(is_subset)
    df_join = df_join.withColumn("Flag", validate(F.col("name"), F.col("model")))
    return df_join

I got an error:

Caused by: org.apache.spark.SparkException: Job aborted due to stage
in is_subset
AttributeError: 'NoneType' object has no attribute '_jvm'

I tried by this code:
df_join = df_join.withColumn("Flag", F.when(
            ((F.size(F.expr(F.array_except(F.col("name"), F.col("model"))) == F.lit(0)))
            & (F.size(F.expr(F.array_except(F.col("matricule"), F.col("model"))) != F.lit(0)))) , True
            ).otherwise(False))

I got this error:
TypeError: 'Column' object is not callable in this line ((F.size(F.expr(F.array_except(F.col("name"), F.col("model"))) == F.lit(0)))

Expected result:
number  |  matricule<array>   | name<array>  |    model <array>   | Flag
---------------------------------------------------------------------------
AA      |  []                 |  [7]         |     [7]            |   True
---------------------------------------------------------------------------
AA      |  [9]                |  [4]         |     [9]            |   False
---------------------------------------------------------------------------
AA      |  [8]                |  [2]         |     [8, 2]         |   False
---------------------------------------------------------------------------
AA      |  [2]                |  [3, 4]      |     [3,4]          |  True

Someone please can suggest me a solution ?
Thank you

A: If you dont want to preserve duplicates:
from pyspark.sql import functions as F
df.withColumn("nm", F.array_intersect("name","model"))\
  .withColumn("nm1", F.array_intersect("matriculate","model"))\
  .withColumn("flag2", F.when((F.col("nm1")==F.col("matriculate"))&(F.size("matriculate")!=0),F.lit(False)).otherwise(F.lit(True)))\
  .withColumn("Flag", F.when((F.col("flag2")==F.lit(True))&(F.col("nm")!=F.col("name")), F.lit(False)).otherwise(F.col("flag2")))\
  .drop("nm","nm1","flag2").show()

+------+-----------+------+------+-----+
|number|matriculate|  name| model| Flag|
+------+-----------+------+------+-----+
|    AA|         []|   [7]|   [7]| true|
|    AA|        [9]|   [4]|   [9]|false|
|    AA|        [8]|   [2]|[8, 2]|false|
|    AA|        [2]|[3, 4]|[3, 4]| true|
+------+-----------+------+------+-----+

If you want to preserve duplicates:
Have to use udf here as array_intersect does not preserve duplicates
def intersect(ar1,ar2):
     return [i for i in ar1 if i in ar2]

udf1= F.udf(intersect, ArrayType(LongType()))

df.withColumn("nm", udf1("name","model"))\
      .withColumn("nm1", udf1("matriculate","model"))\
      .withColumn("flag2", F.when((F.col("nm1")==F.col("matriculate"))&(F.size("matriculate")!=0),F.lit(False)).otherwise(F.lit(True)))\
      .withColumn("Flag", F.when((F.col("flag2")==F.lit(True))&(F.col("nm")!=F.col("name")), F.lit(False)).otherwise(F.col("flag2")))\
      .drop("nm","nm1","flag2").show()

+------+-----------+------+------+-----+
|number|matriculate|  name| model| Flag|
+------+-----------+------+------+-----+
|    AA|         []|   [7]|   [7]| true|
|    AA|        [9]|   [4]|   [9]|false|
|    AA|        [8]|   [2]|[8, 2]|false|
|    AA|        [2]|[3, 4]|[3, 4]| true|
+------+-----------+------+------+-----+


text:
Q: Hadoop 3.0.0 No lib/native folder. WARN util.NativeCodeLoader I was following https://amodernstory.com/2014/09/23/installing-hadoop-on-mac-osx-yosemite/ to install hadoop on my mac for local small tasks.
When hstart/hstop, getting "WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable"
Have tried options in below link to rename folder/path for lib/native. Renamed libexec/ to lib/ but errors in scripts that libexec should be correct.
Hadoop "Unable to load native-hadoop library for your platform" warning
However, in hadoop 3.0.0, the structure is like:
username-local:hadoop me$ pwd
/usr/local/Cellar/hadoop

username-local:hadoop me$ ls
3.0.0   hdfs

username-local:hadoop me$ cd 3.0.0/
username-local:3.0.0 me$ ls
INSTALL_RECEIPT.json    NOTICE.txt      bin         sbin
LICENSE.txt     README.txt      libexec

username-local:3.0.0 me$ cd libexec/
username-local:libexec me$ ls
bin etc libexec logs    sbin    share

username-local:libexec me$ cd libexec/
username-local:libexec me$ pwd
/usr/local/Cellar/hadoop/3.0.0/libexec/libexec
username-local:libexec me$ ls
hadoop-config.sh        hdfs-config.sh          tools
hadoop-functions.sh     mapred-config.sh        yarn-config.sh
hadoop-layout.sh.example    shellprofile.d

username-local:libexec me$ cd ../etc/
username-local:etc me$ ls
hadoop
username-local:etc me$ cd hadoop/
username-local:hadoop me$ ls
capacity-scheduler.xml          httpfs-log4j.properties         mapred-site.xml
configuration.xsl           httpfs-signature.secret         shellprofile.d
container-executor.cfg          httpfs-site.xml             ssl-client.xml.example
core-site.xml               kms-acls.xml                ssl-server.xml.example
hadoop-env.sh               kms-env.sh              user_ec_policies.xml.template
hadoop-metrics2.properties      kms-log4j.properties            workers
hadoop-policy.xml           kms-site.xml                yarn-env.sh
hadoop-user-functions.sh.example    log4j.properties            yarn-site.xml
hdfs-site.xml               mapred-env.sh
httpfs-env.sh               mapred-queues.xml.template
username-local:hadoop me$

Any ideas please?
Thank you.


text:
Q: Question on permission packaging - does User == System? This Permission Sets and Profile Settings in Packages document includes a line item:

Do they include user permissions? No. No.

saying that these User permissions cannot be packaged as part of a permission set or profile.
Does that mean every permission in the System list here (the edit view of a profile) cannot be packaged:


text:
Q: Blanchard Kahn conditions are not satisfied: indeterminacy I am working on a real business cycle model. I am very new to Dynare programme. When I run the model, it says: There are 7 eigenvalue(s) larger than 1 in modulus
for 10 forward-looking variable(s)
The rank condition ISN'T verified!
Error using print_info (line 45)
Blanchard Kahn conditions are not satisfied: indeterminacy.
Does someone have an idea how to overcome this problem?
var
chat
ihat
    nhat
    qhat
    Rhat
    Rkhat
khat
    zhat
    what
    hhat
    xihat
    vahat
    vbhat
    nthat
    vthat
    shat
 ;
 varexo eps_z
    eps_xi
    ;
parameters betta
upsilon
alppha
phi
delta
lambda
epsilon
theta
siggma
rho_z
sigma_z
rho_xi
sigma_xi
covariance_z_xi
;
betta=0.9942;
upsilon=1.7167;
alppha=0.36;
phi=3.6;
delta=0.025;
lambda=0.1548;
epsilon=0.001;
theta=0.9685;
siggma=1;
rho_z=0.9315;
sigma_z=0.006424;
rho_xi=0.3744;
sigma_xi=0.0512;
covariance_z_xi=0;
model(linear);
#zstar=1;
#xistar=1;
#qstar=1;
#Rstar=1/betta-1;
#Rkstar=1/betta-1;
#nstar=((1-alppha)/theta*((1/betta-1+delta)/alppha)^(alppha/(alppha-
1)))/((theta+1-alppha)/theta*((1/betta-
1+delta)/alppha)^(alppha/(alppha-
1))-delta*((1/betta-1+delta)/alppha)^(1/(alppha-1)));
#kstar=((1/betta-1+delta)/alppha)^(1/(alppha-1))*nstar;
#cstar =(kstar/nstar)^alppha*(1-alppha)/theta*(1-nstar);
#ystar=(kstar/nstar)^alppha*nstar
#istar=delta*kstar;
#sstar=kstar;
#ntstar=(1-theta)/(1+betta*theta);
#vastar =qstar*sstar*(lambda/ntstar);
#vbstar=vastar;
#vtstar=0;
//1
1/(1-nstar)*nstar*nhat+siggma*chat=what;
//2
siggma*chat(+1)-siggma*chat=Rhat(+1);
//3
Rkhat(+1)*Rkstar=(zhat(+1)+(1-alppha)*khat+(1-alppha)*nhat(+1))*
 (nstar/kstar)^(1-alppha)+(qhat(+1)-qhat)*qstar;
//4
what=zhat+alppha*khat(-1)-alppha*hhat;
//5
vahat*vastar=xihat+vbhat*vbstar;
//6
qhat+shat=nthat-vthat*vtstar/(lambda-vtstar)+vahat;
//7
nthat*ntstar=(1-theta)*betta*Rhat(+1)*Rstar+betta*theta*((vahat(+1)-
vahat)+nthat(+1));
//8
vthat*vtstar=(1-theta)*betta*(Rkhat(+1)*Rkstar-
Rhat(+1)*Rstar)+betta*theta*(qhat(+1)-qhat+shat(+1)-shat+vahat(+1));
//9
vbhat(+1)*vbstar=theta*(Rkhat(+1)*Rkstar-
Rhat(+1)*Rstar+nthat+vthat*vtstar/(lambda-
vtstar)+Rhat(+1)*Rstar)+epsilon*vbhat;
//10
shat=khat;
//11
khat=khat(-1)-delta*khat(-1)-ihat*(istar/kstar)+(-phi*delta*(ihat-
khat(-1)))*istar/kstar;
//12
qhat*qstar=(phi*(ihat-khat(-1)))*(istar/kstar);
//13
hhat=nhat;
//14
chat*cstar/ystar+ihat*istar/ystar=zhat+alppha*khat(-1)+(1-
alppha)*hhat;
//15
zhat=rho_z*zhat(-1)+eps_z;
//16
xihat=rho_xi*xihat(-1)+eps_xi;
end;
steady_state_model;
    chat=0;
    ihat=0;
    nhat=0;
    qhat=0;
    Rhat=0;
    Rkhat=0;
    khat=0;
    zhat=0;
    what=0;
    hhat=0;
    xihat=0;
    vahat=0;
    vbhat=0;
    nthat=0;
    vthat=0;
    shat=0;
end;
shocks;
var eps_xi; stderr 0.01;
var eps_z; stderr 0.01;
var eps_z,eps_xi=covariance_z_xi ;
end;
resid(1);
steady;
check;
stoch_simul(order=1,irf=20,periods=250);

A: Usually that means that there is a fundamental timing error in your model, typically related to the predetermined variables like capital or bonds or capital. Without knowing your model, this is hard to tell. Note that stackoverflow is probably not the right place to ask such a question. Dynare has a dedicated forum at https://forum.dynare.org/
EDIT following a post at https://forum.dynare.org/t/blanchard-kahn-conditions-not-satisfied-indeterminacy/10484/1:
Your timing structure for capital seems correct, but the one for net worth is almost surely wrong.
If you have
vahat // bank net worth (after the shock) deviations from trend
vbhat // bank net worth (before the shock) deviations from trend

then the second one must be predetermined with respect to the shock at time t. But how can they then be contemporaneously related as in
vahat*vastar=xihat+vbhat*vbstar;


text:
Q: Gmail in Android - Getting No provider for gimaps I am using latest jars 1.5.3 from https://java.net/projects/javamail/lists/users/archive/2012-08/message/0 in android
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "gimaps");
Session session = Session.getInstance(props);

GmailSSLStore store = (GmailSSLStore) session.getStore("gimaps");
store.connect("-SNIP-@gmail.com", "-SNIP-");

and this error in last line "No provider for gimaps"


text:
Q: Android ProgressBar code seems to have errors I am using the following lines of code from the AndroidDevelopers website (http://developer.android.com/guide/topics/ui/layout/listview.html):
ProgressBar progressBar = new ProgressBar(this);
progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, Gravity.CENTER));
progressBar.setIndeterminate(true);
getListView().setEmptyView(progressBar);

// Must add the progress bar to the root of the layout
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
root.addView(progressBar);

The line of code,
progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, Gravity.CENTER));

seems to have an error, as no LayoutParams Constructor takes three arguments. I would like to have my progressbar at the center of the screen. Are there any fixes to the above code?

A: It's just an import namespace problem. Use the import line below.
import android.widget.FrameLayout.LayoutParams;

A: Actually FrameLayout does.
FrameLayout.LayoutParams(int width, int height, int gravity)

Creates anew set of layout parameters with the specified width, height and
  weight.

http://developer.android.com/reference/android/widget/FrameLayout.LayoutParams.html

A: private ProgressDialog progressDialog;
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("MyMessage");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(1000);
progressDialog.setMessage("MyMessage");
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.setProgress(10);

you can also customize it using setView() method


text:
Q: ImportError: cannot import name 'image_to_string' from 'pytesseract' (unknown location) I installed tesseract via homebrew and I'm using a virtual environment called Virtualenv in VS Code.
The error when running the code(Python) is this:
ImportError: cannot import name 'image_to_string' from 'pytesseract' (unknown location)
Any ideas that can help me?
follow the python code below.
from pytesseract import image_to_string
from PIL import Image
import PIL
import pytesseract

print(image_to_string(Image.open('base-image/ocr.png')))


text:
Q: Boot a Mac with WiFi turned off Is there any way to boot a Mac with WiFi turned off completely, until manually turned on again?
(And to be precise - it should be turned off completely and not just disconnected from a network.)
The use case would be to patch a Mac that hasn't been used in a while
(and has been powered off) and therefore booting it in an unpatched state
is a small but non-zero security risk.
I've searched the web and haven't found any hint (could be me using wrong search phrases) so at this point I'm looking for any undocumented, "obscure" solution that's out there.
EDIT: This question has been marked as a duplicate of Can I disable wifi on boot? System not booting but while it's pretty similar,
I believe it's also different, so let me clarify.
The other question is about fixing a system that doesn't boot, whereas my question is about security.
We know that EFI in Macs is able to connect to WiFi to download the Recovery image,
or in case of Macs with the T2 chip--to verify the OS if secure boot is enabled.
This means that if the system hasn't been updated in a longer while,
the WiFi (or more general: networking) code in the EFI can have known vulnerabilities.
So basically when I turn on such a vulnerable Mac, up to a few minutes can pass
until I can disable the WiFi in macOS preferences (let's say is has a spinning disk,
so the boot time is significant),
and even then the EFI will still be able to turn it on after a reboot.
Now, I'm fully aware that it's unlikely that something bad will happen,
but I'm hoping to learn a way to somehow enable "radio silence" mode on boot,
e.g. using some magic, undocumented keyboard shortcut.


text:
Q: Method Illuminate\View\View::paginate does not exist. laravel 5.8 I am trying to get all the results where the user's status is teacher (which is a field in my table).
When I tried to use pagination, it runs into an error.
Here is my code in the controller where I'm fetching the results:
public function index()
{
    $status = User::where('status', '=', 'teacher')->get();

    return view('Profile.alluser')->with('status', $status)->paginate(3);
}

*note laravel version is 5.8

A: You need to paginate a Query, while you are trying to paginate a view, please try the code below:
public function index()
{
    $status = User::where('status', '=', 'teacher')->paginate(3);

    return view('Profile.alluser')->with('status', $status);
}


text:
Q: None of code can establish http connection over BIS I am new in developing Blackberry Application.
In these three days, I already searched and learned in both forum and tutorial from the RIM itself. But none of them can solve my problem. >.<
So. I already tried some different methods to establish http connection over BIS in 4.6.
These are the following codes:
1.
        HttpConnection httpConnection;
    String url = "myURL;deviceside=true";

    try{
    httpConnection = (HttpConnection) Connector.open(url);
    Dialog.inform(">.<");
    }

    catch(Exception e)
    {
        Dialog.inform(e.getMessage());
    }

From the code #1 above, none of the dialogs are displayed.

*

*String url = "myURL";

try {

    StreamConnection s = (StreamConnection)Connector.open(url);

    InputStream input = s.openInputStream();

    Dialog.inform("sblm byte");

    byte[] data = new byte[256];
    int len = 0;
    StringBuffer raw = new StringBuffer();

    Dialog.inform("stlh buat byte");

    while( -1 != (len = input.read(data))) {
        raw.append(new String(data, 0, len));
    }

    Dialog.inform("stlh while");
    response = raw.toString();
    Dialog.inform(response);

    input.close();
    s.close();

}

        catch(Exception e) { }

As well as code #1, this code above also doesnt pop up any dialog.
I am desperately need the right guide for establishing simple http connection. Is there any technique that I missed? Do I need any signature for this? Do I need extra setting in both my Blackberry device (BB 8900 with OS 5.00) or in my compiler, Eclipse?
Thank you.

A: Try this code.
 try {

    HttpConnection httpConnection=(HttpConnection)Connector.open(url);
    httpConnection.setRequestMethod(HttpConnection.GET);
   if(httpConnection.getResponseCode()==HttpConnection.HTTP_OK)
   {
     InputStream is=httpConnection.openInputStream();
     int ch;
     StringBuffer buffer=new StringBuffer();
       while((ch=is.read())!=-1)
       {
        buffer.append((char)ch);
      }
     }
    } catch (IOException e) {
        System.out.println("Exception From Thread"+e);
        e.printStackTrace();
    }
}


text:
Q: Strange WPF Behaviour With WCF Async calls I have a WPF application calling WCF via Async calls.
The application has four tabs in which each are loaded from seperate async calls, each tab has a busy indicator.
The problem:  When running within Visual Studio I can click a refresh button on each tab and each tab's busy indicator starts and the data is retrieved from the WCF service.  As each tab's data comes back it is refreshed.
When I deploy the application via one click the application's UI hangs after only two tabs start refreshing.  So in this case I press refresh on tab one, then on tab two and the application hangs until one of the two tabs data comes back.
I thought at first that it was something to do with the WCF service throtteling and that was not the case as both the Visual Studio and the One Click deployments of the application point to the same service.
Anyone have any ideas on where to look?  I cannot reproduce the hang issue within Visual Studio?

A: The limit of 2 things at once smells like
http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultconnectionlimit(v=VS.100).aspx
http://msdn.microsoft.com/en-us/library/6484zdc1.aspx


text:
Q: Как с помощью php перезаписать в div другой текст? Есть например такой блок

Текст
, как с помощью php перезаписать в div другой текст?

A: Предположим, есть переменная хранящая требуемый текст для вывода его в блоке.
$text = "Сегодня хороший день";

Для вывода в html необходимо выбрать один из вариантов и вставить его в нужном месте:

*

*<?=$text;?>

*<? echo $text;?>

*<?php echo $text;?>
Таким образом, используя самый короткий вариант (1), выведем содержимое переменной $text с текстом:

<?=$text;?>


text:
Q: Got language as 0 when calling VerQueryValue My code below is similar to the example in the VerQueryValue() documentation:
// Structure used to store enumerated languages and code pages.

HRESULT hr;

struct LANGANDCODEPAGE {
  WORD wLanguage;
  WORD wCodePage;
} *lpTranslate;

// Read the list of languages and code pages.

VerQueryValue(pBlock,
              TEXT("\\VarFileInfo\\Translation"),
              (LPVOID*)&lpTranslate,
              &cbTranslate);

// Read the file description for each language and code page.

for( i=0; i < (cbTranslate/sizeof(struct LANGANDCODEPAGE)); i++ )
{
  hr = StringCchPrintf(SubBlock, 50,
            TEXT("\\StringFileInfo\\%04x%04x\\FileDescription"),
            lpTranslate[i].wLanguage,
            lpTranslate[i].wCodePage);
    if (FAILED(hr))
    {
    // TODO: write error handler.
    }

  // Retrieve file description for language and code page "i".
  VerQueryValue(pBlock,
                SubBlock,
                &lpBuffer,
                &dwBytes);
}

The code can retrieve string informations for other exe files, but only for 1 particular file, it can not retrieve string infos (I noticed the language is zero for this case).
By using file explorer, I can see the language is 'Language Neutral'. But, the code shows language part is 0 and codepage part is 1252.

*

*Is it normal to get language as 0?

*Furthermore, I'm not able to get CompanyName and other string, but those are available from windows file explorer.

Here's the screenshots in VC++ for that exe:

Any ideas?


text:
Q: Subquery in Where clause SQLKata I try to pass subquery to where clause in SQLKata and compare it with 0 value.
In SQL it should be like this:
WHERE (SELECT count(id) FROM main.someTable) > 0

I try to reproduce it in SQLKata by this code:
var countSubQuery =
    new Query("main.someTable")
        .SelectRaw("count(id)");

return query
    .Where("0", "<", countSubQuery);

But I get error message:
column \"'0'\" does not exist

How can I fix this? Maybe I should pass zero value by another way?

A: I could solve my problem:
query = query
         .WhereSub(countSubQuery, ">", 0);

A: var countSubQuery =
    new Query("main.someTable")
        .SelectRaw("count(id)");

return query
    .Where(Sql("0"), "<", countSubQuery);


text:
Q: Unable to push code to Azure DevOps because of wrong cached credentials It seems I have got somewhere wrong credentials and are cached which is not allowing me to push the code to Azure DevOps (Azure Repository).
I am using Git Bash as a client tool.
Error Message as below:
fatal: Authentication failed for 'https://xxx.visualstudio.com/DefaultCollection/dms/_git/reponame/'

I tried the below solutions but have had no luck

*

*Stop and start Git bash

*git config --global credential.helper "cache --timeout=60"
3 Renamed C:\Users\hp\AppData\Local\GitCredentialManager\tenant.cache to C:\Users\hp\AppData\Local\GitCredentialManager\tenant.cache.bak
Even deleted tenant.cache still no fun...

A: The Good News is that Git Bash (as well as Git GUI) are typically configured to use Windows Credentials Mgr.
Try this:

*

*Start > Credentials ("Credential Manager") > Generic credentials

*DELETE your Azure DevOps URL (it might be called "azure", it might be called "MicrosofAccount")

*Try pushing to Azure DevOps again.  You should be prompted for username/password.

In parallel, you could also try:
git config --global --unset credential.helper
git config --global --add credential.helper manager


text:
Q: How to typeset dimensions of a box? I want to typeset something like this: 3.0 × 3.0 × 0.9 mm
How can I do that in LaTeX (using siunitx package)?
So far, I have this:
\num{3.0} × \num{3.0} × \SI{0.9}{\milli\metre}

But probably someone else knows a better solution.

A: \SI[product-units = single]{2 x 3 x 4}{\milli\metre}

From section 5.13 Numbers with units of the manual.