text:
Q: Django migrate creates the wrong tables in second database I want to create a model that will only be used by a second database in my Django project. So in theory I would have a default database that has all the apps and their models and then this new database will have a separate apps model which would be my jobs data.
The problem I am having is that whenever I migrate to the new database, it duplicates all the tables including the new table that was only meant to be in the new database. All the original contenttypes, sessions, auth etc is getting added to this new 'jobs' database. I only want the Jobdata model/table to be in the jobs database.
I've gone over the Django documentation a few times and haven't had much success with the router that I have set up.
I've also played around with a few options I found on SO but they are a bit dated and didn't detail the issue about migrating
Here is my current set up:
#models.py
#the new table/model that I want to go to a new separate database called jobs
class Jobdata(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
employer_name = models.CharField(max_length=50, blank=True)
empoyer_profile_id = models.CharField(max_length=50, blank=True)

#also in models.py
#the router class used to pick the right database
class JobDataRouter:
    '''Used to tell Django which database must use the job data model'''
    def db_for_read(self, model, **hints):
        """
        Attempts to read Jobdata models go to jobs database.
        """
        if model._meta.app_label == 'jobdata':
            return 'jobs'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write Jobdata models go to jobs database.
        """
        if model._meta.app_label == 'jobdata':
            return 'jobs'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the jobdata app is involved.
        """
        if obj1._meta.app_label == 'jobdata' or \
           obj2._meta.app_label == 'jobdata':
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the jobdata app only appears in the 'jobs'
        database.
        """
        if app_label == 'jobdata':
            return db == 'jobs'
        return None

#settings.py
DATABASE_ROUTERS = ['jobdata.models.JobDataRouter',]

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'django_live',
        'USER': 'postgres',
        'PASSWORD': os.environ.get('postgresuser'),
        'HOST': '127.0.0.1',
        'PORT': '5433',
    },

    'jobs': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'jobs',
        'USER': 'postgres',
        'PASSWORD': os.environ.get('postgresuser'),
        'HOST': '127.0.0.1',
        'PORT': '5433',
    },
}

A: I managed to get the migrations to apply the correct model to the right database. In case anyone else has this issue, this is what worked for me:
I changed my database to use a blank default, then i renamed my primary database where I want the usual apps to go eg. users, auth etc. I called it 'main'
#settings.py
DATABASE_ROUTERS = ['jobdata.models.JobRouter',]
DATABASES = {
    'default': {},
    'main': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'django_live',
        'USER': 'postgres',
        'PASSWORD': os.environ.get('postgresuser'),
        'HOST': '127.0.0.1',
        'PORT': '5433',
    },

    'jobs': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'jobs',
        'USER': 'postgres',
        'PASSWORD': os.environ.get('postgresuser'),
        'HOST': '127.0.0.1',
        'PORT': '5433',
    },
}
'''
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

I then changed my router so that it selects either the main database or the jobs database according to the app it referring to. The Django documentation shows how to do this for the auth or contenttype apps, but i wanted to only do this for the jobdata app which has my jobs data model in it. So I switched the logic around.
#model.py I should probably put this file somewhere else, but documentation doesn't #specify
class JobRouter:
"""
A router to control all database operations on models in the
auth and contenttypes applications.
"""
route_app_labels = {'jobdata'}

def db_for_read(self, model, **hints):
    """
    Attempts to read jobdata models go to jobs database.
    """
    if model._meta.app_label not in self.route_app_labels:
        return 'main'
    return 'jobs'

def db_for_write(self, model, **hints):
    """
    Attempts to write jobdata models go to jobs database.
    """
    if model._meta.app_label not in self.route_app_labels:
        return 'main'
    return 'jobs'

def allow_relation(self, obj1, obj2, **hints):
    """
    Allow relations if a model in the jobdata apps is
    involved.
    """
    if (
        obj1._meta.app_label not in self.route_app_labels or
        obj2._meta.app_label not in self.route_app_labels
    ):
       return None
    return True

def allow_migrate(self, db, app_label, model_name=None, **hints):
    """
    Make sure the jobdata apps only appear in the
    'jobs' database.
    """
    if app_label not in self.route_app_labels:
        return db == 'main'
    return 'jobs'

It seems Django didn't like me having a default table and then this other new table.


text:
Q: String read from a stream is not added to the database I am using NHibernate and it is working perfectly except for adding strings to the database
when I try to add string using this way
string charname = "Dan";
var account = new Account
{
    Username = charname
};
AccountRepository.Add(account);

it works but when I try to add the string that is read from a stream
string charname = reader.ReadString(false, length + 1);
 var account = new Account
 {
     Username = charname
 };
 AccountRepository.Add(account);

it adds nothing to the table. Can anyone explain why this is happening?
(Even though when printing the value charname it is printed correctly)

A: Might be a character appended to the value you want to add that the database is not accepting double check the value you are adding using debugging mode to check what is the actual value is before added to the databse.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SOAP encoding Problems Hey guys I just started to learn soap and I got a problem when I'm expecting to receive a integer all good and when I'm expecting to receive a string or array or json , error is  :
SOAP-ERROR: Encoding: Violation of encoding rules
I already seen all answers about this and it is not helping me. Any ideas what problem is?
Thanks for any advice.
My code is :
  <?xml version='1.0' encoding='UTF-8' ?>
   <definitions name='Names'
             targetNamespace='http://localhost/soap'
             xmlns:tns=' http://localhost/soap '
             xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:xsd='http://www.w3.org/2001/XMLSchema'
            xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/'
            xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/'
         xmlns='http://schemas.xmlsoap.org/wsdl/'>

        <message name="getNamesRequest">
            <part name="num" type="xsd:string"/>
        </message>
        <message name="getNamesResponse">
            <part name="Result" type="xsd:string"/>
        </message>

        <portType name="NamesPortType">
           <operation name="getNames">
             <input message="tns:getNamesRequest"/>
             <output message="tns:getNamesResponse"/>
           </operation>
        </portType>

        <binding name="NamesBinding" type="tns:NamesPortType">
          <soap:binding style="rpc"
             transport="http://schemas.xmlsoap.org/soap/http"/>
              <operation name="getNames" />
        </binding>

         <service name="NamesService">
            <port name="NamesPort" binding="tns:NamesBinding" >
             <soap:address
                location="http://localhost/soap/server.php" />
             </port>
         </service>
    </definitions>

server.php
     <?php

       function getNames($num)
        {

          $name = $num;
          return $name;
         }

       ini_set('soap.wsdl_cache_enabled', '0');

         $server = new SoapServer("http://localhost/soap/names.wsdl");

          $server->addFunction("getNames");

           $server->handle();

client.php
          <?php

              try {
                 $client = new SoapClient('http://localhost/soap/names.wsdl');
                 $result = $client->getNames('victor');

                 echo $result;
              } catch (SoapFault $e) {
                  echo $e->getMessage();
              }

A: Please initialize your server and client with UTF-8 encoding:
$server = new SoapServer('http://localhost/soap/names.wsdl', array('encoding'=>'UTF-8'));
$client = new SoapClient('http://localhost/soap/names.wsdl', array('encoding'=>'UTF-8'));


text:
Q: Django Mailer not finding server I'm trying to send an email through Django's wrapper.
Here are my relevant settings.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_HOST_USER = 'myemail@gmail.com'

EMAIL_HOST_PASSWORD = 'mypassword'

EMAIL_PORT = 587

DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

The Email, which I am trying to isolate in the most basic form of a view:
from django.core.mail import send_mail

def index(request):

    subject = 'Subject'
    message = 'message'
    from_email = settings.DEFAULT_FROM_EMAIL

    send_mail(subject, message, from_email, ['email@example.com'])

    return render(request, "index.html")

All of the emails and password are legitimate.  When I execute the code, I get thrown an error message:
SMTPAuthenticationError at /....*Link to sign into my account*
Please log in via your web browser and\n5.7.14 then try again

I did that but continue to get the same message.  The password I give in the app is correct.  Is there anything I need to configure in my gmail account?

A: Change EMAIL_HOST = 'smtp.gmail.com ' toEMAIL_HOST = 'smtp.gmail.com' and I bet your problem will disappear :)
EDIT #1
You are running into authentication issues as EMAIL_USE_TLS is True and Gmail only requires TLS connections for SMTP on port 587. Change to EMAIL_PORT = 587 and you should bypass the issue.
EDIT #2
The error you see can be fixed through your Gmail settings. See -
Django SMTPAuthenticationError


text:
Q: I have installed Anuglar using cli , while checking angular version it is showing following error Error: Cannot find module 'C:\Users\myalmala\AppData\Roaming\npm\node_modules@angular\cli\bin\ng'

A: *

*Uninstall the angular cli if you have already installed it

npm uninstall -g @angular/cli

*Install the angular cli globally now.

npm install -g @angular/cli


text:
Q: Using sum method to get the sum of an array I am trying to get the sum of an array using sum method, but it shows up saying "incompatible types" for "return result" part at the very end. I tried to find out how I can fix it, but I'm kind of stuck.
public class Prog2
{

    public Prog2()
    {
        int a[] = {7, 8, 9, 9, 8, 7};

        System.out.println(sum(a));

    }

    public int[] sum(int s[])
    {
        int result = 0;

        for (int i = 0; i < s.length; i ++)
        {
            result += s [i];
        }
        return result;
    }
}

A: Change public int[] sum(int s[])
to public int sum(int s[])
Since your method should return a single int, not an array.


text:
Q: Concatenate in Access 2000 I have searched 'concatenate' topics and have been unable to find the answer I need.  This posting came close  access sql query to concatenate rows but my attempts to make it work for my purpose failed.
What I have is a table like this
Lic# | Permit  | Year
------------------------
1    | NS1     |   2003
1    | NS1     |   2004
1    | NS2     |   2004
2    | TR      |   2012
2    | NS2     |   2012
3    | OR      |   2008
2    | OR      |   2011
2    | NS1     |   2011
2    |  TR     |   2011

....And so forth.  This table has many unique license numbers with permit type and year (from 2003-2012) listed for each.
What I would like is to create a table that would display the information like this
Lic#  | Permit      | Year
-----------------------------
1     |NS1          | 2003
1     | NS1, NS2    | 2004
2     | TR, NS2     | 2012
3     | OR          | 2008
2     | OR, NS1, TR | 2011

A: As I posted in my comment, this is easy using the group_concat() function in MySQL, but if you want to do it in MS Access, I think you have to deal with this using VBA.
I propose you this function:
public function concatenatePermits(licNo as integer, year as integer)
    dim db as DAO.database, rec as DAO.recordset, strSQL as string
    dim ans as string

    set db = currentdb()
    strSQL = "select permit from [your table] " & _
             "where [lic#]=" & licNo & " and year=" & year & ";"
    set rec = db.openrecordset(strSQL, dbOpenDynaset, dbReadOnly)
    ans = ""
    with rec
        .moveFirst
        do
            if ans = "" then
                ans = !permit
            else
                ans = ans & "," & !permit
            end if
        loop until .EOF
    end with
    rec.close
    db.close
    concatenatePermits = ans
end function

This function can be used in any query. Downside: If your table is really big, the execution of a query that uses this function can be really slow. I think the better approach would be to create an empty table and then fill it row by row using VBA.
Hope this helps you.

Adding rows using VBA
In your comment you ask how to add rows to a table with VBA. Assuming the table exists and you have the data you want to feed into this table, I suggest you something like this:
public sub addData()
    dim db as dao.database, recOut as dao.recordset
    ' Declare all the variables you need for your code'
    set db = currentdb()

    ' recOut will be the table where you want to store your data '
    set recIn = db.openRecordset("tblYourOutTable",dbOpenDynaset,dbEditAdd)

    ' At some point in your code you will need to store data in your table: '
    with recOut
        .addNew
            ![A_Field] = value1
            ![Another_field] = value2
            ![Yet_another_field] = value3
        .update
    end with

    ' Close the recordset and the database objects '
    rec.close
    db.close
end sub


text:
Q: Is there a simple way to navigate between tabs of tabview with primefaces without using wizard? I am trying to do a page with 3 tabs and I want user to navigate between tabs by "next" and "back" buttons without using wizard. But user cannot navigate after second tab. Where is the mistake I could not find?
Here is my html code:
<?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <ui:composition xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:p="http://primefaces.org/ui"
        xmlns:c="http://java.sun.com/jsp/jstl/core"
        template="template/template.xhtml">

        <ui:define name="body">

        <h:form  prependId="false" id="form">
        <p:tabView id="tabPanel" widgetVar="tabPanel" binding="#{myBean.tabView}" dynamic="true">

        <!-- FIRST TAB -->
                <p:tab id="person" title="Person">
                    <h:panelGrid columns="2" cellpadding="10">
                     <h:outputText value="name" />
                     <p:inputText value="#{myBean.user.firstname}" label="Name" </p:inputText>
    <p:commandButton  value="NEXT" action="#{myBean.nextButton}" update=":form:tabPanel" immediate="true"/>
               </h:panelGrid>
    </p:tab>

 <!-- SECOND TAB -->
                <p:tab id="adres" title="Address">
                    <h:panelGrid columns="2" cellpadding="10">
                      <h:outputText value="Phone" />
                      <p:inputMask id="phone" value="#{myBean.user.phone}" mask="1999999999" required="true" requiredMessage="ERROR AT PHONE NUMBER"/>
    <p:commandButton  value="NEXT" action="#{myBean.nextButton2}" update=":form:tabPanel" immediate="true"/>
  </h:panelGrid>
    </p:tab>

                <!-- THIRD TAB -->
                <p:tab title="Contact">
                    <h:panelGrid columns="2" cellpadding="10">

                    </h:panelGrid>
                </p:tab>

            </p:tabView>
        </h:form>
        </ui:define>
        </ui:composition>

And Here is my myBean:
@ManagedBean(name = "myBean")
@ViewScoped
public class MyBean implements Serializable {

private User user = new User();

 private TabView tabView;

    public TabView getTabView() {
        return tabView;
    }

    public void setTabView(TabView tabView) {
      this.tabView = tabView;
    }

    public void nextButton()
    {
        tabView.setActiveIndex(1);
    }

    public void nextButton2()
    {
        tabView.setActiveIndex(2);
    }
}

A: Approach 1
You have some unclosed Tags. After i changed the code as follows and it worked for me.
tabs.xhtml
<h:form  prependId="false" id="form">
    <p:tabView id="tabPanel" widgetVar="tabPanel" binding="#{myBean.tabView}" dynamic="true" activeIndex="0">

        <!-- FIRST TAB -->
        <p:tab id="person" title="Person">
            <h:panelGrid columns="2" cellpadding="10">
                <h:outputText value="name" />
                <p:inputText value="???USERINFO???" label="Name" />
                <p:commandButton  value="NEXT" action="#{myBean.nextButton}" update=":form:tabPanel" immediate="true"/>
           </h:panelGrid>
        </p:tab>

        <!-- SECOND TAB -->
        <p:tab id="adres" title="Address">
            <h:panelGrid columns="2" cellpadding="10">
                <h:outputText value="Phone" />
                <p:inputMask id="phone" value="???USERINFO???" mask="1999999999" required="true" requiredMessage="ERROR AT PHONE NUMBER"/>
                <p:commandButton  value="NEXT" action="#{myBean.nextButton2}" update=":form:tabPanel" immediate="true"/>
            </h:panelGrid>
        </p:tab>

        <!-- THIRD TAB -->
        <p:tab title="Contact">
            <h:panelGrid columns="2" cellpadding="10">
                <h:outputText value="CONTACT" />
            </h:panelGrid>
        </p:tab>
    </p:tabView>
</h:form>

MyBean.java
@ManagedBean(name = "myBean")
@RequestScoped
public class MyBean implements Serializable {

    private static final long serialVersionUID = 2431097566797234783L;

    private TabView tabView;

    public TabView getTabView() {
        return tabView;
    }

    public void setTabView(TabView tabView) {
      this.tabView = tabView;
    }

    public void nextButton()
    {
        tabView.setActiveIndex(1);
    }

    public void nextButton2()
    {
        tabView.setActiveIndex(2);
    }
}

Approach 2
For me switching from ViewScopedto RequestScopeddid the trick.
If i were you, i would do the following:
Remove the binding from the tabView.
<p:tabView id="tabPanel" widgetVar="tabPanel" dynamic="true">

Switch tabs with JavaScript.
<p:button onclick="PF('tabPanel').select(1);return false;" value="NEXT" />

...instead of...
<p:commandButton  value="NEXT" action="#{myBean.nextButton}" update=":form:tabPanel" immediate="true"/>

Approach 3
This third approach works with ViewScoped bean and without binding.
Remove the binding and map the activeIndex of the TabView to a property.
<p:tabView id="tabPanel" dynamic="true" activeIndex="#{myBean.activeIndex}">

On the next button, call an action which increments the activeIndex property.
<p:commandButton  value="NEXT" action="#{myBean.nextTab}" update=":form:tabPanel" />

tabs.xhtml
<h:form id="form">
    <p:tabView id="tabPanel" dynamic="true" activeIndex="#{myBean.activeIndex}">

        <!-- FIRST TAB -->
        <p:tab id="person" title="Person">
            <h:panelGrid columns="2" cellpadding="10">
                <h:outputText value="name" />
                <p:inputText value="???USERINFO???" label="Name" />
                <p:commandButton  value="NEXT" action="#{myBean.nextTab}" update=":form:tabPanel" />
            </h:panelGrid>
        </p:tab>

        <!-- SECOND TAB -->
        <p:tab id="adres" title="Address">
            <h:panelGrid columns="2" cellpadding="10">
                <h:outputText value="Phone" />
                <p:inputMask id="phone" value="???USERINFO???" mask="1999999999" required="true" requiredMessage="ERROR AT PHONE NUMBER"/>
                <p:commandButton  value="NEXT" action="#{myBean.nextTab}" update=":form:tabPanel" />
            </h:panelGrid>
        </p:tab>

        <!-- THIRD TAB -->
        <p:tab id="contact" title="Contact">
            <h:panelGrid columns="2" cellpadding="10">

            </h:panelGrid>
        </p:tab>

    </p:tabView>
</h:form>

MyBean.java
@ManagedBean(name = "myBean")
@ViewScoped
public class MyBean implements Serializable {

    private int activeIndex = 0;

    public int getActiveIndex() {
        return activeIndex;
    }

    public void setActiveIndex(int activeIndex) {
        this.activeIndex = activeIndex;
    }

    public void nextTab() {
        activeIndex++;
    }
}


text:
Q: How to filter array of file paths using array of file names Using lodash, how can I filter out the array of file paths using the array of file names?
var imageNames = ['/Users/x/edm/images/advertiser.jpg', '/Users/x/edm/images/advertiser_mob.jpg', '/Users/x/edm/images/app_store_button.jpg', '/Users/x/edm/images/header.jpg'];

var usedImageNames = ['app_store_button.jpg', 'advertiser.jpg'];

_.mixin({
  findArrayItemsUsingArray: function (collection, values) {
    return _.filter(collection, function (fileName) {
      _.each(values, function (imageName) {
        if (_.endsWith(fileName, imageName))
          return true;
      });
    })
  }
})

console.log(_.findArrayItemsUsingArray(imageNames, usedImageNames));

A: Assuming POSIX filepaths (separated with /):
In ES6:
imageNames.filter(path => {
  let parts = path.split('/')
  let file = parts[parts.length -1]
  return usedImageNames.indexOf(file) !== -1
})

In ES5:
imageNames.filter(function (path) {
  var parts = path.split('/')
  var file = parts[parts.length -1]
  return usedImageNames.indexOf(file) !== -1
})

In Lodash:
_.filter(imageNames, function (path) {
  return _.includes(usedImageNames, _(path).split('/').last())
})

In Lodash + ES6:
imageNames.filter(path => _.includes(usedImageNames, _(path).split('/').last()))

You could do the comparison with _.endsWith(), but consider what would happen if you had /path/to/somefilename.jpg and /path/to/filename.jpg in the imageNames array, but only filename.jpg in the usedImageNames one.
Similarly, you could also use something like .endsWith('/' + name), but I preferred the split-and-last approach for clarity.
I've done some performance testing. Conclusion: don't use Lodash ;) This version with regexp is sometimes slightly faster, but its lack of clarity is probably not worth it:
imageNames.filter(function(path) {
  return usedImageNames.indexOf(path.match(/\/([^/]+)$/)[1]) !== -1
})

A: var objArray = imageNames.map(function(path) {
  var splitted = path.split("/");
  return {name: splitted[splitted.length - 1],
          path: path};
});

_.sort(objArray, "name");


text:
Q: Customizing Router Firmware i've got a netgear DG834 router, and i want to have a go at hacking the firmware on it to try and add a Wake on Lan option. Netgear let you download the source and the tools to build an image, but i'm not sure where to start.
I've never programmed on a unix platform before, and never done any firmware hacking, just wondering if anyone knows any good resources i can look through
Ta

A: Check for openwrt or tomato or some other firmware.

A: Well, hacking would be fine... except that wake-on-lan requires hardware support, which almost certainly does not exist in your device.


text:
Q: Finding subdirectories that doesn not contain a file with name X I have been struggling with finding subdirectories without a file called UID_points.txt where UID is dependent on the user. I have tried many variations according to other threads without success. The general idea is to use find and call test to test for the presence of the file, but It does not seem to use with a regex - what is wrong?
find "topfolder/subfolder/" -mindepth 1 -maxdepth 1 -type d -not -exec test -f  {}/*points.txt \; -print

A: As pointed out in the comments, the * is only expanded by shells. You don't run a shell but just the plain test command.
To fix this you can explicitly start a shell
find topfolder/subfolder/ -mindepth 1 -maxdepth 1 -type d \
     -not -exec sh 'test -f  "$0"/*points.txt' {} \; -print

But note that this will probably fail if *points.txt matches more than one file. You can work around this by using bash's compgen.
find topfolder/subfolder/ -mindepth 1 -maxdepth 1 -type d \
     -not -exec bash 'compgen -G "$0/*points.txt" > /dev/null' {} \; -print

But then again you could run the search in plain bash altogether. This is probably faster than starting a new process for each directory.
for d in topfolder/subfolder/*/; do
  if ! compgen -G "$d/*points.txt" > /dev/null; then
    echo "$d"
   fi
done

A: Combining the suggestion of a shell from @jhnc and the knowledge of when things expand from @Socowi I derived this solution which in my humble opinion seems good
find "topfolder/subfolder/" \
  -mindepth 1 \
  -maxdepth 1 \
  -type d \
  -exec sh -c '[[ $(ls -A "{}"/*points.txt 2>/dev/null) ]] && exit 1; true' \; \
  -print

So instead if risking iterating again, which find already does I can simply check if a file is present and return a boolean accordingly.
Thanks for the help!!


text:
Q: XMLHttpRequest for chrome-extension protocol I'm using background page and I need to inject some code into current tab contents.
so I do following:

*

*define browser_action

*define listener like this chrome.browserAction.onClicked.addListener

*calling script loaded by content_scripts via chrome.tabs.executeScript
And from page content I need to load html resource from within extensions folder.
but using this XMLHttpRequest gives me error Cross origin requests are only supported for HTTP
handled by XMLHttpRequest by error NETWORK_ERR: XMLHttpRequest Exception 101
So how am I supposed to solve it?
Note: address is like chrome-extension://someextensionid/file.html

A: Solved using:
btoa(loadXHR(chrome.extension.getURL('file.html')))

where

*

*btoa = string to base64

*loadXHR = synchronous xmlhttprequest

*chrome.extension.getURL = resolve address in extension folder

this was done in background_page and passed to script in foreground using
chrome.tabs.executeScript

and in foreground, script converted string to html-string and dom object
var div = document.createElement('div');
div.innerHTML = atob(tbr);
document.body.appendChild(div);

where

*

*document.createElement = creates new "" element

*innerHTML = HTML value of div element, so setting it will create DOM parseable content

*atob = base64 string to decoded version

*document.appendChild = appends div with HTML content to body element

A: Instead of:
btoa(loadXHR(chrome.extension.getURL('file.html')))

you should be able to just use:
loadXHR('file.html')

as XMLHttpRequest understands relative path (with root being your extension folder).


text:
Q: Cannot pass yield value to another function I have these two functions:
def getItems(r, c):
     **do something**
     **find and yield four values a, b, c, d**
     yield (a,b,c,d)

def mainfunction(data):
     reader = csv.reader(records)
     for row in reader:
         a,b,c,d = getItems(row, c)
     yield (a,b,c,d)

However, when I run the file, I keep getting an error :
a, b, c, d = getItems(r, c)
ValueError: not enough values to unpack (expected 5, got 1)

I'm not sure how to proceed with this!

A: yield converts the function to a generator, each yield being one item of the iterator. The tuple is an other item. So your getItem returns an iterable (~sequence) of tuples, even if it only yields one tuple, it's still an iterator of tuples.
Just replace the yield by return. Or if there's an actual reason for it to be there, you need to iterate the result of getItem.
You could also yield the individual values such that getItem() is an iterable of 4 elements but that doesn't seem very useful.


text:
Q: jquery token input not working in mozilla I am using yii to create a auto populate form.
I am using the token input jquery to find the required person.
The code that i have written is working in chrome but not in mozzila.
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
 <script language="javascript" type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery.tokeninput.js"></script>

 <input type="text" id="bhi" name="blah2" />
 <script>

 $(document).ready(function() {
    $("#bhi").tokenInput("http://shell.loopj.com/tokeninput/tvshows.php", {
        theme: "facebook",
    });

});
</script>


text:
Q: ReactNative: AsyncStorage Problem : I can't retrieve Data the correctly I am trying to use the AsyncStorage in my Project by Saving the token to the AsyncStorage by using setItem()
Action that response with token
 import axios from 'axios';
 import {URL, Config} from '../../service/Api';
 import AsyncStorage from '@react-native-async-storage/async-storage';

export const checkSmsToLoginUser = value => async dispatch => {
  dispatch({type: 'USER_LOGIN_REQUEST'});
  try {
    const {data} = await axios.post(`${URL}user/checkSMSCode`, value, Config);
    console.log(data.token); // it consoles the token
    await AsyncStorage.setItem('USER_TOKEN', data.token);
    dispatch({type: 'USER_LOGIN_SUCCESS', payload: data?.token});
  } catch (error) {
    dispatch({type: 'USER_LOGIN_ERROR', payload: error});
  }
};

and I dispatch the action in the component,  then I try to get the the token from the the AsyncStorage by using getItem
 const getData = async () => {
    try {
      const token = await AsyncStorage.getItem('USER_TOKEN');
      return token, JSON.parse(token);
    } catch (error) {
      return error;
    }
  };

  console.log(getData(), 'token From AsyncStorage');

but when I console the token that comes from the AsyncStorage, I have some sort of unhandled promise

any clue what's the problem or maybe solution?

A: This might help
function App() {

  const getData = async () => {
    try {
      const token = await AsyncStorage.getItem('USER_TOKEN');

      // Log here
      console.log(JSON.parse(token), 'token From AsyncStorage');

    } catch (error) {
      return error;
    }
  };

  useEffect(() => {
   getData(); // call here
  }, []);

  return (
    <View>
      ...
    </View>
  );
}

A: You are printing an async function without awaiting for it.
The code is correct, but the console log is not correct:

console.log(getData(), 'token From AsyncStorage'); // missing async logic

Insert the console log inside the getData function, or await for the response.

A: By Adding the getData() in UseEffect and handling the promise by using then().catch() worked for me
 useEffect(() => {
    getData()
      .then(res => {
        console.log(res, 'it worked');
        setToken(res);
      })
      .catch(err => {
        setError(err);
        console.log(err);
      });
  }, []);


text:
Q: php4 decode string to display as html I'm very new to PHP and I have a small task of displaying a class list from an XML file.  I have managed to figure that part out that took longer than expected.  I'm running into some descriptions that have html characters that are not displaying on my page.  I have tried numerous ways and nothing seems to work for me.  Please take a look and let me know what I'm doing wrong.
    $bb = "
Dont spend another day manually filtering information from your spreadsheets.
";
    $a = htmlentities($bb);
    $b = html_entity_decode($a);

    echo $book['PRODUCTID']." - ".$book['PRODUCTNAME']." - ".$b."

";

Thanks

A: get rid of
    $a = htmlentities($bb);

just use
    $b = html_entity_decode($bb);

A: something like this will help:
str_replace(array("<", ">"), array("<", ">"), $bb);
that should solve the problem


text:
Q: How to extend sales_order_grid.xml listing within my new ui component listing? How to extend sales_order_grid.xml listing within my new ui component listing?
I created new module where i want to show the same order grid as admin panel with filtered orders as per custom flag data. every thing is working fine.
I crated ui component xml where I have to call every component like colums toolbar and datasource.
I want to know if there are a way to extend original sales_order_grid and just change datasource
here is my new uicomponent xml file for now
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">

<argument name="data" xsi:type="array">
    <item name="js_config" xsi:type="array">
        <item name="provider" xsi:type="string">
            personalisedorders_order_grid.personalisedorders_order_grid_data
        </item>
        <item name="deps" xsi:type="string">
            personalisedorders_order_grid.personalisedorders_order_grid_data
        </item>
    </item>
    <item name="spinner" xsi:type="string">spinner_columns</item>
</argument>

<settings>
    <spinner>sales_order_columns</spinner>
    <deps>
        <dep>personalisedorders_order_grid.personalisedorders_order_grid_data</dep>
    </deps>
</settings>

<listingToolbar name="listing_top">
    <settings>
        <sticky>true</sticky>
    </settings>
    <bookmark name="bookmarks"/>
    <columnsControls name="columns_controls"/>
    <exportButton name="export_button"/>
    <filterSearch name="fulltext"/>
    <filters name="listing_filters">
        <filterSelect name="store_id" provider="${ $.parentName }">
            <settings>
                <options class="Magento\Store\Ui\Component\Listing\Column\Store\Options"/>

All Store Views

                Purchase Point
                <dataScope>store_id</dataScope>
                <imports>
                    <link name="visible">ns = ${ $.ns }, componentType = column, index = ${ $.index }:visible</link>
                </imports>
            </settings>
        </filterSelect>
    </filters>
    <massaction name="listing_massaction" component="Magento_Ui/js/grid/tree-massactions">
        <action name="cancel">
            <settings>
                <url path="sales/order/massCancel"/>
                <type>cancel</type>
                Cancel
            </settings>
        </action>
        <action name="hold_order">
            <settings>
                <url path="sales/order/massHold"/>
                <type>hold_order</type>
                Hold
            </settings>
        </action>
        <action name="unhold_order">
            <settings>
                <url path="sales/order/massUnhold"/>
                <type>unhold_order</type>
                Unhold
            </settings>
        </action>
        <action name="pdfinvoices_order">
            <settings>
                <url path="sales/order/pdfinvoices"/>
                <type>pdfinvoices_order</type>
                Print Invoices
            </settings>
        </action>
        <action name="pdfshipments_order">
            <settings>
                <url path="sales/order/pdfshipments"/>
                <type>pdfshipments_order</type>
                Print Packing Slips
            </settings>
        </action>
        <action name="pdfcreditmemos_order">
            <settings>
                <url path="sales/order/pdfcreditmemos"/>
                <type>pdfcreditmemos_order</type>
                Print Credit Memos
            </settings>
        </action>
        <action name="pdfdocs_order">
            <settings>
                <url path="sales/order/pdfdocs"/>
                <type>pdfdocs_order</type>
                Print All
            </settings>
        </action>
        <action name="print_shipping_label">
            <settings>
                <url path="adminhtml/order_shipment/massPrintShippingLabel"/>
                <type>print_shipping_label</type>
                Print Shipping Labels
            </settings>
        </action>
    </massaction>
    <paging name="listing_paging"/>
</listingToolbar>

<dataSource name="personalisedorders_order_grid_source" component="Magento_Ui/js/grid/provider">
    <settings>
        <updateUrl path="mui/index/render"/>
    </settings>
    <aclResource>Magento_Sales::sales_order</aclResource>
    <dataProvider class="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider"
                  name="personalisedorders_order_grid_data">
        <settings>
            <requestFieldName>id</requestFieldName>
            <primaryFieldName>main_table.entity_id</primaryFieldName>
        </settings>
    </dataProvider>
</dataSource>

<columns name="spinner_columns">
    <settings>
        <childDefaults>
            <param name="fieldAction" xsi:type="array">
                <item name="provider" xsi:type="string">
                    sales_order_grid.sales_order_grid.sales_order_columns.actions
                </item>
                <item name="target" xsi:type="string">applyAction</item>
                <item name="params" xsi:type="array">
                    <item name="0" xsi:type="string">view</item>
                    <item name="1" xsi:type="string">${ $.$data.rowIndex }</item>
                </item>
            </param>
        </childDefaults>
    </settings>
    <selectionsColumn name="ids">
        <settings>
            <indexField>entity_id</indexField>
        </settings>
    </selectionsColumn>
    <column name="increment_id">
        <settings>
            <filter>text</filter>
            ID
        </settings>
    </column>
    <column name="store_id" class="Magento\Store\Ui\Component\Listing\Column\Store">
        <settings>
            Purchase Point
            <bodyTmpl>ui/grid/cells/html</bodyTmpl>
            <sortable>false</sortable>
        </settings>
    </column>
    <column name="created_at" class="Magento\Ui\Component\Listing\Columns\Date"
            component="Magento_Ui/js/grid/columns/date">
        <settings>
            <filter>dateRange</filter>
            <dataType>date</dataType>
            Purchase Date
            <sorting>desc</sorting>
        </settings>
    </column>
    <column name="billing_name">
        <settings>
            <filter>text</filter>
            Bill-to Name
        </settings>
    </column>
    <column name="shipping_name">
        <settings>
            <filter>text</filter>
            Ship-to Name
        </settings>
    </column>
    <column name="base_grand_total" class="Magento\Sales\Ui\Component\Listing\Column\Price">
        <settings>
            <filter>textRange</filter>
            Grand Total (Base)
        </settings>
    </column>
    <column name="grand_total" class="Magento\Sales\Ui\Component\Listing\Column\PurchasedPrice">
        <settings>
            <filter>textRange</filter>
            Grand Total (Purchased)
        </settings>
    </column>
    <column name="status" component="Magento_Ui/js/grid/columns/select">
        <settings>
            <filter>select</filter>
            <options class="Magento\Sales\Ui\Component\Listing\Column\Status\Options"/>
            <dataType>select</dataType>
            Status
        </settings>
    </column>
    <column name="billing_address" class="Magento\Sales\Ui\Component\Listing\Column\Address">
        <settings>
            <filter>text</filter>
            Billing Address
            <bodyTmpl>ui/grid/cells/html</bodyTmpl>
            <visible>false</visible>
        </settings>
    </column>
    <column name="shipping_address" class="Magento\Sales\Ui\Component\Listing\Column\Address">
        <settings>
            <filter>text</filter>
            Shipping Address
            <bodyTmpl>ui/grid/cells/html</bodyTmpl>
            <visible>false</visible>
        </settings>
    </column>
    <column name="shipping_information">
        <settings>
            <filter>text</filter>
            Shipping Information
            <visible>false</visible>
        </settings>
    </column>
    <column name="customer_email">
        <settings>
            <filter>text</filter>
            Customer Email
            <visible>false</visible>
        </settings>
    </column>
    <column name="customer_group" component="Magento_Ui/js/grid/columns/select">
        <settings>
            <filter>select</filter>
            <options class="Magento\Customer\Ui\Component\Listing\Column\Group\Options"/>
            <dataType>select</dataType>
            Customer Group
            <visible>false</visible>
        </settings>
    </column>
    <column name="subtotal" class="Magento\Sales\Ui\Component\Listing\Column\Price">
        <settings>
            <filter>textRange</filter>
            Subtotal
            <visible>false</visible>
        </settings>
    </column>
    <column name="shipping_and_handling" class="Magento\Sales\Ui\Component\Listing\Column\Price">
        <settings>
            <filter>textRange</filter>
            Shipping and Handling
            <visible>false</visible>
        </settings>
    </column>
    <column name="customer_name">
        <settings>
            <filter>text</filter>
            Customer Name
            <visible>false</visible>
        </settings>
    </column>
    <column name="payment_method" component="Magento_Ui/js/grid/columns/select">
        <settings>
            <filter>select</filter>
            <options class="Magento\Payment\Ui\Component\Listing\Column\Method\Options"/>
            <dataType>select</dataType>
            Payment Method
            <visible>false</visible>
        </settings>
    </column>
    <column name="total_refunded" class="Magento\Sales\Ui\Component\Listing\Column\PurchasedPrice">
        <settings>
            <filter>textRange</filter>
            Total Refunded
            <visible>false</visible>
        </settings>
    </column>
    <actionsColumn name="actions" class="Magento\Sales\Ui\Component\Listing\Column\ViewAction">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="viewUrlPath" xsi:type="string">sales/order/view</item>
                <item name="urlEntityParamName" xsi:type="string">order_id</item>
            </item>
        </argument>
        <settings>
            <indexField>entity_id</indexField>
        </settings>
    </actionsColumn>
</columns>


text:
Q: Need help configuring apache .conf file I want to deploy my django app on a Apache 2.4 server. The same server will host static files. The thing is that this server hosts other php based web sites.
In order for all this to work I just need to install mod_wsgi and configure apache's .conf file related to this web site, is that right?
After reading few articles I came up with this config, assuming that the web site will be in the var/www/ folder :
<VirtualHost *:80>
ServerName example.com
#   Alias /events /var/www/events/html
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/example

            Alias /media/ /var/www/example/media/
            Alias /static/ /var/www/example/static/

            <Directory /var/www/example/static>
            Order deny,allow
            Require all granted
            </Directory>

            <Directory /path/to/example/media>
            Order deny,allow
            Require all granted
            </Directory>

            WSGIScriptAlias / /var/www/example/events_promgruz/wsgi.py
            WSGIDaemonProcess example.com python-path=/var/www/example:/opt/envs/lib/python3.6/site-packages
            WSGIProcessGroup example.com

            <Directory /path/to/example/example>
            <Files wsgi.py>
            Order allow,deny
            Require all granted
            </Files>
            </Directory>

    LogLevel debug
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>

What would you suggested to change or add to config?
Is there some other steps to ensure that django app will work and that it doesn't interfere other non wsgi apps?

A: This is what I ended up using:
<VirtualHost *:80>
ServerName expample-domen.com
    ServerAdmin webmaster@localhost
Alias /static /var/www/example/static
Alias /media /var/www/example/media

<Directory /var/www/example/static>
Require all granted
</Directory>

<Directory /var/www/example/media>
    Order deny,allow
    Require all granted
</Directory>

<Directory /var/www/example/example>
<Files wsgi.py>
        Require all granted
    </Files>
</Directory>

    WSGIDaemonProcess example python-home=/path/to/virtualEnv python-path=/var/www/example
    WSGIProcessGroup example
    WSGIScriptAlias / /var/www/example/example/wsgi.py

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>


text:
Q: Provide form data via GET in Django Create View I want to create a CreateView which allow user get a form where they click somethings and response a form with pre-filled fields which cannot not be change.
By the way, I want to display these prefilled and uneditable fields in

 instead of <input>. The code below contains the model which I want CreateView to create, and the form which I still have no idea how to do next.
#models.py
class Booking(Occurrence):
    TYPE_CHOICES = (
        ('web', 'Web Application'),
        ('emb', 'Embedded Application'),
    )
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookings')
    room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='bookings')
    type = models.CharField(max_length=50, choices=TYPE_CHOICES, default='web')
    date = models.DateField()
    start= models.TimeField()
    end = models.TimeField()
    check_in = models.BooleanField(default=False)
    check_out = models.BooleanField(default=False)

#views.py
@method_decorator(login_required, name='dispatch')
class BookingAddView(CreateView):
    model = Booking
    form_class = BookingForm
    template_name = 'booking/add_booking.html'

    def get_initial(self):
        pass

    def form_valid(self, form):
        form.instance.user = self.request.user
        super().form_valid(form)

    def form_invalid(self, form):
        pass

#forms.py
class BookingForm(forms.Model):
    class Meta:
        model = Booking
        fields = ['user', 'room', 'date', 'start', 'end']

    def __init__(self):
        pass

For example, I want room, date, end fields prefilled when rendering. I am thinking of GET but I want know the right way to do it with class CreateView.
I want to something like:
<form>

{room field value}

{date field value}

{start field value}

<input id='id_end' type='text'></input>
</form>


text:
Q: Is there a way to force an instance group to "work harder" at one task? I set up an instance group on the Google Cloud Platform to run a single python script. After running the script for a few hours, it looks like only one instance (4 vCPUs, 16 GB memory) has been running consistently at around 25% CPU, while the other two instances have been at 2%.
Is there a way to tell each instance to contribute more resources to run the script faster? Note that I am not even close to the designated 60% CPU utilization before the load is shared, among other instances.

A: Not directly with Google Cloud.
You will need to design/redesign your software to support multiple CPUs in a cluster. Not a simple task unless designed that way.


text:
Q: How to use this execute immediate create table to insert values in table I am using execute immediate to create table and use this table into my code to insert some values when i run this code .it gives me error that table and view does not exist.why?. this code has ability to create table because when i use drop and create table command with existing table by using execute immediate then my code works fine and when i just remove drop table syntax, my code does not work, Please help me to clear my concept about dynamic SQL-----------
SET serveroutput ON
DECLARE
  ddl_table VARCHAR2(200);
  r_emp     SYS.ODCINUMBERLIST   := SYS.ODCINUMBERLIST();
  v_array   SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST('ACCT_ID',
                                                         'PARENT_ACCT_ID',
                                                         'CUST_ID',
                                                         'ACCT_NAME',
                                                         'BILLING_CYCLE_TYPE',
                                                         'PAID_FLAG',
                                                         'BILL_DELIVER_METHOD');
BEGIN
  ddl_table := 'CREATE TABLE test123(
                                      v_column VARCHAR2(50),
                                      v_count  NUMBER
                                    )';
  EXECUTE IMMEDIATE ddl_table;
  DBMS_OUTPUT.ENABLE;
  FOR i IN 1 .. v_array.COUNT LOOP
    r_emp.EXTEND;
    EXECUTE IMMEDIATE 'SELECT COUNT(*)
                         FROM account_profile
                        WHERE NOT REGEXP_LIKE(' ||v_array(i) || ',''[A-Za-z0-9.]'')'
      INTO r_emp(i);

    IF r_emp(i) <> 0 THEN
      DBMS_OUTPUT.PUT_LINE(v_array(i) || ': ' || r_emp(i));
      INSERT INTO test123 VALUES (v_array(i), r_emp(i));
    END IF;
  END LOOP;
END;
/

Error report -

ORA-06550: line 24, column 17:
PL/SQL: ORA-00942: table or view does not exist

A: Your problem is that the annonymous block is pre-validated (pre-compiled) before it is valid. Oracle will check all objects in use before executing it. Since you are creating test123 dynamically it doesn't exist so your insert statement fails.
You can instead, use an EXECUTE IMMEDIATE command to also insert the data on your test123 table.
The way you use the EXECUTE IMMEDIATE for an insert command is either concatenating the parameters or preparing them, I prefer the later. Like this
execute immediate 'insert into test123 values (:param1,:param2)' using v_array(i), r_emp(i);

Here is the official documentation for the EXECUTE IMMEDIATE command.
Though it shows how it works and explain the usage of it, it doesn't particularly answer you direct question on the comments.
So

can you explain :param1,:param2

Those are called "binding" parameters that will be replaced by the variables used after the using statement. It doesn't matter their  name only the order in which they appear on the string. The number of parameters within the dynamic string needs to match the number of parameters after the using statement.

why we use it with : colon and what are these

The colon : there is just to make it easier for the parser to know what to replace and where when using the variables you provided after the using statement
Translating that execute immediate it would be something like this:
... values (:param1,:param2)' using v_array(i), r_emp(i)
Hey "execute immediate" whenever you see :param1 please replace it with the content of the variable I'm providing as v_array(i) and whenever you see :param2 please replace it with the content of the variable I'm providing as r_emp(i)


text:
Q: Error: It looks like you called `mount()` without a global document being loaded me sale este error al ejecutar mis pruebas.
import { Meteor } from 'meteor/meteor';
import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import { mount } from 'enzyme';
import { chai,  assert } from 'meteor/practicalmeteor:chai';
import { Factory } from 'meteor/dburles:factory';
import faker from 'faker';
import StubCollections from 'meteor/hwillson:stub-collections';

import {Button, FormGroup, ControlLabel, FormControl, HelpBlock,
        ButtonToolbar, Checkbox, Radio, Glyphicon} from 'react-bootstrap';

import MainApp  from '/imports/ui/MainApp.jsx';
import {Companies} from '/imports/api/companies.js';

import {
  insert,
} from '/imports/api/companies.js';

describe('Server', () => {

    Factory.define('user', Companies, {
      firstName: () => 'Daniel',
      lastName: () => 'Peña',
      orgType: () => 'non-profit',
    });

    if (Meteor.isServer)

        it('Se insertan los datos', () => {

            const users = Factory.create('user');
            StubCollections.stub(Companies);
            Companies.insert({ users });
            assert.equal(Companies.find().count(), 1);
            StubCollections.restore();
        });

        it('No se insertan los datos al no seleccionar el TOS', () => {
            const main = mount(<MainApp/>);

            const users = Factory.create('user');
            StubCollections.stub(Companies);

            main.find('div.checkbox').simulate('change', {
              target: { checked: false }
            });

            Companies.insert({ users });
            assert.equal(Companies.find().count(), 0);
            StubCollections.restore();
        });

    return;

});

A: Este error puede ocurrir cuando estás en un entorno sin navegador. Según la documentación de enzyme (traducción mía):

Como la API de enzyme mount requiere un DOM, JSDOM es necesario para poder usar mount si no estás aún en un entorno de navegador (por ejemplo, un entorno Node).

En el github de airbnb hay un par de bugs similares que reciben el mismo mensaje de error que indicas. En ambos casos lo solucionaron importando JSDOM y creando un "DOM vacío". El código es algo como esto (copiado del primer enlace):
import jsdom from 'jsdom'
const doc = jsdom.jsdom('<!doctype html>')
global.document = doc
global.window = doc.defaultView


text:
Q: How to store last value of iteration? Im new to python and just a quick question.
I have created a for loop which runs through the values of a list, then converts into an angle of a circle (multiply by 360). What I want to do now is store that value of the previous iteration. eg, after running this code, I would get
79.2
118.08
21.6
29.52
10.8
7.2
7.2

The Code:
for i in range(len(percentages_minus_index)):
    other_segment_angles = percentages_minus_index[i] * 360

So basically, if the first value is 79.2, I want to store in a variable in the loop, and then replace it after the next iteration. eg.
iteration 1: 79.2, previous value = nothing
iteration 2: 118.08, previous = 79.2
.... etc etc
Any help?

A: You can use another variable, which can store the previous value and also, a better way to loop a list would be, like this
previous = None
for percentage in percentages_minus_index:
    other_segment_angles = percentage * 360
    print previous
    previous = other_segment_angles

But I wonder why you would want to use that, as your program doesn't depend on the previous value. For example, if I want to find the sum of n numbers (without using sum), then
previous = 0
for number in range(10):
    temp = previous + number
    previous = temp

A: You mean something like this?
percentages_minus_index = [23,14,16,1]

previousValues = [None]*len(percentages_minus_index)

for i in range(len(percentages_minus_index)):
    other_segment_angles = percentages_minus_index[i] * 360
    print(other_segment_angles)
    if i > 0:
        previousValue[i] = percentages_minus_index[i-1] * 360
    print(previousValue[i])


text:
Q: How do I use WordPress alongside CFWheels? Anyone with a bit of experience with CFWheels will know how awesome it is, but also how fiddly it is with its placement in the web root / sub-folders etc.
I have a CFWheels website, that I would now like to place alongside a WordPress installation.
CFWheels placed in the web root (which is fine) and I would like WordPress to run in a sub-folder in that same web root named 'blog'. How can I do this without invoking CFWheels desire to find a controller or action called 'blog'?
I know that the 'miscellaneous' folder is a folder that I can place things that CFWheels will ignore, but putting the blog into this directory isn't really an option.
Any help or advice would be great.
EDIT: I just noticed that the miscellaneous folder has a blank Application.cfc file that stops CFWheels messing with it. I'm not around to test this right now, but will update later if it's possible to use this same technique on other folders I create. I may have answered my own question in record time.
Thanks,
Mikey.

A: Wordpress runs on PHP so CFWheels should never get involved in the process. If it does, simply change the DirectoryIndex (or IIS equivalent) to have index.php ahead of index.cfm for the Wordpress directory (or link to blog using full URL and not just the directory) and you should be fine.

A: Placing a blank Application.cfc file in the folder of choice, stops CFWheels getting involved with everything in it.


text:
Q: Heavyweight Jquery slideshows are slow in desktops and crash on ipad 2, android ics and iphone I am building my portfolio site (have a look here ...)
http://www.tripleagent.co.uk/projects.html
And I am using Jquery with jquery.cycle.all.js.  I added about 200 slides with my work dated many years back and a few vimeo videos with fitvid.js (it resizes the videos to fit in a responsive design). My problem is that the page is slow on a workstation computer (i7 ivy bridge and chrome) and it crashes on ipad, android and iphone. I am new on jscript and html5 so I am not sure what is going wrong.
With my limited experience I believe that its running out of memory or that the slower machines can't handle the fade animations simultaneously.
I use a typical setup for the slideshow
$("#slideshow").cycle({
    fx:'fade,',
    speed: 1000,
    slideExpr:'.slide',
    slideResize: 0,
    timeout:        7000,
    pause: 1,
    //sync: true,
    autostop: false,
    pager: '#nav',
    next: '#slideshow',
    pagerEvent: 'mouseover',
    fastOnEvent: true ,
    pagerAnchorBuilder: function(idx, slide)
    {return '

';
    },
    after:   captionsAlt ,
    });

What should I do ? I can break up the page in two and it will probably work but i was thinking that there must be a way to optimize the page instead.
Any suggestions? Is there any mistake, a bug or a bad design idea in the first place ?

A: It has been months since i asked this question.
I upgraded to the latest jquery 1.9.1, cycle.all 3.0.4 I just noticed that Safari, IE9 and mozilla don't have  much of a problem anymore. The videos play well in android 4.1+ and IOS  but it is still a bit heavy and it has some problems regarding touching and scrolling on top of the vimeo player. but i asked that already in the vimeo forums.


text:
Q: Android getting unexpected response from remote server call I am trying to send a call to a remote server with user credentials, and get back a true/false for whether the persons credentials match. But my code is returning the credentials right back to me in JSON lol
        try
        {
            String query = String.format("login=%s&password=%s",
                     URLEncoder.encode(myEmail, charset),
                     URLEncoder.encode(myPassword, charset));

            final URL url = new URL( myUrl + "?" + query );

            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");

            conn.setRequestProperty("login", myEmail);
            conn.setRequestProperty("password", myPassword);

            conn.setUseCaches(false);

            final InputStream is = conn.getInputStream();
            final byte[] buffer = new byte[8196];
            int readCount;
            final StringBuilder builder = new StringBuilder();
            while ((readCount = is.read(buffer)) > -1)
            {
                builder.append(new String(buffer, 0, readCount));
            }

            response = builder.toString();
            Log.d( "After call, response: " , " " + response);
        }
        catch (Exception e)
        {
                Log.d( "Exception: " , "Yup");
                e.printStackTrace();
        }

Would anyone know how I can get the output from the server instead of this stuff that I get back now?
Thanks!

A: Surprisingly the code you have posted works on my standalone java client as well as in my android app. It seems something is wrong on the server part. Can you post any additional output from server??
On server I have a servlet which receives user and passcode in JSON format and returns validation result in json format back.

A: First of all, you're sending the username and password both as URL-encoded parameters http://.../?username=abc&password=test and as HTTP request headers.
Check the documentation of your service to see where the username and password is expected.
Could it be that you service uses HTTP Basic authentication? If so, take a look at the Android documentation at http://developer.android.com/reference/java/net/HttpURLConnection.html, under HTTP Authentication.
PS: remember to disconnect() your connection after use so the resources can be released.

A: Another solution would be to work with the HTTPClient a possible scenario would be like that:
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(yoururlhere);
HttpResponse response = httpClient.execute(request);
respondEntity = EntityUtils.toString(response.getEntity());

This will also work with HttpGet just as you desire. Perhaps this will give you some clarity of what is "really" coming from the server.


text:
Q: create a JSON using swift let nlp_json_string = "{\"appId\":\"**********\",\"cloud\":true}"
let cmd_json_string = "{\"asr\":\"\",\"id\":\(id),\"name\":\"\(name)\",\"nlp\":\"\(nlp_json_string)\",\"subid\":\(subid)}"
print(cmd_json_string)

log:
{"asr":"","id":260744,"name":"aaaaaa","nlp":"{"appId":"**********","cloud":true}","subid":123743947}

I want to build a JSON like this, but this JSON format is wrong, what should I do,The problem is that the "nlp" key causes the JSON to not be formatted. (note: the type of "nlp" value needs to be a String), thanks!

A: You can use the Encodable protocol to convert an object to JSON string or JSON object upto your choice.
Please try to understand the example
//This the the customer structure
struct Customer: Codable {

    var name: String?
    var id: String?
    var account: Account?
}

//This is customer's account structure
struct Account: Codable {

    var acId: String?
    var openedDate: Date?
}

//Main View Controller.
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //Call this fnctions to initiate the process.
        self.makeJson()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func makeJson() {

        //Make the account object
        let accountInfo = Account.init(acId: "100100234", openedDate: Date())

        //Make the customer object
        let customer = Customer.init(name: "Naresh", id: "dfg-2561", account: accountInfo)

        do {

            //make data object
            let data = try JSONEncoder.init().encode(customer)

            //print as JSON String
            let jsonString = String.init(data: data, encoding: String.Encoding.utf8)
            print(jsonString ?? "Not parsed")

            //print as JSON Object
            let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
            print(jsonObject)

        }
        catch {
            print(error.localizedDescription)
        }
    }
}

Look at the terminal. This will print the json string & json object both.

A: The easy way is to create a multiline String:
let myJSON: String = """
{
  "id" : 12,
  "foo": "bar"
}
"""

A: First of all take advantage of the new literal string syntax to avoid the confusion of the escaped double quotes.
Second of all please conform to the naming convention that variables are camelCased

Assumed variables :
let name = "Foo"
let id = 1
let subid = 2

The strings look much clearer.
let nlpJsonString = """
{"appId":"**********","cloud":true}
"""

let cmdJsonString = """
{"asr":"","id":\(id),"name":"\(name)","nlp":"\(nlpJsonString)","subid":\(subid)}
"""

As you can see (better now) nlpJsonString is inserted as String (note the wrapping double quotes) so the result is
{"asr":"","id":1,"name":"Foo","nlp":"{"appId":"**********","cloud":true}","subid":2}

If you want to insert nlpJsonString as a dictionary remove the double quotes
let cmdJsonString = """
{"asr":"","id":\(id),"name":"\(name)","nlp":\(nlpJsonString),"subid":\(subid)}
"""

then you get
{"asr":"","id":1,"name":"Foo","nlp":{"appId":"**********","cloud":true},"subid":2}

An alternative is to create dictionaries and serialize them
let name = "Foo"
let id = 1
let subid = 2

let nlpDict : [String:Any] = ["appId":"**********","cloud":true]
let cmdDict : [String:Any] = ["asr":"","id":id,"name":name,"nlp":nlpDict,"subid":subid]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: cmdDict)
    let json = String(data: jsonData, encoding: .utf8)!
    print(json)
} catch { print("something went wrong", error) }


text:
Q: Why multiple JADE GUI appear on refreshing JSP page I want to run JADE middleware GUI from JSP, for that I created a "Dynamic Web Project" and made right click on WebContent folder and select New .. Other ..type JsP file and gave the name e.g. runJADE.jsp. Now add the following details inside runJADE.jsp
<%@ page import="jade.core.*"%>
<% try {
    String [] _args = {"-gui"};
    jade.Boot.main(_args);
   } catch (Exception ex) {
       out.println(ex);
       ex.printStackTrace();
   }
 %>

<HTML>
<BODY>
JADE is running.
</BODY>
</HTML>

I also tried the following code in JSP page:
<%@ page import="jade.core.Profile,jade.core.ProfileImpl,jade.core.Runtime,jade.wrapper.AgentContainer %>
<% try {
        Profile profile = new ProfileImpl();
        profile.setParameter(Profile.GUI, "true");
        AgentContainer mainContainer = Runtime.instance().createMainContainer(profile);
   } catch (Exception ex) {
       out.println(ex);
       ex.printStackTrace();
   }
 %>

<HTML>
<BODY>
JADE is running.
</BODY>
</HTML>

The code gives fine result by launching the JADE but refreshing the page leads to create another GUI. Am I missing some basic step? and how to avoid this problem?

A: Your approach is deeply flawed. Every time you load your JSP, it creates another Jade container. When using Jade, you generally only want to have a single container on a single machine.
A better approach would be to start up your container when your entire application starts up. Then, when you want to trigger the Jade GUI, you should just start the RMA agent inside your Jade container, as described in this answer: https://stackoverflow.com/a/20462656/2047962

Now, let's take a step back and talk about your code. I would strongly recommend that you stop using scriptlets in your JSPs RIGHT NOW. It's a bad practice that leads to really poor designs. If you don't know the alternatives, please read "How to avoid Java code in JSP files?".
Second, why are you mixing web applications and desktop Swing UIs? Why are you opening a Swing GUI when someone accesses your web page in a browser? If you were to deploy that application, your clients would get to a page that says "JADE is running", but they wouldn't see anything. The GUI would open on the server, not the client. I can't see why you would want this functionality in a web environment.


text:
Q: what is the used of $\{x:f(x) \ge r\}$ in the given answer? Prove that if $f$ is a real function on a measurable space $X$ such that $\{x:f(x) \ge r\}$ is measurable for every rational $r$, then $f$ is measurable.
My attempt : I got the answer here
I have some confusion in the given answer below

My confusion : what is the  used of $\{x:f(x) \ge r\}$ in the given answer ?
My thinking: There is no relation between the $\{x:f(x) \ge r\}$ and the given above answer .Then how can i claim that this  answer is correct .
I think given answer  is not match with given question


text:
Q: Probability query 8 Indians and 3 Americans are to stand in a row at random. What is the probability that no 2 Americans are always together?
I think the answer should be 1 because as there are many possible configurations, 2 Americans can never be "always" together.
However, a solution by a person online says the following :

so lets see.. it's given indians and americans so i'm assuming that implies every person is unique.
Our sample space would be $11! = 39916800$
Counting the unfavorable conditions (A-american I-indian)
situation like this
AAI(remaining in any order)
AAA(remaining in any order)
AAI......
The number of ways to achieve this would be
$3C2 *2* 8C1 * 8!$
which is choosing $2$ americans from $3$ which would be $3C2*2$ and choosing $1$ indian from $8$ >which would be 8C1 and then the remaining people in any order which would be 8!
AAA......
The number of ways to achieve this would be
$3! * 8!$
So this would sum up to $2177280$
So the probability of this would be $2177280/39916800 = 0.0545$
So the probability of no $2$ americans being together would be $ 1 - 0.0545 = 0.9455$
so $94.55%$

Which one is the right answer?

A:
8 Indians and 3 Americans are to stand in a row at random. What is the probability that no 2 Americans are always together?

This is simply badly phrased.  Clearly you're after the proportion of all ways to arrange the row which do not place 2 Americans adjacent.

My Approach
An equivalent problem is: How many ways can you put 8 balls into 4 boxes such that there is at least one ball in each of the middle two boxes?  (The two end boxes can be empty.)
Where the 'balls' are Indians, and the 'boxes' are spaces between Americans.  The order of individuals within the places doesn't matter.
This is a 'stars and bars' problem.  There are ${n+k-1\choose k-1}$ ways to arrange $n$ objects into $k$ bins such that any bin may be empty.  We require $n=6$ (because 2 of the 'balls' must be in the center bins, and we wish to count ways to arrange the other 6), and $k=4$.
This is: ${9\choose 3}$ ways to arrange places.
Now there are ${11\choose 3,8}$ ways to arrange the places in total.
$$\begin{align}
\Pr(\text{answer})& =\frac{9!\,8!}{6!\,11!}
\\[1ex] & = 0.5\dot{\overline{09}}
\end{align}$$

Your friend's approach

Our sample space would be 11!=39916800

The sample space is $11!/8!3!$, as we're only interested in arrangements of places, not individuals.

Counting the unfavorable conditions (A-american I-indian) situation like this AAI(remaining in any order) AAA(remaining in any order)

No, you don't want that.  The first of these includes cases such as I...IAAAI...I, and does not include cases like I...IAI...IAA.  The count will be off.
What you need to count is permutations of 8 I, 1 A and 1 AA, and then discount permutations of 8 I and 1 AAA.  (Principle of Inclusion and Exclusion: count the ways at least one pair of Americans are adjacent, less ways all three are co-adjacent.)
$$\begin{align}
\Pr(\text{answer}) & = 1 - \frac{{10\choose 8,1,1}-{9\choose 8,1}}{11\choose 8, 3}
\\[1ex] & = 1 - \frac{\frac{10!}{8!\,1!\,1!}-\frac{9!}{8!\,1!}}{\frac{11!}{8!\,3!}}
\\[1ex] & = \frac{11!-(10!-9!)3!}{11!}
\\[1ex] & = 0.5\dot{\overline{09}}
\end{align}$$

A: For the case $AAA$ we have: $9\cdot 8!$ choices of seating.
For the case $AA$ we have:  $ 8\cdot 7\cdot 8! + 2\cdot 8\cdot 8!$ choices of seating.
And there are a total of $11!$ choices of seating available. Thus $P(\text{no 2 A together}) = 1 - \dfrac{9\cdot 8! + 8\cdot 7\cdot 8! + 2\cdot 8\cdot 8!}{11!}$


text:
Q: How to convert string column type to integer using Laravel migration? I am trying to alter the column datatype using Laravel migration. But I am facing following error. Please help me out.
Schema::table('files', function(Blueprint $table) {
    $table->integer('app_id')->change();
    $table->index(['app_id', 'filename']);
});

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CHARACTER SET utf8 DEFAULT 0 NOT NULL COLLATE utf8_unicode_ci' at line 1 (SQL: ALTER TABLE files CHANGE app_id app_id INT CHARACTER SET utf8 DEFAULT 0 NOT NULL COLLATE utf8_unicode_ci)

A: As a alternative solution to https://github.com/doctrine/dbal/issues/3714 that is downgrading the doctrine/dbal package u can do:
Schema::table('member_section', function (Blueprint $table) {
    $table->bigInteger('type')->charset(null)->collation(null)->change();
});

A: Your issue is most likely caused by a bug in the most recent version of the doctrine/dbal package. The issue was introduced with v2.10.0.
You can always downgrade the package in your composer.json to v2.9.3 it should work just fine.
See the offical issue here:  https://github.com/doctrine/dbal/issues/3714


text:
Q: How to extract rows that meet conditions in one column but sorted on another? I am writing an R code that selects top 2 movies for each user, among this 10, maximum of 1 are sponsored movies. The data is sorted based on user rating as follow:
user   movie  rating  sponsored
10     m23    3.4     1
2      m5     3.3     0
6      m74    3.3     1
10     m3     3.2     0
6      m2     3.1     0
10     m54    3.0     1
6      m13    2.8     0
2      m74    2.6     1
2      m12    2.5     0

Now since I have to sort based on rating in general, not withing each user, I was wondering how I hold variables like the number of movies within each user(K = 2) and max number of sponsored movies(S = 1) for each user? Should I create different tables for each user with their 2 movies? And if yes, how? The following is basically my algorithm:
n: number of users
m: number of movies

for(i in 1:nm){
    if(K_u_i < 2 && S_u_i <= 1)
    add that movie to top 2 list of that user
}

Please let me know if any further clarification is needed.
Thank you

A: I'm not claiming that this is the only way, or a very elegant way, but this should work (hard to know without being able to test against a slightly larger dataset, though). Basic approach: First, create a subset containing only sponsored films, cutting them out of the original data. Cut the subset to the top film per user. Append that back to dataset of non-sponsored films. Now take the top 2 films for each user from the appended dataset.
> dat<- data.frame(user = c(10, 2, 6, 10, 6, 10, 6, 2, 2),
+                  movie = c('m23', 'm5', 'm74', 'm3', 'm2', 'm54', 'm13', 'm74', 'm12'),
+                  rating = c(3.4, 3.3, 3.3, 3.2, 3.1, 3.0, 2.8, 2.6, 2.5),
+                  sponsored = c(1, 0, 1, 0, 0, 1, 0, 1, 0))
>
> spons <- subset(dat, sponsored == 1)
> non_spons <- subset(dat, sponsored == 0)
>
> spons <- spons[order(spons$user, spons$rating, decreasing = TRUE), ]
>   spons <- spons %>% group_by(user) %>% slice(1) %>%
+   ungroup()
>
> new_dat <- rbind(spons, non_spons)
>
> new_dat <- new_dat[order(new_dat$user, new_dat$rating, decreasing = TRUE), ]
> new_dat <- new_dat %>% group_by(user) %>% slice(1:2) %>%
+   ungroup()
> new_dat <- new_dat %>% group_by(user) %>% slice(1:2) %>%
+   ungroup() %>% print()
# A tibble: 6 x 4
   user movie rating sponsored
  <dbl> <fct>  <dbl>     <dbl>
1     2 m5       3.3         0
2     2 m74      2.6         1
3     6 m74      3.3         1
4     6 m2       3.1         0
5    10 m23      3.4         1
6    10 m3       3.2         0

Edit: the code I provided did not work, partly because I tried using dplyr without a lot of experience with that package. This is a hackier solution, but it works with the data provided.


text:
Q: C# 8.0 using Range for multidimensional arrays In C# 8.0, why can I use range on single dimensional arrays:
var oneDim = new int[5];
var oneDimSlice = oneDim[2..4];

But can not use it on multi dimensional arrays ?
var twoDim = new int[5, 5];
var twoDimSlice = twoDim[2..4, 2..4];

A: https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/ranges-indexes

Array has more nuanced behavior. Single dimension arrays support both
  indices and ranges. Multi-dimensional arrays don't. The indexer for a
  multi-dimensional array has multiple parameters, not a single
  parameter. Jagged arrays, also referred to as an array of arrays,
  support both ranges and indexers.

so the answer is no, but it is possible to do it with jagged arrays if you are interested.


text:
Q: Second background service does not start I defined two background services for my app. But only one of the, the AttachService starts. In LogCat I can see the starting log messages of the attachService but nothing from the PenManagerService. I defined for each service a startup receiver
public class StartupCompletedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, PenManagerService.class);
        context.startService(service);

    }

}

public class AttachmentStartupReceiver extends BroadcastReceiver {

    private static final String TAG = AttachmentStartupReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive");

        Intent attachSvc = new Intent(context, AttachService.class);
        context.startService(attachSvc);

    }

}

Here the definition of the two services in the manifest
   <service
        android:name="de.android.services.PenManagerService"
        android:process=":PenManagerService" >
    </service>

    <service
        android:name="de.android.services.AttachService"
        android:icon="@drawable/loading_icon"
        android:label="@string/attachServiceName"
        android:process=":attachServiceBackground" />

    <receiver
        android:name="de.android.services.StartupCompletedReceiver"
        android:process=":PenManagerService" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <receiver
        android:name="de.android.AttachmentStartupReceiver"
        android:process=":attachServiceBackground" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

Both services extends the IntentService and in their onCreate I have a log message, but only the one from the attachService shows up in the log.


text:
Q: gulp nodemon doesn't work Here is my gulpfile.js:
var gulp = require('gulp'),
  nodemon = require('gulp-nodemon'),
  plumber = require('gulp-plumber'),
  livereload = require('gulp-livereload');

gulp.task('develop', function () {
  livereload.listen();
  nodemon({
    script: 'app.js',
    ext: 'js ejs html coffee'
  }).on('restart',function() {
    console.log('Livereload reload...');
    livereload.reload();
  });
});

gulp.task('default', [
  'develop'
]);

My app.js:
var express = require('express');

var app = express();

app.set('view engine','ejs');

app.get('/', function(req,res){
   res.send('Hello world!');
});

app.listen(8888, function() {
  console.log('Server started at 8888');
});

When I change 'Hello world!' to 'Hello world!!!!!', I can see the following in my console:

It did logged my changes. But the page is not reloaded at all. I have to refresh my browser to see the change. Anything wrong in my gulpfile.js? Any idea? Thanks.

A: I see that the question is pretty old but, anyway, livereload will only work if your browser supports it. For example, for Chrome you need to install an extension called LiveReload. This will enable refreshing the page for you (don't forget to enable it).
Another option is to use BrowserSync. It doesn't actually need anything else besides the plugin (no browser extensions) which you can use in your gulp task. This is an example (taken from here):
var gulp = require('gulp');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');
var BROWSER_SYNC_RELOAD_DELAY = 500;

gulp.task('nodemon', function (cb) {
var called = false;
  return nodemon({
    // nodemon our expressjs server
    script: 'app.js',

    // watch core server file(s) that require server restart on change
    watch: ['app.js']
  })
    .on('start', function onStart() {
      // ensure start only got called once
      if (!called) { cb(); }
      called = true;
    })
    .on('restart', function onRestart() {
      // reload connected browsers after a slight delay
      setTimeout(function reload() {
        browserSync.reload({
          stream: false
        });
      }, BROWSER_SYNC_RELOAD_DELAY);
    });
});

gulp.task('browser-sync', ['nodemon'], function () {

  // for more browser-sync config options: http://www.browsersync.io/docs/options/
  browserSync({

    // informs browser-sync to proxy our expressjs app which would run at the following location
    proxy: 'http://localhost:3000',

    // informs browser-sync to use the following port for the proxied app
    // notice that the default port is 3000, which would clash with our expressjs
    port: 4000,

    // open the proxied app in chrome
    browser: ['google-chrome']
  });
});

A: Everything is alright with your nodemon installation. You actually have to refresh your browser to see the changes you made.
If you want to have that done for you, check out guard-livereload at this website.


text:
Q: How do I copy from Javascript variable to Clipboard I was trying to copy my JavaScript variable to my clipboard in Chrome. I found a lot of information on the web but none of the results were exactly what I needed.
The answer ended up being pretty simple. Though, I'm unsure if all this is needed.
document.body.appendChild(element);
element.value = "foo";
element.select();
document.execCommand('copy', element.value); <--- solution
document.body.removeChild(element);

I was also unable to find documentation that mentions the ability to pass a value parameter to the execCommand copy function and actually guessed its existence. Other examples used .focus and .select methods instead, hence the element.select(). Those did not work for me. Adding the parameter to the execCommand function seemed to fix the problem.
So my question is how can this snippet be improved? Does that additional parameter have to be an html element?

A: Try the code below:
var text = "text";
function copyVar(text) {
    var textElement = document.createElement('textarea');
    textElement.value = text;
    textElement.setAttribute('readonly', '');
    document.body.appendChild(textElement);
    textElement.select();
    document.execCommand('copy');
    document.body.removeChild(textElement);
}


text:
Q: Div in LI causes extra row before content If I have the following HTML. Why does the content of the li drop down a line?
I am looking for an explanation of the behaviour and how to fix

                            Left Text

                            Right Text

left	right

A: The DIV's are set as display: block by default, therefore it does not stay in the same line as the LI..
If you set it as display: inline; it will force it to stay in the same line

                                Left Text

                                Right Text

Edit:
as Billy said there is an issue with the floats, but changing them to inline-block adds another issue, the margin look at this explanation
Adding a SPAN instead of a div won't solve the issue, because the difference is that the SPAN is display: inline; by default, (the same as we have now with the DIV)

Left Text

Right Text


text:
Q: add border to pdf page using itext this is my source code. why am I not able to add border to my pdf page even after enabling borders for all sides? I've set border and its color too still I'm not able to add border.
void create() throws DocumentException,IOException{
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.setPageSize(PageSize.LETTER);
        document.setMargins(36, 72, 108, 180);
        document.setMarginMirroring(false);
        // step 3
        document.open();
        // step 4
        Rectangle rect= new Rectangle(36,108);
        rect.enableBorderSide(1);
        rect.enableBorderSide(2);
        rect.enableBorderSide(4);
        rect.enableBorderSide(8);
        rect.setBorder(2);
        rect.setBorderColor(BaseColor.BLACK);
        document.add(rect);
         Font font = new Font(Font.FontFamily.TIMES_ROMAN, 26, Font.UNDERLINE, BaseColor.BLACK);
        Paragraph title= new Paragraph("CURRICULUM VITAE\n\n",font);
        title.setAlignment(Element.ALIGN_CENTER);
        document.add(title);
        Font f1= new Font (Font.FontFamily.UNDEFINED, 13, Font.NORMAL, BaseColor.BLACK);
        Paragraph info= new Paragraph("Name\n\nEmail\n\nContact Number",f1);
        Paragraph addr= new Paragraph("Street\n\nCity\n\nPin",f1);
        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.spacingAfter();
        PdfPCell cell = new PdfPCell(info);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.disableBorderSide(Rectangle.BOX);
        cell.setExtraParagraphSpace(1.5f);
        table.addCell(cell);
        cell = new PdfPCell(addr);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.disableBorderSide(Rectangle.BOX);
        cell.setExtraParagraphSpace(1.5f);
        table.addCell(cell);
        document.add(table);
        document.add(new Chunk("\n"));
        document.add(new LineSeparator(2f,100,BaseColor.DARK_GRAY,Element.ALIGN_CENTER,-1f));

A: *

*You didn't define a border width.

*You're adding the border only once. What if you want the border to appear on every page?

You can fix (1.) by adding:
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(2);

Note that I would remove the enableBorderSide() calls. You'll notice that you've used the setBorder() method in the wrong way.
To fix (2.), I would use a page event. Note that you can't use document.add() in a page event, so you'll have to do something as described in the DrawRectangle example that was written in answer to the question iText: PdfContentByte.rectangle(Rectangle) does not behave as expected
You didn't define a page size when creating the Document object, which means that iText will be using PageSize.A4. A couple of lines later, you use PageSize.LETTER. These values are immutable Rectangle objects. You can create a new Rectangle using the dimensions/coordinates of PageSize.A4 (or in your case: PageSize.LETTER). You can obtain the dimensions using the getWidth() and getHeight() method and the coordinates using getLeft(), getBottom(), getRight() and getTop().

A:     Rectangle rect= new Rectangle(577,825,18,15); // you can resize rectangle
     rect.enableBorderSide(1);
     rect.enableBorderSide(2);
     rect.enableBorderSide(4);
     rect.enableBorderSide(8);
     rect.setBorderColor(BaseColor.BLACK);
     rect.setBorderWidth(1);
     document.add(rect);


text:
Q: .htaccess redirect subdomain to root domain Maybe I just don't know how to ask the question to find the answer but what I want to do is an .htaccess redirect from an old URl, shop.nilandsplace.com/camp to nilandsplace.com/store/camping. Not to make it more difficult, but I would like to know what it is that I am doing so I can learn this

A: Try this:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^shop.nilandsplace.com$
RewriteRule ^camp(.*)$ http://nilandsplace.com/store/camping$1 [R=301,L]

The top line turns on the rewrite engine. We need to do this before rewriting any URLs.
The second line checks that we're visiting the shop.nilandsplace.com domain.
The third line redirects any requests from /camp to http://nilandsplace.com/store/camping. The bit in brackets at the end of the third line tells Apache to make this a 301 redirect (so search engines know the page has moved), and to do the redirect straight away, bypassing any upcoming rewrite rules for this request.
The code will also redirect subdirectories of camp (anything after camp), for example shop.nilandsplace.com/camp/tent-poles > nilandsplace.com/store/camping/tent-poles.
You can learn more about the mod_rewrite module (which powers the rewrite engine) on the Apache Docs.


text:
Q: prometheus filter range vector by day_of_week I use sub-queries to get hourly aggregated values for the last week for example: The number of http requests per hour over the whole last week, which will return 168 values in a range vector.
delta(http_server_requests_seconds_count[1h])[1w:1h]

Now I want to filter the value to return only the ones which are for a specific week day, lets say return only the 24 value from Monday.
I found some hints about day_of_week, timestamp, bool expr, but I cannot combine them to get it working or maybe it is not possible? Something like:
delta(http_server_requests_seconds_count[1h])[1w:1h] bool day_of_week() == 1

A: It'd be more effficient to adjust your start/end time to only over the day, but you could do:
(increase(http_server_requests_seconds_count[1h]) and on () day_of_week() == 1)[1w:1h]


text:
Q: XACML condition comparing subject attribute and resource attribute, not hard coded I am working on a policy in XACML where a subject with security classification and category, should be compared with an object's classification and category.
The request could be:

*

*Subject:

*

*classification: Secret,

*category: Nato, EU.

*Resource:

*

*classification: Secret,

*category: Nato.

This should be permit.
If the resource has higher classification than the subject, or the subject don't have the correct category, the result should be denied. So, I need to somehow rank the classifications (with the function in-bag?) to see if the subject has the correct ones. I also need to compare the subject's and the object's one or more categories to each other.
I can only make it work hard-coded with the classifications, and the similar questions I have seen on this site uses xacml 3.0 and alfa. I have not been able to code the category part. This is my condition in the policy for hard-coded attributes.
    <Condition FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-one-and-only">
                    <SubjectAttributeDesignator
                          AttributeId="classification"
                          DataType="http://www.w3.org/2001/XMLSchema#string"/>
                </Apply>
            <AttributeValue
                DataType="http://www.w3.org/2001/XMLSchema#string">top-secret</AttributeValue>
            </Apply>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-one-and-only">
                    <ResourceAttributeDesignator
                          AttributeId="resclassification"
                          DataType="http://www.w3.org/2001/XMLSchema#string"/>
                </Apply>
            <AttributeValue
                DataType="http://www.w3.org/2001/XMLSchema#string">top-secret</AttributeValue>
            </Apply>
        </Condition>

Any help?
This code works with hard-coded attributes.
               <!-- Hard-coded condition check -->
        <Condition FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-greater-than-or-equal">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-one-and-only">
                    <SubjectAttributeDesignator
                        AttributeId="classification"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                </Apply>
            <AttributeValue
                DataType="http://www.w3.org/2001/XMLSchema#string">3.0 top-secret</AttributeValue>
            </Apply>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-one-and-only">
                    <ResourceAttributeDesignator
                        AttributeId="resclassification"
                        DataType="http://www.w3.org/2001/XMLSchema#string"/>
                </Apply>
            <AttributeValue
                DataType="http://www.w3.org/2001/XMLSchema#string">3.0 top-secret</AttributeValue>
            </Apply>
        </Condition>

A: To solve the problem you have to define attributes as follows:
SubjectClassificationRank (Data Type: integer),
SubjectAccessCategory     (Data Type: string),
ResourceClassificationRank (Data Type: integer),
ResourceCategory           (Data Type: string)
The XACML 2.0 code for your whole condition is as follows:
<Condition>
  <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-greater-than-or-equal">
      <SubjectAttributeDesignator SubjectCategory="urn:oasis:names:tc:xacml:1.0:subjectcategory:accesssubject" AttributeId="SubjectClassificationRank" DataType="http://www.w3.org/2001/XMLSchema#integer" MustBePresent="false"></SubjectAttributeDesignator>
      <ResourceAttributeDesignator AttributeId="ResourceClassificationRank" DataType="http://www.w3.org/2001/XMLSchema#integer" MustBePresent="false"></ResourceAttributeDesignator>
    </Apply>
    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:all-of-any">
      <Function FunctionId="urn:oasis:names:tc:xacml:2.0:function:integer-greater-than"></Function>
      <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
        <ResourceAttributeDesignator AttributeId="ResourceCategory" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></ResourceAttributeDesignator>
      </Apply>
      <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
        <SubjectAttributeDesignator SubjectCategory="urn:oasis:names:tc:xacml:1.0:subjectcategory:accesssubject" AttributeId="SubjectAccessCategory" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></SubjectAttributeDesignator>
      </Apply>
    </Apply>
  </Apply>
</Condition>

Explanation :
first it applies a greater than function between Subject's Rank and Resource's rank and get the boolean "result-1".part of this as follows:
  <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-greater-than-or-equal">
          <SubjectAttributeDesignator SubjectCategory="urn:oasis:names:tc:xacml:1.0:subjectcategory:accesssubject" AttributeId="SubjectClassificationRank" DataType="http://www.w3.org/2001/XMLSchema#integer" MustBePresent="false"></SubjectAttributeDesignator>
          <ResourceAttributeDesignator AttributeId="ResourceClassificationRank" DataType="http://www.w3.org/2001/XMLSchema#integer" MustBePresent="false"></ResourceAttributeDesignator>
        </Apply>

Separately it makes one bag out of SubjectAccessCategory list and other bag out of ResourceCategory list.Then compare to return true if the each element first bag(ResourceCategory List) contains in second bag(SubjcetAccessCategory) else false which is "result2".
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:all-of-any">
  <Function FunctionId="urn:oasis:names:tc:xacml:2.0:function:integer-greater-than"></Function>
  <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
    <ResourceAttributeDesignator AttributeId="ResourceCategory" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></ResourceAttributeDesignator>
  </Apply>
  <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
    <SubjectAttributeDesignator SubjectCategory="urn:oasis:names:tc:xacml:1.0:subjectcategory:accesssubject" AttributeId="SubjectAccessCategory" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></SubjectAttributeDesignator>
  </Apply>
</Apply>

Then finally combines both "result1" and "result2" with "And" function.