text:
Q: Model Binding Object properties gets NULL on passing while Redirecting to another Action Method I am trying to learn binding a complex object in My MVC application. Below is my Class
public class StrongUser
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public Country myCountry { get; set; }
    public List<Country> CountryList { get; set; }
    public StrongUser()
    {
        firstName = "Naveen";
        lastName = "Verma";
        myCountry = Country.ListOfCountries()[0];
        CountryList = Country.ListOfCountries();
    }

    public static StringBuilder Print(StrongUser user2)
    {
        StringBuilder sr = new StringBuilder();
        sr.AppendLine("First Name=" + user2.firstName);
        sr.AppendLine("
");
        sr.AppendLine("Last Name=" + user2.lastName);
        sr.AppendLine("
");
        sr.AppendLine("My Country Name=" + user2.myCountry.Name);
        sr.AppendLine("
");
        sr.AppendLine("My Country Continent=" + user2.myCountry.Continent);
        sr.AppendLine("
");
        sr.AppendLine("My Country List:");
        sr.AppendLine("
");
        foreach (Country c in user2.CountryList)
        {
            sr.AppendLine("
");
            sr.AppendLine("Name=" + c.Name);
            sr.AppendLine("
");
            sr.AppendLine("Continent=" + c.Continent);
        }
        return sr;
    }
}

public class Country
{ public int Id { get; set; }
  public string Name { get; set; }
  public string Continent { get; set; }

    public static List<Country> ListOfCountries()
    {
        return new List<Country>()
        {
            new Country(){Id=1, Name ="India",Continent="Asia"},
            new Country(){Id=2,Name="USA",Continent="North America"},
            new Country(){Id=3,Name="Japan",Continent="Asia"},
            new Country(){Id=4,Name="UK",Continent="Asia-Pacific"},
            new Country(){Id=5,Name="Australia",Continent="Australia"},
            new Country(){Id=6,Name="China",Continent="Asia"}

        };
    }

}

I am using the following controller
    [HttpGet]
     public ActionResult EditBindCheck()
    {
        return View(new StrongUser());
    }

    [HttpPost]
    public ActionResult EditBindCheck(StrongUser user)
    {
//here all the values are properly binded to **user** object

        return RedirectToAction("PrintStrongUser", user);
    }

    public StringBuilder PrintStrongUser(StrongUser user2)
    {

        return StrongUser.Print(user2);
    }

On posting form in EditBindCheck method all the Values are properly binded to user object.
But On Passing to  PrintStrongUser, user2.firstName and user2.lastName are same as in user object , but user2.myCountry  and user2.CountryList are NULL
I dont understand why the object has changed its values on passing to another ActionMethod??


text:
Q: PHP XML duplicate nodes need help summing up the values foreach loop Apologies up front PHP is not my native programming language.
I have a file that is consuming an XML object and spins through it and sets values so it can update a table.
The file has been changed and there are now two nodes with the same name 'pac'.
I have a foreach loop that sets the values to the final object variable. and I need to add another foreach loop inside that (or maybe I don't PHP people may know better ways to handle incrimental sums on duped nodes in XML).
PHP code:
function parseSingleLineFile($singleFilePath,$bundlename)
{
    $xmlobject = simplexml_load_file($singleFilePath);
    $finalObject;
    $finalObject->timestamp = $xmlobject->Info->Created;

    global $LAST_TIMESTAMP;
    if($finalObject->timestamp != 0) $LAST_TIMESTAMP = $finalObject->timestamp;

    foreach($xmlobject->MeanPublic as $logItem)
    {
        $psplit = split(":",$logItem->Key);
        $parametername = strtolower($psplit[sizeof($psplit)-1]);

        switch($parametername)
        {
            case "exlbnmb":
                $finalObject->exlsolirr = $logItem->Mean;
                break;
            case "solacp":
                $finalObject->intsolirr = $logItem->Mean;
                break;
            case "smaa":
                $finalObject->sma_h_on = $logItem->Mean;
                break;
            case "pac": /* here is the problem spot (there are now two of these...*/
                $finalObject->pac = $logItem->Mean;
                break;
        }
    }
}

I need to add the two mean values and set to the finalObject pac key variable:
Here was my best attempt but I could not test it in production and I cannot recreate this outside of the product system so I so I am not sure I'm right track. I doin't want to risk breaking this at this point of the file's work.
My best guess at getting the mean value for each node:
case "pac":
$pacbuilder ='0';
foreach($parametername = pac) {
    $pacbuilder += $logItem->Mean;
}
$finalObject->pac = $pacbuilder;
break;

I also want to note that it is grabbing the last pac value and skips the first instance/node.
The finalObject is used to populate a table...
if($totalRows_checkForLine == 0)
{
    $query_insertLine = sprintf("INSERT INTO mean_data_table SET
                                d_exlsolirr = '%s',
                                d_intsolirr = '%s',
                                d_sma_h_on = '%s',
                                d_pac = '%s'
                                ",
                                $finalObject->exlsolirr,
                                $finalObject->intsolirr,
                                $finalObject->sma_h_on,
                                $finalObject->pac);
    $insertLine = mysql_query($query_insertLine) or die(mysql_error());
}

A: The questioner want the sum of node values when "pac"  >= 2 occurrences and add/to increment to "$finalObject->pac", like this:
switch($parametername) {
   //....
    case "pac":
        $finalObject->pac = (float)$finalObject->pac + (float)$logItem->Mean;
        break;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get All attachments of gmail compose box using inboxsdk I am creating a chrome addon for Gmail email tracker. For which I am using InboxSDK, I want to get all attachments from current Gmail compose body and I am using the following code.
composeView.addButton({
    .....
    onClick: function (event) {
       var cv = event.composeView;
       var mail_body = cv.getHTMLContent();
    });
});

As I am new to Chrome addon development as well as InboxSDK, I don't know how to get attachments from mail_body. Please, can anyone help me?
Thanks in advance.

A: Try input[name="attach"] + a as a selector to fetch all the composes attachments links.
From there you can go up in the DOM tree to get the root element for each attachment and do whatever you wanna do.
you could use document.querySelectorAll('input[name="attach"] + a'); for example. But that would return all the attachments links in all open compose views.
Here is an example with jquery, which then would just get the links from the given compose view.
composeView.addButton({
    .....
    onClick: function (event) {
       var cv = event.composeView;
       var mail_body = cv.getHTMLContent();
       var attachment_links = $(mail_body).find('input[name="attach"] + a');
    });
});


text:
Q: Kendo angularjs tree view, prevent parent node check by its default Hi am using Kendo treeview with Angularjs, i have tree view with checkbox in below hierarchy
Parent1
  Child1
  Child2
I need like this,
Scenario 1:
if user select Parent1-> Child1, Child2 needs to check automatically. This is working fine
Scenario 2:
if user select Child1, Child2->Parent1 should not be automatically. i want to prevent parent checked by default, how to do this?

A: The only option available is checkChildren that triggers this behavior.
Setting it this to false:
$("#treeview").kendoTreeView({
  checkboxes: {
    checkChildren: false
  }
});

will disable Scenario 2 in this case you will no longer have available the scenario 1.
What you can do is create a small recursive function that goes through all children and check them whenever the parent is clicked.


text:
Q: PropertyPlaceholderConfigurer in Spring MVC I use Spring MVC in my project, I define the details in web.xml like this :
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath*:/applicationContext.xml,
            classpath*:/applicationContext-security.xml
        </param-value>
    </context-param>

<servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:/applicationContext-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

I also define a external properties file, I want use the details in the properties file, so I define a PropertyPlaceholderConfigurer bean in applicationContext.xml like this :
<context:property-placeholder location="classpath*:/system.properties" ignore-resource-not-found="true" ignore-unresolvable="true" />

but when i run my project, I find that I can't use the properties file details in applicationContext-mvc.xml , when I also put the
<context:property-placeholder location="classpath*:/system.properties" ignore-resource-not-found="true" ignore-unresolvable="true" />

in my applicationContext-mvc.xml, it works well。 That is say I must define PropertyPlaceholderConfigurer  bean in all Spring configuration xml file, it is right?
I do not understand, the ContextLoaderListener create the root web application context, the DispatcherServlet create the servlet-specifical web application context,
the hierarchy in Spring MVC like this:

it didn't say that I could use the bean extends from root web application context in Spring MVC configuration file?
I don't know why, whether I must define PropertyPlaceholderConfigurer in all Spring configuration file?


text:
Q: show and hide tabs dynamically in touch ui -AEM I have a requirement, where I need to show few tabs on selection of a value from a drop down.
I have done this in classic UI. But not sure how to proceed for Touch UI. I know that we can use JQuery, Can anyone let me know the approach I can use.

A: Its fairly simple, look at the OOTB List Component /libs/foundation/components/list. The selection dropdown is defined -  /libs/foundation/components/list/cq:dialog/content/items/column/items/listFrom, look at property class and cq-dialog-dropdown-showhide-target these are used to manage hide and show.
Now from here look at the dropdown values under - /libs/foundation/components/list/cq:dialog/content/items/column/items/listFrom/items these values trigger the hide and show mapping to property showhidetargetvalue as in /libs/foundation/components/list/cq:dialog/content/items/column/items/setDescendants


text:
Q: How to programmatically define a global function within a function or method? For example,
def makeFunction name
    ... #define a function with the name supplied
end

makeFunction 'functionMade'
functionMade

I know it's possible to make a global variable $functionMade through lambda or proc, but is it possible to make it really a function without the $ prefix?

A: i think via class_eval on Kernel:
Kernel.class_eval <<-RUBY
  def abc
    puts 'abc'
  end
RUBY

but i wouldn't recommend that. what do you need it for, or are you just curious?


text:
Q: Severity: Notice Message: Undefined variable: questions Filename: views/quiz.php  **view**

    <?php foreach($questions as $row){ ?>

    <?php $ans_array = array($row->choice1,$row->choice2,$row->choice3,$row->answer);
    shuffle($ans_array);?>

<?=$row->quizID?>.<?=$row->question?>

    <input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[0]?>"> <?=$ans_array[0]?>

    <input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[1]?>"> <?=$ans_array[1]?>

    <input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[2]?>"> <?=$ans_array[2]?>

    <input type="radio" name="quizid<?=$row->quizID?>" value="<?=$ans_array[3]?>"> <?=$ans_array[3]?>

    <?php } ?>

controller
public function quest ()
    {
    $this->Model_students;
    $this->data['questions']=$this->Model_students->quest();
    $this->load->view('quest',$this->data);
    }

    public function quiz ()
    {

    $this->load->view('quiz');
    }

model
public function quest()
    {
     $this->db->select("quizID,question,choice1,choice2,choice3,answer");
     $this->db->from("quiz");

     $query = $this->db->get();

     return $query->result();

     $num_data_returned = $query->num_rows;

     if ($num_data_returned < 1)
     {
       echo "there is no data in the db";
       exit();
     }

    }

after submitting this i get 2 errors;
1. Severity: Notice
Message: Undefined variable: questions
Filename: views/quiz.php
Line Number: 14
2.everity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/quiz.php
Line Number: 14

A: Remove $this
$data['questions']=$this->Model_students->quest();
$this->load->view('quest',$data);


text:
Q: Modeling multiple relationship ERD and SQL I am new in databases and I have to model a relationship between two entity sets: Bookings and Users. I created two relationhips between them (many-to-many and one-to-many) like

In SQL I created 3 tables: Booking, Users and junction table Booking_Users like i

In short what I want to achieve: one user can make multiple bookings. One booking can be for several people and they are added to Users table. Each user can be associated with several booking. I have to store an information about who is responsible for a booking (there is a foreign key User_id in Bookings table) and to which booking users are assigned (this information is stored in junction table).
My question is, is it a good way to model such a relationship?

A: That's ok.  The weakness there is that it doesn't enforce a rule that the "Primary user" is one of the "booking users".  You can enforce that by making the Foreign Key from Booking to Booking_User(BookingId,UserId), but that complicates the DML a bit as you can't set the primary user until you've added the Booking_user.
The common alternative design is to add an IsPrimary column to the Bookings_Users junction table.  But both designs are pretty common.


text:
Q: Java format xml using Transformer with CDATA part I want to format string to xml this my code:
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(4));
transformer.transform(xmlInput, xmlOutput);

This is my String
 <attr name="a1">this is a test</attr><attr name="a2"><![CDATA[this is a test inside cdata part]]></attr>

Output
<?xml version="1.0" encoding="UTF-8"?>

    <attr name="a1">this is a test</attr>
    <attr name="a2"><![CDATA[this is a test inside cdata part]]></attr>

desired
<?xml version="1.0" encoding="UTF-8"?>

    <attr name="a1">
        this is a test
    </attr>
    <attr name="a2">
        <![CDATA[this is a test inside cdata part]]>
    </attr>

I want each new tag will start in new line.

A: The precise effect of OutputKeys.INDENT is not defined in the specifications. The XSLT 2.0 version of the spec, however, is explicit that indentation must add whitespace only before a start tag or after an end tag - in other words, the value of a non-whitespace text node will never be changed.
Incidentally, it's also not defined in the spec that CDATA will be preserved in a JAXP identity transformation, and I'm slightly surprised that this happens.


text:
Q: should query inside must elasticsearch I am new to elasticsearch query DSL, I have documents in my ES index as below
{
    "doc_id":1,
    "city_id": 1,
    "name": "test1",
    "vvip": false
},
{
    "doc_id":2,
    "city_id": 1,
    "name": "test2",
    "vvip": false
},
{
    "doc_id":3,
    "city_id": 1,
    "name": "test3"
}
{
    "doc_id":4,
    "city_id": 1,
    "name": "test4"
}
{
    "doc_id":5,
    "city_id": 1,
    "name": "test5",
    "vvip": true
}
{
    "doc_id":6,
    "city_id": 1,
    "name": "test6",
    "vvip": true
}

For doc_id 3 and doc_id 4 vvip field does not exist
I want to form a query in such a way that these documents should always be returned if I query for vvip:true or vvip:false
Meaning for query city_id=1 and vvip=false
response will contain doc_id 1,2,3,4
for city_id=1 and vvip=true
response will contain doc_id 3,4,5,6
I tried below query but it did not help
{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "city_id": "1"
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "vvip"
                    }
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "city_id": "1"
                }
              },
              {
                "match": {
                  "vvip": false
                }
              }
            ]
          }
        }
      ]
    }
  }
}

A: You may simplify your query like this, which should work as you expect :
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "city_id": "1"
          }
        },
        {
          "bool": {
            "should": [
              {
                "match": {
                  "vvip": true
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "vvip"
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

The query mean you match city_id=1 AND (vvip=true OR vvip not exist).


text:
Q: Let's Encrypt: ClientID reqistered under application settings differs from what I entered? So I am trying to get Let's Encrypt working on Windows Azure through the web extension but I am getting a error that I cannot solve or find any information about.
I am following this tutorial on how to set ut Let's Encrypt on Azure:
https://github.com/sjkp/letsencrypt-siteextension/wiki/How-to-install#create-a-service-principal
When I use the extension wizard, fill in all the fields and press next this is the error I get:

My resourcegroup:

My serviceplan inside my resourcegroup (+ storage and app service):

My ClientID (application id):

My secret is also set, saved the value and pasted it into the wizard:

My connection strings are set (in the format mentioned in the tutorial/setup):

There is a webjob running, I did not create this, I think it was created by the wizard in some way(?):

And at last:

It seems to me that I have done everything the tutorial has asked me to do, I don't know why I get the error, I also don't understand the reference to "00000000-0000-0000-0000-000000000000". Does anyone know what I did wrong and how to solve this error?
Thanks in advance.

A: The checkbox "Update Application Settings" must be checked if you want to modify the settings from the Let's Encrypt extension's pages.

A: If you hate the idea of an azure webjob swallowing valuable system resources of your azure app service then there is now an alternative solution which uses Azure Automation;
https://www.powershellgallery.com/packages/GetSSL-LetsEncrypt
Documentation @ https://w.itpro.es/ssl-eng


text:
Q: Nivo slider loading problem I've strange Nivo Slider loading problem, the left side of the image shows how my slider looks just after entering the website (and this is WRONG) and right - after a while.
The question is why my images are loaded before containing div (with loading animation) and are shown one below another? Of course the main container has position set to relative and every container img is absolutely positioned at top: 0 and left: 0. Any ideas? Tried to put that on jsfiddle, but I believe Nivo isn't supported.

A:
How do I stop my images stacking down
  the page before the slider has loaded?
Due to the fact you have to use the
  $(window).load() function there is a
  delay before the plugin apply's
  certain styles to the elements. You
  can help this by manually applying the
  above CSS styles to stop the images
  stacking on the page before the plugin
  loads.

#slider {
    //See the "style-pack" for image
    background:url(images/loading.gif) no-repeat 50% 50%;
}
#slider img {
    display:none;
}

http://nivo.dev7studios.com/support/
Next time I'll start with FAQ ;/ Sorry. I hope this will help somebody in the future...

A: I had the same issue and was able to solve it with the following styles:
.nivo-slice {
    display:block;
    position:absolute;
    z-index:5;
    height:100%;
}
.nivo-box {
    display:block;
    position:absolute;
    z-index:5;
}

A: Just hide the overflow
.nivo-slice {
    display:block;
    position:absolute;
    z-index:5;
    height:100%;
    top:0;
}
.nivo-box {
    display:block;
    position:absolute;
    z-index:5;
    overflow:hidden;
}
.nivo-box img { display:block; }

A: You could try adding 'overflow:hidden' to the css for the container element.

A: My experience with using Nivo-Slider is when this happens, the nivo-slider.css is not linked correctly to the html page. Double check your links to your stylesheet.


text:
Q: Clifford Algebra and Gamma matrices: is this relation generally true for any dimension? I expect the following relation to be vanishing. But it seems not that obvious.
$\Gamma_{ab}^{\lambda}t^at^b \Gamma_{\lambda c(d)}t^c=0$
where $t^a$ are even ghosts, "$ab$" are indices for matrix element, and $\lambda$ denote different Gamma matrices. The Einstein summation convention is used above, i.e. we will sum over all indices except $d$.
I checked for both 3D and 4D Clifford algebra. The relation above seems to be right. But not sure whether it is generally true.
Does the following equation also vanishes?
$\Gamma_{\lambda a b}t^a t^b C^{\lambda} C^{\alpha}C^{\beta}=0$
where $C^{\lambda}$ are odd ghosts, i.e. $C^{\alpha}C^{\beta}=-C^{\beta}C^{\alpha}$.
The left hand side of the equation above is supposed to be something in $\wedge^2 V$, where $V=\{ C^{\lambda}|\lambda=1,2,\cdots,D \}$. $D$ is the dimension of the space.

A: It's not clear to me what you mean by "even ghosts".  Do you mean perhaps that $t^a t^b = t^b t^a$?
If so, then you will find that the identity is only valid in 3, 4, 6 and 10 dimensions and with lorentzian signature.  Indeed, this identity is essentially the condition for the vanishing of a fermionic trilinear which appears in the supersymmetric variation of Yang-Mills coupled minimally to an adjoint fermion, which in turn is the obstruction to the existence of "pure" supersymmetric Yang-Mills.
It is no accident that those dimensions are 2 plus the dimensions of the real division algebras: $\mathbb{R}$, $\mathbb{C}$, $\mathbb{H}$ and $\mathbb{O}$.  In fact, the identities are well-known identities for these algebras.  In particular, when the dust clears, the ten-dimensional identities are the celebrated Moufang identities.
Of course, if I got the definition of the even ghosts wrong, then what I say above is probably wrong.


text:
Q: Printing selected chapters without affecting cross-referencing I am writing my thesis in Lyx and for some reason, probably due to the style sheet, I am unable to print the complete thesis. It gives weird errors. However, individually all chapters are easily converted to PDF.
Is there a command that allows printing only a few selected chapters but does not affect referencing? I could then restart page numbering and get a quick fix to the problem.
Please advise.

A: Use \includeonly
\documentclass{book}

%\includeonly{Introduction}% uncomment this line if you want to include chapter "Introduction" only without affecting the referencing.

\begin{document}
\include{Introduction}
\include{Summary}
\end{document}


text:
Q: What is a good way to backup SQL Server DB's from multiple AWS EC2 instances to a single AWS EBS Volume or S3 Bucket? I have about 30 AWS instances, each running SQL Server. I want to back them up onto an AWS EBS Volume or S3 bucket - using a free solution.
I was thinking of creating a large volume and mapping each of the instances to it, to backup directly onto it, or to create local backups, which I can then copy onto the central volume. Would this be a good solution?
Another solution would be to set up local backups, then create scripts to FTP the backups to a central server (or copy to S3 https://aws.amazon.com/getting-started/tutorials/backup-to-s3-cli/).

A: You're best off archiving to S3 IA class, as it's cheaper storage but reliable.
An EBS snapshot already stores backups to S3, and can be scheduled. However, the disk images may not be perfect if a write is in progress when the snapshot is taken. They're probably good enough though, but it depends on how critical your data is.
If you move your SQL Server databases into RDS it manages backups for you. That's definitely something to consider. I suspect you get a bit less control than running on EC2 instances.
I'd do this, in a loop for each instance

*

*Dump the database to a flat file using command line tools, probably to a temp directory

*Optionally compress the file

*Use the "aws s3" commands to upload the file to s3

*Delete the original file on your file system - just to save disk space

Alternately you could use s3fs to map a folder to s3, then simply copy the file to that location in your file system.


text:
Q: How to translate controller member arrays in Ember-i18n? In my customer controller I have defined some constant arrays that are used for populating select input (dropdown) options.
import Ember from 'ember';

export default Ember.Controller.extend({
    occupations: [
        {code: 'student', name: "Student"},
        {code: 'worker', name: "Worker"},
        {code: 'retired', name: "Retired"},
        {code: 'other', name: "Other"}
    ]
});

Normal solution would be using translationMacro function t() or this.get('i18n').t() around translation key, but they can't be used in such situation as "this" inside object or array will not refer to controller.
What is best practice for solving such situation?

A: You can make occupations a property:
import Ember from 'ember';

export default Ember.Controller.extend({
    i18n: Ember.inject.service(),

    occupations: function() {
        var i18n = this.get('i18n');
        return [
            {code: 'student', name: i18n.t('occupations.student') },
            {code: 'worker', name: "Worker"},
            {code: 'retired', name: "Retired"},
            {code: 'other', name: "Other"}
        ];
    }.property()
});


text:
Q: Python sqlite3 insert only works in console I have a simple insert statement in sqlite3, but somehow the python version doesn't work, but the exact same statement works fine in console. And python doesn't show any insert error. Any suggestion on how to fix this insert statement in python?
Insert statement:
INSERT INTO facilities (facility_id,facility_name) VALUES ('239SIE39', 'Lobby A');
Table creation statement:
CREATE TABLE IF NOT EXISTS facilities (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, facility_id, facility_name)
Function to store data:
def store_data(table_name: str, rec: dict):
  keys = ','.join(rec.keys())
  values = tuple(rec.values())
  stmt = f"INSERT INTO {table_name} ({keys}) VALUES {values}"
  cur.execute(stmt)


text:
Q: Is there a way to define multiple type synonyms in a single line? My code is currently like this:
type Speed = Float
type Height = Float
type FuelMass = Float
type Gravity = Float

is there a way to not be wasting so much space by grouping the declarations, like
type (Speed, Height, FuelMass, Gravity) = Float

A: No. A type definition is its own statement. If you really wanted to, you could group them on the same line by separating with semicolons instead of newlines, but this would be a very very unusual style.

A: Well, you can of course have any code generated for you by Template Haskell.
module MultiDefinitions where

import Language.Haskell.TH
import Control.Monad

multipleTypeSynonyms :: [Q Name] -> Q Type -> DecsQ
multipleTypeSynonyms synGs tG = do
  t <- tG
  forM synGs $ \synG -> do
    syn <- synG
    return $ TySynD syn [] t

Then
{-# LANGUAGE TemplateHaskell #-}

import Language.Haskell.TH
import MultiDefinitions

multipleTypeSynonyms
    (newName <$> ["Speed", "Height", "FuelMass", "Gravity"]) [t| Float |]

will generate the same definitions you wrote manually.
Is it a good idea to du stuff like that with TH? Hardly. In fact it is also not clear that type synonyms like that are a good thing at all – many Haskellers would argue that you should either use newtypes that actually give additional type safety (or use existing library types, such as from the units library), or else simply hard-code Float.
BTW there's seldom a good reason to use Float, just use Double.


text:
Q: Firebase database structure - denormalized data? I read a lot about nosql databases lately. I get that rule of thumb is to structure the data based on our view (of course, depends on the use case).
Now, let's say that we have a social app and the user has a profile but he also creates posts and we have to store them in the database.
So, I see some developers choose to do that like so:
Posts
-----UserID
-----------PostID
-----------------username: John
-----------------profileImage: https://...
-----------------posted_photo: https://...

This totally fits the structure base on the view. We'd go into posts and our userID and we could get all the data that our view needs. Now my question is, what happens when the user has made 100K posts and he decides to change his profile photo for example. All of his posts so far contain his old photo, so now, we have to write a method that would cycle through 100K of posts (or all of his posts in general) and update his photo. In 2 hours, he decides that "Nah, I don't like this photo, I'd change it back" and we have to make another 100K queries.
How is that (denormalized data) ok? Sure, its easier, its flat but then we have to make ridiculous amounts of queries to change a single profile photo. What's the way to handle this really?

A: I've done this storing user's data in a place and setting just the userID as post attribute.
posts:
    userID:
        postID:
            userID: 'user1',
            attachedImageURL: 'http:..',
            message: 'hey',
            reblogID: 'post4',
            type: 'audio|poll|quote'
users:
    user1:
        name: 'john',
        profileImage: 'http..'

It requires one more query to Firebase to retrieve user's profile data but it's a good way to solve this. It really depends on how you want to use those data.


text:
Q: What the meaning of "vertices induce hyperedges" in hypergraphs? I don't understand what's the meaning of the word "induce" regrading hypergraphs.
For example, "3 vertices induce 2 hyperedges".
I would be glad if you could draw it and explain the meaning of the word.
Edit:
I saw the term in the following article, page 2, the second point of Conjecture 1:
https://www.dropbox.com/s/w39zlg08piiwi9d/DominationIn3Tournaments.pdf?dl=0

The domination number of a 3-tournament such that any four of its
  vertices induce at least two edges with the same tail is bounded by a
  constant.

A: Vertices in hypergraphs induce hyperedges in the same way that vertices in graphs induce edges.
That is, an induced subgraph of a (hyper)graph $G$ is a subgraph that includes an edge $e$ of $G$ whenever all vertices of $e$ are included. In particular, the subgraph $G[S]$ induced by a vertex set $S$ is the unique induced subgraph which has vertex set $S$: its edges are all the edges of $G$ contained in $S$.
A slightly-informal phrase such as

any four of its vertices induce at least two edges with the same tail

that doesn't talk about induced subgraphs directly is meant to unpack to something like

any set of four vertices induces a subgraph that contains two edges with the same tail.


text:
Q: Using SFINAE to select friend or base class c++x03 Hi I was trying to use SFINAE to check if a variable exists on a class and use it to define which friend should I use, and I found out that when I check the value from has_helloworld it fails to deduct the actual value. Is that expected?
How could I implement something similar?
The output result like this should be:
0
1

But when I put the friend again it will be
1
1

I am using c++03 on gcc.
#include <iostream>
#include <string>

template <typename T>
class has_helloworld
{
    template <typename C> static char (&f( __typeof__(&C::helloworld) ) )[1] ;
    template <typename C> static char (&f(...))[2];
public:
    static const bool value = sizeof(f<T>(0)) == 2 ;
};
template <class T, const bool>
class FriendOption{public: void t (){std::cout<< "genericFriend";  }};
template <class T>
class FriendOption<T, false> {public: void t (){std::cout<< "false friend";  }};
template <typename T>
class Hello
{
        typedef T field_type;
static const bool test = has_helloworld<field_type>::value;
    //friend class FriendOption<field_type, test >;
public:
    int helloworld() { return 0; }
};
class OTF {
public:
    int helloworld() { return 0; }
};
class test : public Hello <test>
{};

struct Generic {};

int main(int argc, char *argv[])
{
    std::cout << has_helloworld<test>::value << std::endl;
    std::cout << has_helloworld<Generic>::value << std::endl;
    return 0;
}

A: The problem is not in the friend but in the test
static const bool test = has_helloworld<field_type>::value

Pass the whole new type Hello<field_type> to the test:
static const bool test = has_helloworld<Hello<field_type>>::value;

Demo


text:
Q: Git fetch not pulling changes when using URL I'm trying to set up a service that will update my repository automatically when it detects changes on the remote branch. Before anyone mentions it, I'm aware that embedding the password in the URL is bad practice. I'm currently using:
git fetch https://<user>:<pass>@github.com/<org>/<repo>

Which gives an output of:
From https://github.com/<org>/<repo>
 * branch            development -> FETCH_HEAD

When I run git status after doing the fetch, it doesn't detect the most recent changes.
If I run a normal git fetch without the URL and supply the username and password manually, I get a different output:
From https://github.com/<org>/<repo>
   96353f7..e88782c  development -> origin/development

And then running git status works as predicted and detects that there are changes on the remote branch.
I'm not very experienced with Git and I feel like I'm missing something very obvious. Where is my error?
Edit
So it looks like the missing piece was for me to specify the local and remote branch after the URL:
git fetch https://<user>:<pass>@github.com/<org>/<repo> development:origin/development

As the accepted answer points out: if you don't specify the remote name, git puts the remote changes in the default FETCH_HEAD. This is resolved by specifying the local and remote branches explicitly.
I'm still a little confused as to why git fetch knows to grab from the origin remote by default, but specifying the URL changes this default. But it's working now in any case

A: Git remotes are a name associated with a URL. The default name is origin and the URL is usually whatever you cloned from.
Git stores a snapshot of remote repositories in "remote tracking branches". These are of the form <remote-name>/<branch>. When you git fetch origin Git goes and fetches changes from the URL associated with origin and puts them into remote branches. development -> origin/development is telling you that it put the remote's development branch into your origin/development remote branch.
When you run git fetch https://<user>:<pass>@github.com/<org>/<repo> and give it just the URL, no remote name, Git doesn't have a name for its remote tracking branches. So it just sticks them in an ephemeral FETCH_HEAD which records your last git fetch. That's what development -> FETCH_HEAD is telling you.

Regardless of any of this, git status will show no change. git fetch never changes your local branches nor your index nor your checkout. It will only update your remote tracking branches. This makes it safe to habitually run git fetch to update your snapshot of the remote repository.
What you're looking for to update your local copy of a remote branch is git pull.

Finally, to avoid having to type in your username and password every time, or worse hard coding them into the URL, set up a Git credential helper to securely store your username and password.

A: Since no matter how hard I tried to make git fetch with url behave exactly like git fetch with no url, the only solution I have is this: First cache the password by using some dummy command (git ls-remote), and then run the regular git fetch as follows (assuming there is some non zero timeout for the git credential manager):
git ls-remote --heads https://<user>:<pass>@bitbucket.org/<org>/<repo>

git fetch


text:
Q: Halting the Event Dispatch Thread activity temporarily (v7) Alright, so explaining this situation is somewhat complex. It actually isn't as risque as it seems.
I'm writing a concurrency package which does two things, and it used to work perfectly on JDK 6. The first thing it does is provide a better Future interface which allows callback when the task completes, using event listeners. "But you can use FutureTask's done() for that!" you might say. The problem is that done() is called immediately when a task is cancelled, while the task might still be doing stuff in its call() method. Also, cancelling makes it impossible to retrieve partial results. So my own package fixes these issues by extending on the existing packages (including a new thread pool, but most of the implementation is reused there).

The second thing the package does is solve a common GUI problem. Let's say the user clicks "Save" to save an image. If the image is huge, it would be nice to display a progress monitor instead of freezing the interface. But if the document is small, then the sudden flash of a progress monitor confuses users. And we cannot have a minimum popup time - this slows the workflow down. My solution compromises between these two. The effect is that the EDT "freezes" for the time the task takes to complete, or, if it takes longer than say 1 second, displays a progress monitor with a minimum popup time. The effect is rather elegant. This, too, worked perfectly in JDK6, and even worked with several threads.
THE PROBLEM: In JDK7, the freezing part above now gets a subtle bug. A critical assumption of my code is that the Runnable passed to SwingUtilities.invokeLater() will not run concurrently with other event dispatch thread stuff. So the EDT can't be processing button clicks, accelerators, other events, etc, while the Runnable runs. (This is exploited to stop all input during the freezing) But this seems to have changed in JDK7. In my debugging I noticed the Runnable might be running while the button pressing code is still running! This quickly causes a deadlock due to later stuff. Due to an implementation mistake, nevermind.
Abusing the EDT like this is risky, but back in the day it was the only thing that worked. Some suggested using a GlassPane to intercept events. But it can't intercepts accelerators. Everything else I tried at the time was also limited in this way.
My question is now if anyone sees a better way to do this. If you think my Future problem can be solved in a better way, do tell. And most importantly, if you can see a way to solve the GUI problem above, or stop the input, or guarantee the critical assumption I need on JDK, or suggest a long-term solution - all are extremely appreciated. Thanks!

A: Is the first part of the question related to a better usage of Future?

... done() is called immediately when a task is cancelled, while the task might still be doing stuff in its call() method.

Did you check Thread.interrupted() manually in your call() method?
We know for the source code of FutureTask.cancel(), it just calls Thread.interrupt(), which means only a boolean flag that stands for the interrupted status of the thread will be set to true. No InterruptedException will be thrown unless Thread.sleep(),.wait() or .join() is called because the latter 3 they do check the flag and make a response.
A sample is here, please read the accepted answer.

Also, cancelling makes it impossible to retrieve partial results.

Yes. You may leak the partial result to a Hashmap outside the task. Or straightforward, init the result as a final variable outside, then use it inside(call() & done()). Actually I have ever saved the percentage field into a KV store before.


text:
Q: Creating multiple instances in libgdx Box2d I create an object in box2d, lets say a square and I want to make many copies of square with different coordinates so I can call it with
Square square = new Square(int x, int y)

Inside square I created a method that changes the square color.
What I'm trying to do is create multiple instances of square
square = new Square(2, 4);
square = new Square(9, 7);
.
.
.

and when I call square.changeColor() I want all of them to change, what would be the best way of doing this?

A: Use a static variable for color, that way there will be one across all instances.

A: Make Color in the square class static.
What are static variables?
A simplified explanation of it would be that when you make a change in an Object(Square) of a particular static variable(Color). It will change across all instances of the object (Square).
More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html


text:
Q: Automatic Workflow not triggering from SP designer Using Moss 07 and SPD 07, I'm attempting to create a simple workflow that will trigger an e-mail when the status of a list item has been changed to resolved.
I created a service request list with some custom columns. This is the text that is shown:
If Service Requests:Status equal Resolved
Email Service Requests:Owner
For some reason I cannot get it to trigger and/or send an e-mail.
alt text http://img153.imageshack.us/img153/1884/spworkflow.jpg

A: Provide a screenshot of the SPDesigner Workflow layout (assuming this is a 1 step workflow). Its my guess that you are trying have the workflow read when the item status changes?

A:
I changed that to the "Automatically start this workflow whenever an
  item is changed" and so it triggers multiple workflows (not really
  what I want) but when I changed the status to resolved, I got my
  e-mail!!! so I'm partway there. I guess I need the workflow to start
  when the item is created, but not "complete" until the status has been
  changed to resolved. Thoughts?

There is a Workflow Action in the Workflow designer called "Wait for Field Change in Current Item". I think it will do what you are look for.


text:
Q: Cannot Resolve Method getListView and setListAdapter (Android) When I try to use either of the methods listed in the title (getListView() and setListAdapter()), I get an error that says the methods cannot be resolved.
Here is my code:
 public void onResume() {
    super.onResume();

    mCurrentUser = ParseUser.getCurrentUser();
    mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);
    mFriendsRelation.getQuery().findInBackground(new FindCallback<ParseUser>() {
        @Override
        public void done(List<ParseUser> friends, ParseException e) {
            List<ParseUser> mFriends = friends;
            String[] usernames = new String[mFriends.size()];
            int i = 0;
            for(ParseUser user: mFriends){
                usernames[i] = user.getUsername();
                i++;
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    getListView().getContext(),android.R.layout.simple_list_item_1,
                    android.R.layout.simple_list_item_checked, usernames);
            setListAdapter(adapter);
        }

    });

This is inside of a class called MainActivity.

A: your MainActivity must extends ListActivity
public class MainActivity extends ListActivity {

Go to this Android List View for more information.


text:
Q: Unable to store Web Service response in R I have a SOAP request that is getting a correct response in Rstudio as shown in the screenshot below.  The code used to request the response is
library(RCurl)

headerFields =
  c(Accept = "text/xml",
    'Content-Type' = "text/xml; charset=utf-8",
    SOAPAction = "")

body = '<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://www.xxxxx.com/esotservice/schema">
   <S:Header/>
<S:Body>
<sch:OwnerOnlyInquiryRequest>
<sch:RequestHeader>
<sch:ClientSystem>ePRS</sch:ClientSystem>
</sch:RequestHeader>
<sch:RequestParameterList>
<sch:RequestParam>12174391</sch:RequestParam>
</sch:RequestParameterList>
<sch:RequestType>CESEID</sch:RequestType>
<sch:PeckingOrder>Pricing</sch:PeckingOrder>
<sch:ViewType>Pricing</sch:ViewType>
</sch:OwnerOnlyInquiryRequest>
</S:Body>
</S:Envelope>'

R <- curlPerform(url = "http://slsesotdevt1.ute.xxxx.com:10149/esot/esotservice.wsdl",
            httpheader = headerFields,
            postfields = body, verbose=TRUE)

The response I am getting in RStudio is

My intention is to store the webservice response (black text from the image) into object called R in the code with the object class as XML so that I can use XML package to further process the data.  However, when I say print(R) the only response I get is

After searching the web the response 0 indicates that all went correctly.  But is there a way to actually store the response in R?  If I copy paste the black text appearing in the first image in Rstudio and feed it to xml functions such xmlTreeParse, it gets processed correctly.

A: You need to fetch the response body using a basicTextGatherer.
For example (taken from https://cran.r-project.org/web/packages/RCurl/RCurl.pdf):
library(RCurl)

headerFields =
  c(Accept = "text/xml",
    'Content-Type' = "text/xml; charset=utf-8",
    SOAPAction = "")

body = '<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://www.xxxxx.com/esotservice/schema">
   <S:Header/>
<S:Body>
<sch:OwnerOnlyInquiryRequest>
<sch:RequestHeader>
<sch:ClientSystem>ePRS</sch:ClientSystem>
</sch:RequestHeader>
<sch:RequestParameterList>
<sch:RequestParam>12174391</sch:RequestParam>
</sch:RequestParameterList>
<sch:RequestType>CESEID</sch:RequestType>
<sch:PeckingOrder>Pricing</sch:PeckingOrder>
<sch:ViewType>Pricing</sch:ViewType>
</sch:OwnerOnlyInquiryRequest>
</S:Body>
</S:Envelope>'

h = basicTextGatherer()
R <- curlPerform(url = "http://slsesotdevt1.ute.xxxx.com:10149/esot/esotservice.wsdl",
            httpheader = headerFields,
            postfields = body, verbose=TRUE,
writefunction = h$update)
body <- h$value()


text:
Q: Is it possible to run pluginkit from a process running as root? I'm trying to run pluginkit (The executable that manages extensions on OS X) from a launch daemon running as root.
/usr/bin/pluginkit -m -i "<identifier>" fails with an output of match: Connection invalid. This is not terribly unexpected, since extension settings are handled on a per-user basis.
However, I've tried to use su to run pluginkit as a normal user, and it still doesn't work.
su <username> -l -c "/usr/bin/pluginkit -m -i "<identifier>" also fails with an output of match: Connection invalid.
Somehow the environment that pluginkit is running in is still different enough from a normal user that it doesn't work properly. Is there anyway to run pluginkit as root? Or is there any other way to launch a process as another user that might provide a more complete environment?
I'm testing this with a command line tool written in Swift:
main.swift
import Foundation

let task = NSTask()

// Option 1: Run pluginkit directly
task.launchPath="/usr/bin/pluginkit"
task.arguments = ["-m", "-i", "com.example.findersyncext"]

// Option 2: Run pluginkit as <username> using 'su'
//task.launchPath="/usr/bin/su"
//task.arguments = ["<username>", "-l", "-c", "/usr/bin/pluginkit -m -i \"com.example.findersyncext\""]

// Option 3: Run pluginkit as <username> using 'sudo'
//task.launchPath="/usr/bin/sudo"
//task.arguments = ["-u", "<username>", "/usr/bin/pluginkit", "-m", "-i", "com.example.findersyncext"]

task.standardOutput = NSPipe()
task.standardError = NSPipe()
task.launch()
task.waitUntilExit()

NSLog("Exit code: \(task.terminationStatus)")
let output = NSString(data: (task.standardOutput!.fileHandleForReading.readDataToEndOfFile()), encoding: NSUTF8StringEncoding)
NSLog("Output: \(output)")

let error = NSString(data: (task.standardError!.fileHandleForReading.readDataToEndOfFile()), encoding: NSUTF8StringEncoding)
NSLog("Error: \(error)")

/Library/LaunchDaemons/com.example.PluginKitTest.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.example.PluginKitTest</string>
    <key>Program</key>
    <string>/path/to/PluginKitTest</string>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>/Users/<username>/Desktop/pluginkit-error.log</string>
    <key>StandardOutPath</key>
    <string>/Users/<username>/Desktop/pluginkit-out.log</string>
</dict>
</plist>

A: It turns out that there is additional user context that is not set by the su command, that needs to be set by using the command launchctl asuser. So, I was able to solve my problem by updating my command to invoke both launchctl asuser and su to update all aspects of the context:
launchctl asuser $USER_UID su $USER_UID -c "<command>"
According to the documentation of launchctl asuser:

Adopted attributes include the Mach bootstrap namespace, exception server and security audit session.

I'm not familiar enough with these concepts to tell you exactly what these do, but it was enough to get pluginkit working.


text:
Q: Flask-Restful: Passing list into MongoDB via POST request I'm building an API for a new web service using Python, Flask-Restful w/ pymongo.
A sample MongoDB document should look like this:
{ domain: 'foobar.com',
  attributes: { web: [ akamai,
                       google-analytics,
                       drupal,
                       ... ] } }

The imports:
from flask import Flask, jsonify
from flask.ext.restful import Api, Resource, reqparse
from pymongo import MongoClient

The class:
class AttributesAPI(Resource):
def __init__(self):
    self.reqparse = reqparse.RequestParser()
    self.reqparse.add_argument('domain', type = str, required = True, help = 'No domain given', location='json')
    self.reqparse.add_argument('web', type = str, action='append', required = True, help = 'No array/list of web stuff given', location = 'json')
    super(AttributesAPI, self).__init__()

def post(self):
    args = self.reqparse.parse_args()
    post = db.core.update(  {'domain': args['domain']},
                            {'$set':{'attr': {  'web': args['web'] }}},
                            upsert=True)
    return post

When I CURL post, I use this:
curl -i -H "Content-Type: application/json" -X POST -d '{"domain":"foobar", "web":"akamai", "web":"drupal", "web":"google-analytics"}' http://localhost:5000/v1/attributes

However, this is what gets saved in my document:
{ "_id" : ObjectId("5313a9006759a3e0af4e548a"), "attr" : { "web" : [  "google-analytics" ] }, "domain" : "foobar.com"}

It only stores the last value given in the curl for 'web'. I also tried to use the CLI command with multiple -d params as described in the reqparse documentation but that throws a 400 - BAD REQUEST error.
Any ideas how why it is only saving the last value instead of all values as a list?

A: In JSON objects and in Python dictionaries, names are unique; you cannot repeat the web key here and expect it to work. Use one web key instead and make the value a list:
{"domain": "foobar", "web": ["akamai", "drupal", "google-analytics"]}

and it should be processed as such.

A: In addition to @Martin Pieters answer, you would need to set your location parameter on your self.reqparse.add_argument to a tuple of json and values and the store parameter is append
self.reqparse.add_argument('domain',store='append', type = str, required = True, help = 'No domain given', location=('json','values'))
`


text:
Q: Determine length of NumberLong in Python I have some documents in my MongoDB collection, some of which contain NumberLong values :
{ "_id" : ObjectId("57e4d18df4733211b613f199"), "parentid" : "P1000016", "phone" : NumberLong("9819733299") }
{ "_id" : ObjectId("57e4d18df4733211b613f19a"), "parentid" : "P1000014", "phone" : "24306574|9920599404||9920840077|865" }
{ "_id" : ObjectId("57e4d18df4733211b613f19b"), "parentid" : "P1000017", "phone" : "25821154|25821188|" }

I'm importing them into my python code and extracting each number using split (if I have multiple number sets in phone) or otherwise, directly appending to a list.
But I want only those numbers in my list whose length is greater than 6.
So I tried using this:
#Initializing MongoDB client
client = MongoClient()

#Connection
db = client.mumbai
collection = db.mumbaiLive

for post in collection.find():
    shops.append(post)

for shop in shops:
    phones = shop["phone"].split("|")
    for eachPhone in phones:
        if (len(eachPhone) < 6):
            pass

It works fine until it encounters a NumberLong value.
When I perform
print "len = ", len(eachPhone), I get
len =

I even tried converting it into string first but got the same result.
What I want : I want to skip 'pass'ing the NumberLong values using length check or any other method (like determining whether a value is NumberLong or not).

A: Depending on your use case, you can either add a filter to your query, to only return field phone where the value is string by utilising $type
client = MongoClient()
db = client.database
collection = db.collection

for document in collection.find({"phone":{"$type":"string"}}):
    print document

Which would 'skip' passing phone containing NumberLong value to your function.
Alternatively, if you would like to process phone with NumberLong value in a different manner you can utilise Python isinstance. See below for an example:
for doc in collection.find():
    if isinstance(doc["phones"], long):
        print("Number of digits: %s" % len(str(doc["phones"])))
    else:
        print("Number is not NumberLong")

If you are using Python 2, you have to detect long. If you are using Python 3, you can just detect int .


text:
Q: Apple Retina display doesn't detect headphone Here is my setup:
I have a MBP 15 Retina Display with a Thunderbolt monitor connected to it.
I have a specific set of earphones (IEMs) which aren't being detected by the audio out port.
Despite having them plugged in I am unable to get the Thunderbolt to stop playing the sound.
The above earphones don't change the status of the Sound Pref. pane.
I have another set of earphones which are detected just fine. These do change the Sound Pref. pane to reflect headphones.
The earphones mentioned in case #1 work fine on an iPhone and don't have a Mic built-in.
How do I get the headphones to detect is there a way to force audio out of the Mac with the first earphones plugged in?

A: Maybe the pplug has a tiny misform which leads to a malformed detection, try using a 2.5 jack to 2.5 jack adapter plug, they cost a buck or 2 and might jsut do the trick.


text:
Q: Supporting multiple screens in Android for numerous activities and resources I have around 10 activities in an app and around more than hundred images. Now need to provide support for multiple screens of diff sizes and densities. If I need to create for small,large and xlarge sizes even though it will be customization of 30 more activities rest aside diff densities for a specific size :O Is there any way I can stretch the whole layout depending on the size and densities, I mean what is the best way to solve this problem. It must be a very common problem but I am missing something here. I read the android dev. screen support doc but still confused. Any ideas? Thanks for your help.

A: It's hard to give an answer specific to your project, but in general Android does a good job of this all by itself. All layouts will automatically scale if you haven't specified fixed dimensions (ie using px instead of dp). When it comes to fullscreen images (background and the like) it is best if you provide several resolutions (in the drawable-mdpi, drawable-hdpi etc) folders. You may also have to look at the scaleType for an ImageViews you may have.
Read through the official documentation on how to support multiple screen resolutions. It provides all the information you need and it goes into detail on how to provide different layouts not only for different screen resolutions, but also for different screen orientations and things like smallest width etc (for tablet specific layouts)


text:
Q: set the dropdown value to the given ID I wonder if it is possible to set an HTML dropdown menu to the option matching a given id using jquery. I need this for editing some data.
 IT Department

<select id="department">
  <option value="1">Admin</option>
  <option value="2">Sales</option>
  <option value="3">HR</option>
  <option value="4">IT</option>
</select>

In jquery:
$(".d").click(function(){
    var depid = $(this).attr('id'); // get the id of the department
    $("#department").val(depid); // make the IT option of the menu selected
});

I hope I am well understood. any help is greatly appreciated!

A: You have invalid HTML markup, your td not wrap inside any table as well as you're missing closing </option> tag, change to this:

            IT Department

<select id="department">
    <option value="1">Admin</option>
    <option value="2">Sales</option>
    <option value="3">HR</option>
    <option value="4">IT</option>
</select>

then you can use:
$(".d").click(function(){
    var depid = $(this).attr('id'); // get the id of the department
    $("#department").val(depid); // make the IT option of the menu selected
});

Fiddle Demo


text:
Q: How can I create a hierarchical datagrid in asp.net (.net 2.0) using VB.net How can I create a similar hierarchical datagrid in asp.net (.net 2.0) using VB.net
Please see the image here.
This is the gridview, which is shown after the conversion wizard. How it is desgined(it's like a hirerachial). Thanks in advance

A: Check this link Asp.Net Hierarchical GridView for vb.net implementation and for more information and reference check the following links:
hierarchical grid
ASP.NET - Hierarchical grid view
Hierarchical treeview implementation
Hope this help..


text:
Q: Root Locus Diagrams - "Breakaway Point" Say that we have a root locus diagram with n poles and m zeroes. And we determine that the root locus on the real axis lies between two of these poles and breaks away from the real axis and tends to infinity somewhere in between these points.
There are formulae to determine what angle the asymptote makes with the real axis as well as what point the root locus "breaks away" from the real axis.
I have noticed from some examples that the point at which the root locus breaks is often half-way in between the two poles I was talking about. But sometimes its not. Is there a rule of thumb to determine when this is the case? This would make drawing root locus diagrams much quicker and give me more intuition on the topic.
This might sound a bit confusing, http://www.facstaff.bucknell.edu/mastascu/econtrolhtml/RootLocus/RLocus1ARCADE.html has some examples on root locus diagrams. The "Three Real Poles" and "Three Poles, One Zero" examples show what I meant about the "breakaway point" being exactly halfway between two poles whilst my textbook uses long formulae to determine a "breaksway point" which is not halfway between the two poles.

A: Intuitively you can think that open loop poles tend to "push" and zeros tend to "pull" the root loci. Suppose you have only two real poles, then roots break away at exactly the halfway between them as in System 2 in your link. If you add another real pole as in System 3, it pushes the roots, hence the break away point.
Suppose you have real poles at -1, -3 and a zero at -5. Then zero tends to pull the roots and in fact a circle with center at -5 and radius a little less than 3 will occur. Hence, the break away point will be between -1 and -3, but closer to -3 due to the effect of the zero. Of course there will be another break away point close to -8.
In System 4, zero at -4 is closer to other poles than the pole at -5, hence it pulls the roots "more strong" then the pole pushes. But their effects will even out at infinity, hence asymptote has a 90 degree angle. Note that angle of the asymptotes are directly determined by the difference between number of roots and zeros.


text:
Q: How i can find my pdf file on android phone I've created an app where I assumed an ID opens a pdf file, but as it is now
pdfFile File = new File (Environment.getExternalStorageDirectory () "/ storage/sdcard0 /" + item.getID () + ". pdf ")

so I located it in myself on the phone, but how can I throw it into the app so I can share it with pdf files? Have tried to make a assets under the res, but can not see where it is on your phone so / storage/sdcard0 / can be changed to the location

A: Please give some more details -
Do you want to check the file existence and take necessary action ? then you can proceed as follow-
  File file = new File(Environment.getExternalStorageDirectory () "/ storage/sdcard0 /" + item.getID () + ". pdf ");
 if(file.exists())
 {
  // do what you want
 }


text:
Q: Kentico V8 custom slider web part I don't have a very strong dotNet background, as i'm primary a JS/CSS guy.
I want to use slick.js as a slider plugin, but i'm lost one how. I'm wondering if i'm on the right track here.
Ideally, an editor would be able to create a new page based on a slider template i create each. Each page would be a new slide. These pages would be in a specific folder in the site tree.
My web part would then pull these pages in and render the correctly formatted code and include the needed JS.
Am i on the right tract here? And if so how do i start.

A: You're absolutely on the right track.  I've used slick on a couple of sites now and followed this pattern:

*

*Setup a repeater webpart

*Set the repeater's HTML envelope to be your slider's wrapper

*Set the repeater's transformation to repeat the content of the documents you want to repeat as slides

*Setup your slider script in a javascript webpart OR (my preferred method) on the page template's markup

Here's an example implementation in Kentico that uses slick's documentation.  I'm using version 7, so things will look a little bit different and be in different places, but it shouldn't be too hard to figure out where to go with some googling
First off, you'll need to get the css for slick.  Here I've just added it to the CSS file applied to this site in Kentico.:

Next you need to setup your page template:

Then add a repeater in the design tab:

And setup the repeater's HTML Envelope like so:

Finally, create your transformation:

Edit:  You'll also need to make sure you've setup your content properly, and made sure your repeater's content settings are pointed to the right path.  Here I've set the repeater up to pull everything from underneath the current path ./% which is the slick document.

It's pulling in the test documents which you see here:

A: What you do is add your JS files to the JavaScript application under a folder with your site's code name.  So if your site's code name is "MySite" then you open the JavaScript application in Kentico and add a new folder named "MySite" under the Custom folder.  Then upload your JS files in there.
On your page template, add a reference to your JS files using the JavaScript webpart and some code like
<script type="text/javascript" src="/CMSPages/GetResource.aspx?scriptfile=/CMSScripts/Custom/MySite/my-js-file.js"></script>

Also include jQuery library if you need to.
Then Add a repeater webpart to your page template.  In the properties, you'll want to set the following properties:

*

*Path: the path to pickup the slider/images

*Page types: the page type you will be looking for in the path (ie: menu item)

*ORDER BY expression: NodeLevel, NodeOrder, NodeName

*Transformation: should be the transformation for each item in your slider.  For instance if you have an unordered list, this would include the opening and closing <li> tags and all their contents.

*Content before and after with the opening and closing tags for the unordered list as well as any wrapper elements you might need.

This should get you started.

A: Could be done using custom page types for each slide and using a repeater and transformation. Set the path in the repeater to the folder containing your pages, Then just add the javascript file to your page.
Might want to check out Writing Transformations Documentation


text:
Q: UnknownTimeZoneError when using RequestContext When using Django 1.4, I am getting an UnknownTimeZoneError for America/Chicago when using RequestContext, but it works without it...any ideas?
Error Message
UnknownTimeZoneError at /my_proj/bad_view/
'America/Chicago'

Source
# This works
def good_view(request):
    data = {}
    return render_to_response('mytemplate.html',
                              data)

# This doesn't
def bad_view(request):
    data = {}
    return render_to_response('mytemplate.html',
                              data,
                              context_instance=RequestContext(request))

A: If you don't care about timezone support you should add USE_TZ = False to your settings.py.
If you want timezone support you should install pytz:
pip install pytz

I believe the error is caused by django getting America/Chicago in the template from the request, but django's limited timezone data doesn't have this timezone. The error will go away if pytz is installed.
You should read django's timezone docs to learn how django 1.4 handles timezones.


text:
Q: Replacing the Q code with bluebird I want to do some POC to replace my Q library code with bluebird,
after digging on the bluebird library I dont see (maybe i miss it) the fail method ,is it true?
Does it have some similar logic (in BB) which I can consider to use,example will be helpful :-)

A: Both Q and Bluebird do have a catch method:

*

*https://github.com/kriskowal/q/wiki/API-Reference#promisecatchonrejected

*http://bluebirdjs.com/docs/api/catch.html
which does about the same (being a shorthand for .then(null, …)). Since catch is a keyword and can cause syntax errors when used as a method name in pre-ES5 environments, both libraries do provide an alias. This alias is however different: fail for Q, and caught for Bluebird.

A: Note that bluebird has a Q adapter written by bluebird's author called bluebird-q.
Like Bergi said, the way forward is not to use fail but to use .catch like native promises and bluebird.


text:
Q: Setting NGINX TLS with certificate/key loaded by initContainer I've found several pages describing how to set NGINX to use HTTPS/TLS.
However, all suggest setting a secret tls with the key & cert.
We want to be able to use TLS but ask NGINX to load the key/cert via init-container which in this case implemented by acs-keyvault-agent.
Any ideas?

A: If your only goal is to obtain the TLS key/cert from Azure Key Vault, then you're probably better of going with the Key Vault FlexVolume project from Azure. This would have the advantage of not using init containers at all and just dealing with volumes and volume mounts.
Since you explicitly want to use Hexadite/acs-keyvault-agent and in default mode (which uses volume mounts btw) there is a full example of how to do this in the projects examples folder here: examples/acs-keyvault-deployment.yaml#L40-L47.
Obviously you need to build, push, and configure the container correctly for your environment. Then you will need to conifgure Nginx to use the CertFileName.pem and KeyFilename.pem from the /secrets/certs_keys/ folder.
Hope this helps.


text:
Q: Circuit to enable switching between antennas I'm trying to build my own portable Wi-Fi router that can switch between small internal PCB based antennas (like this from Aliexpress) and an external directional antenna.
Is there  circuit that I can make that can work as a switch between these two different analogue signal inputs? Something that switches automatically based on whether an external antenna's connected would be ideal but not necessary. Is a signal multiplexer (and demultiplexer) at least part of what I need?
Thanks!

A: You can buy SMT coaxial connectors that contain a switch. The antenna input is switched based on whether anything is plugged into the connector.
Just filter results by the feature "internal switch" or search for the term "RF micro-switch".


text:
Q: Flutter how to convert string date to dd/MM/yyyy I am fetching data through api issue is date is coming like string
2020-11-24T21:26:01.627

I simply print it now print((widget.text['OrderCheckouts'] as Map)['CheckoutDate']);
I want to print it in dd/MM/yyyy format
i know its dumb question but i am not able to solve it :D

A: Use Intl DateFormat:
DateFormat('dd/MM/yyyy').format(DateTime.parse(formattedString));


text:
Q: Proper address for married couple when husband is a Jr I have been unable to find a complete answer to my question in any source I have consulted.
I want to make a donation in memory of my deceased parents.  I would like to use both of their first names if possible, and my father was a Jr.  Should the proper format be: John and Mary Smith Jr. or Mr. John Smith Jr. and Mrs. Mary Smith? I believe the Jr. is restrictive and so I have omitted the comma.

A: According to Wikipedia at least (I know, not the best source, but first I found in a quick google search):

A wife who uses the title Mrs. would also use her husband's full name, including the suffix. In less formal situations, the suffix may be omitted. Hence: Mrs. Lon Chaney Jr. on a wedding invitation, but Mrs. L. Chaney or simply Shannon Chaney for a friendly note. Widows are entitled to retain their late husband's full names and suffixes, but divorcees may not continue to style themselves with a former husband's full name and suffix, even if they retain the surname.

Further, it is more correct to name the wife's name first, then the husbands. (see Crane's Blue Book of Social Stationery)
As such:  "Mary and John Smith Jr." (or alternatively: "Mary and John Smith, Jr.")
Note: With regards to whether to use a comma or not when using Jr., Sr., etc, see this Chicago Manual of Style page.


text:
Q: How about having the mods / admins document why they deleted a post In general, there's a lot of push back against documenting why a post gets deleted. In looking at various posts similar to this, it's been explained that nothing really needs to be documented, that the reasons for deleting a post are pretty clear.   That any requirement to document a reason could be circumvented.  That there are not enough admins and more than enough users...etc...  In my humble opinion, it should be done, in fact it should be 100 percent mandatory.  I can give a great example why:
This is a deleted answer
I'm well aware that there are a few reasons an answer can be deleted. The most glaring is if  you don't answer the question. The other reasons are:
Answers that do not fundamentally answer the question may be removed. This includes answers that are:

*

*commentary on the question or other answers

*asking another, different question

*"thanks!" or "me too!" responses

*exact duplicates of other answers

*barely more than a link to an external site

*not even a partial answer to the actual question
Now, on the answer I linked to, the answer given doesn't qualify as any of the above reasons. It is, in fact, a different explanation for the error with an explanation that included an image.   However, a mod came by and deleted that answer and in fact, turned it into a comment. If you'll look at the comment, it's ended before the actual answer is ended and the image is removed, both of which change the answer.
Without a comment as to why this was deleted there's no way to tell what the mod thought was wrong with the answer. To add to this, it can't be undeleted if you have less than 50 points.  You can flag it, HOWEVER if you do that, you must explain why you're flagging it.
In other words, you have to make a case for un-deletion but the mod / admin that deleted has to do nothing other than click a button.  That's simply not correct. In both cases documentation needs to exist. This does two things:

*

*It allows the user to see why the admin/mod deleted it, and it creates a record for other admins / mods to view and to see why this was deleted.

*It allows the user to see what rule was violated and why. That way the user learns. It also gives the user something to challenge directly , if they choose to do so.
As of right now, the challenge is blind and as a result, unfairly weighed in the direction of the mod.

*Allows for documentation on the admins side, in case this user is engaging in a pattern of disruptive behaviour. For example, if this user's contributions were looked at and say they had 10 good posts and 3 deletions all in one area for the same reason, this could be used to show a pattern of behaviour in one area, creating a real and convincing reason for this user to be possibly banned or blocked from a certain area in stack.
As you can see, this is a case where everyone wins. There's literally no reason not to do it.
As to the reasons against:
The reasons are clear - although we have a link that explains why posts can be deleted, I think you'll agree this post doesn't fit any of those rationales, therefore a note from the admin would have been extremely helpful (see points 1 , 2 and 3 ).  The pointers on the question offer on generic explanations and not specific explanations as to the reason for deletion.
That it can circumvented - Yes, nothing's 100 percent foolproof, but if any admin/mod tries to circumvent this, they should loose their mod/admin rights on the spot.
Too many users, not enough admins - That's true of any site. HOWEVER you have to remember, although we can flag that post and ask for it to be reviewed, we're absolutely required to give reasons for our flag, we can't just flag it and be done with it.  Further, we can't undelete our message and request a concensus from other users.
It's obvious that the system is weighed in favor of the admins / mods - so I propose to even the odds, if the admins / mods want to delete a message, they must indicate why this is so.  Once again, per points 1 , 2 and 3 it's an everyone wins situation.

A: There's no reason why you can't ask a clarification question on the relevant sites Meta site asking for why the answer was deleted.
Given enough rep, you can also ping the relevant mod in chat and discuss the matter.  Most moderators are open to discussion and are willing to guide users.
There might be cases where some sites are more rigorous in their moderation and content is removed if it goes against local policy.  In that case, look in the relevant Meta site for guidelines and previous discussions of deleted content, or create a new Meta question if you don't see the answers.

A:
As you can see, this is a case where everyone wins. There's literally no reason not to do it.

Yes, there is. On sites like Stack Overflow, there are so many flags per day that it's not reasonable to expect ♦ moderators to provide a detailed reasoning for every post deletion they perform. I moderate a couple of smaller sites and I tend to leave a comment (often autogenerated) whenever I delete a post, but in blatantly obvious cases I'll omit it. There are more useful things I can do with my time.
When in doubt, or when you want to challenge a deletion, just use one of the regular 'appeal' processes: flag the post for moderator attention, ask a question on the site's own meta or post a message in chat; some sites have a dedicate chatroom for issues involving moderation, like this one.


text:
Q: how to update xml file from another xml file dynamically? I would like to update an xml file from another xml file.I have used an xml file as shown below:
one.xml
    <?xml version="1.0" encoding="utf-8"?>
   <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="#00BFFF">
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:gravity="center" android:visibility="visible">
</LinearLayout>
<LinearLayout
    android:id="@+id/linearLayout2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:gravity="center" android:visibility="visible">

</LinearLayout>

</LinearLayout>
</ScrollView>

two.xml as follows:
      <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
       <map>
      <int name="linearLayout1" value="8" />
      <int name="linearLayout2" value="0" />
      </map>

from the above two xml files i would like to change the attribute value one. xml when
if
  <int name ="linearLayout1" value = "8"/>

from two.xml then I would like to update one.xml file as where LinearLayout android:id="@+id/linearLayout1" then change the attribute value as android:visibility="gone".

A: Here is code what you want it's
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse("/home/riddhish/developerworkspace/SplitString/src/com/updatexmlwithjava/two.xml");
    DocumentTraversal traversal = (DocumentTraversal) doc;
    Node a = doc.getDocumentElement();
    NodeIterator iterator = traversal.createNodeIterator(a, NodeFilter.SHOW_ELEMENT, null, true);

/**
    *  Logic for checking
    **/
boolean flag=false;
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
       Element e = (Element) n;
            if ("int".equals(e.getTagName())) {
                if(e.getAttribute("name").equals("linearLayout1")){
                        if(e.getAttribute("value").equals("8"))
                            flag=true;
                    }
            }
}

/**
* Logic for reading one.xml and setting android:visibility="gone"
**/
docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.parse("/home/riddhish/developerworkspace/SplitString/src/com/updatexmlwithjava/one.xml");
traversal = (DocumentTraversal) doc;
a = doc.getDocumentElement();
iterator = traversal.createNodeIterator(a, NodeFilter.SHOW_ELEMENT, null, true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
      Element e = (Element) n;
          if ("LinearLayout".equals(e.getTagName())) {
                if(e.getAttribute("android:id").equals("@+id/linearLayout1")){
                        if(flag==true){
                            System.out.println(""+e.getAttribute("android:visibility"));
                            e.setAttribute("android:visibility", "gone");
                        }
                }
          }
}

/**
* Logic for rewriting one.xml
**/
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/home/riddhish/developerworkspace/SplitString/src/com/updatexmlwithjava/one.xml"));
iterator = traversal.createNodeIterator(a, NodeFilter.SHOW_ELEMENT, null, true);
doc = docBuilder.newDocument();
Element rootElement = doc.createElement("ScrollView");
doc.appendChild(rootElement);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
        rootElement.appendChild(doc.importNode(n, true));
}
transformer.transform(source, result);


text:
Q: Javascript Regexp - replace function should decide not to replace matched string to let other parenthesized submatch strings work with a match This is fairly simple example, what I want is this: if replace function decides not to replace a 'match' - every other parenthesized submatch string: '(".+?":)' or '([^\s]+?:)' should work on this match also and not skip it only because the first submatch string got a match on that.
Simple example, please take a look:
var fieldNames = [
    { displayName: "Sender", systemName: "from_field"},
    { displayName: "Receiver(addressee)", systemName: "to_field"},
    { displayName: "Author", systemName: "author_id_field"}
];

var query = 'AND (ENTITY(Company),OR(Sender:john, Receiver(addressee):john),OR(#"Receiver(addressee)":Tanaka),OR(#"Abracadabra":Phil)) OR Author:Stan';

// What I want to retrieve as a result:
// 'AND (ENTITY(Company),OR(from_field:john, to_field:john),OR(to_field:Tanaka),OR(#"Abracadabra":Phil)) OR author_id_field:Stan'

// I want to:
// Replace '#"displayName":' with 'systemName:'
// Replace '"displayName":' with 'systemName:'
// Replace 'displayName:' with 'systemName:'
regexp = /(#".+?":)|(".+?":)|([^\s]+?:)/gi;

var newQuery = query.replace(regexp, replaceDisplayName);
console.log('Result:');
console.log(newQuery);

function replaceDisplayName(match, p1, p2, p3) {
    console.log("match: " + match);
    var potentialDisplayName;
    if (p1) {
        // Get the word(s) inside: '#"displayName":' -> get 'displayName'
        potentialDisplayName = match.substring(2, match.length - 2);
    } else if (p2) {
        // Get the word(s) inside: '"displayName":' -> get 'displayName'
        potentialDisplayName = match.substring(1, match.length - 2);
    } else if (p3) {
        // Get the word(s) inside: 'displayName:' -> get 'displayName'
        potentialDisplayName = match.substring(0, match.length - 1);
    }

    console.log('potentialDisplayName: ' + potentialDisplayName);
    var systemName = getFieldNameByDisplayName(potentialDisplayName);
    console.log('found systemName: ' + systemName);

    var newStringValue = systemName ? systemName + ":" : match;
    return newStringValue;
};

function getSystemNameByDisplayName(displayName) {

    for (var i = 0; i < fieldNames.length; i++) {
        if (fieldNames[i].displayName.toLowerCase() === displayName.toLowerCase()) {
            return fieldNames[i].systemName;
        }
    }

    return null;
};

Result:

'AND (ENTITY(Company),OR(Sender:john,
  to_field:john),OR(#"Receiver(addressee)":Tanaka),OR(#"Abracadabra":Phil))
  OR author_id_field:Stan'

Result that I want:

'AND (ENTITY(Company),OR(from_field:john,
  to_field:john),OR(to_field:Tanaka),OR(#"Abracadabra":Phil)) OR
  author_id_field:Stan'

The issue is that for example the first match would be:
'(ENTITY(Company),OR(Sender:'
This value is not a 'displayName', so no systemName will be found and I'll get no replacement. BUT I want 'Sender:' still be replaced with 'to_field'. But, this whole match would be skipped because the first submatch string '(#".+?":)' already worked with it, so it doesn't give a chance for other submatch strings: '(".+?":)' and '([^\s]+?:)' to work with it.
Thank you for your time, any help is appreciated!

A: Give this a try. I did build a fast lookup from displayName to systemName to use:
var fieldNames = [
        { displayName: "Sender", systemName: "from_field"},
        { displayName: "Receiver(addressee)", systemName: "to_field"},
        { displayName: "Author", systemName: "author_id_field"}
    ],
    regex = /(?:#?"?)([^":]+)(?:"?):/i,
    map = {
        "Sender": "from_field",
        "Receiver(addressee)": "to_field",
        "Author": "author_id_field"
    };

var test = [
    '#"Sender":',
    '"Sender":',
    'Sender:',
    '#"Receiver(addressee)":',
    '"Receiver(addressee)":',
    'Receiver(addressee):',
    '#"Unknown":'
];

for (var i=0; i<test.length; i++) {
    var systemName = test[i].replace(regex, function(match, p1) {
       if (p1) return map[p1] || p1;
    });
    console.log("Display[%s] = System[%s]", test[i], systemName);
}
// output:
// Display[#"Sender":] = System[from_field]
// Display["Sender":] = System[from_field]
// Display[Sender:] = System[from_field]
// Display[#"Receiver(addressee)":] = System[to_field]
// Display["Receiver(addressee)":] = System[to_field]
// Display[Receiver(addressee):] = System[to_field]
// Display[#"Unknown":] = System[Unknown]

If the displayname being matched isn't known (_i.e. in the lookup map), it simply returns it as is.


text:
Q: How to make validations from a query to a table? yii2 my problem is: I have a form where i have select2 and the user can select from a dropdown list which is populated from a table, so, basically what i want to happen is that when the user tries to select a driver a validation rule will take place which will check if the driver was already registered through the system that day.
I have one idea of how to do it, i have my archive form which registers people that enter in the archive table, it checks wether it exists or not in the drivers table and if not you have to register them, if they exists you proceed to fill out the form, each field in the this archive table has a datecreated column which is the date the field was entered, so basically the last time he came in.
How can i make a rule which calls for this column compares to current day and gives an error if he had already entered that day? The rule should be in drivers model.(My code is confusing that is why i'm clarifying, i'm new to Yii2)
My view (archive form):
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use wbraganca\dynamicform\DynamicFormWidget;
use app\models\Drivers;
use app\models\Vehicles;
use app\models\Invoices;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use yii\bootstrap\Modal;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $model app\models\Archive */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
    <?= $form->field($model, 'driver_identitynum')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(Drivers::find()->all(),'driver_identitynum', 'fullname'),
    'language' => 'en',
    'options' => ['placeholder' => 'Ingrese el numero de cedula...'],
    'pluginOptions' => [
        'allowClear' => true],
    ]); ?>

<?= Html::a('Add driver', ['/drivers/create'],
       ['target'=>'_blank']); ?>

    <?= $form->field($model, 'vehicle_lp')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(Vehicles::find()->all(),'vehicle_lp', 'fulltruck'),
    'language' => 'en',
    'options' => ['placeholder' => 'Ingrese la placa del vehiculo...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
    ]); ?>

<?= Html::a('Add vehicle', ['/vehicles/create'],
       ['target'=>'_blank']); ?>

Facturas

             <?php DynamicFormWidget::begin([
                'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
                'widgetBody' => '.container-items', // required: css class selector
                'widgetItem' => '.item', // required: css class
                'limit' => 4, // the maximum times, an element can be cloned (default 999)
                'min' => 1, // 0 or 1 (default 1)
                'insertButton' => '.add-item', // css class
                'deleteButton' => '.remove-item', // css class
                'model' => $modelsInvoices[0],
                'formId' => 'dynamic-form',
                'formFields' => [
                    'invoice_number',
                    'invoice_loadamount',
                    'invoice_date',
                ],
            ]); ?>

            <?php foreach ($modelsInvoices as $i => $modelInvoices): ?>

Facturas

                            <button type="button" class="add-item btn btn-success btn-xs"></button>
                            <button type="button" class="remove-item btn btn-danger btn-xs"></button>

                        <?php
                            // necessary for update action.
                            if (! $modelInvoices->isNewRecord) {
                                echo Html::activeHiddenInput($modelInvoices, "[{$i}]id");
                            }
                        ?>

                                <?= $form->field($modelInvoices, "[{$i}]invoice_number")->textInput(['maxlength' => true]) ?>

                                <?= $form->field($modelInvoices, "[{$i}]invoice_loadamount")->textInput(['maxlength' => true]) ?>

                                <?= $form->field($modelInvoices, "[{$i}]invoice_date", ['enableAjaxValidation' => true])->widget(DatePicker::className(), [
                                            // inline too, not bad
                                             'inline' => false,
                                             // modify template for custom rendering
                                            //'template' => '
{input}
',
                                             'options' => ['class' => 'form-control picker'],
                                            'clientOptions' => [
                                                'autoclose' => true,
                                                'format' => 'dd-mm-yyyy'

                                                                                ]
                                                                            ]);?>

            <?php endforeach; ?>

            <?php DynamicFormWidget::end(); ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>

My drivers model:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "drivers".
 *
 * @property integer $driver_id
 * @property string $driver_name
 * @property string $driver_lastname
 * @property string $driver_identitynum
 */
class Drivers extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'drivers';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['driver_name', 'driver_lastname', 'driver_identitynum'], 'required'],
            [['driver_name', 'driver_lastname', 'driver_identitynum'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'driver_id' => 'Driver ID',
            'driver_name' => 'Driver Name',
            'driver_lastname' => 'Driver Lastname',
            'driver_identitynum' => 'Driver Identitynum',
        ];
    }

    public function getfullName()
        {
                return $this->driver_identitynum.' - '.$this->driver_name.' '.$this->driver_lastname.' ';
        }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getArchives()
    {
        return $this->hasMany(Archive::className(), ['driver_identitynum' => 'driver_identitynum']);
    }
}

My archive model:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "archive".
 *
 * @property integer $id
 * @property string $driver_identitynum
 * @property string $vehicle_lp
 * @property string $DateCreated
 *
 * @property Invoices[] $invoices
 */
class Archive extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'archive';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['driver_identitynum', 'vehicle_lp'], 'required'],
            [['DateCreated'], 'safe'],
            [['driver_identitynum', 'vehicle_lp'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'driver_identitynum' => 'Cedula del conductor:',
            'vehicle_lp' => 'Placa del vehiculo:',
            'DateCreated' => 'Date Created',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getInvoices()
    {
        return $this->hasMany(Invoices::className(), ['archive_id' => 'id']);
    }
    public function __toString()
    {
        return 'CI:'.$this->driver_identitynum.' Placa: '.$this->vehicle_lp;
    }

    public function didheloadtoday($attribute,$params)
    {
    $inputlp=($this->invoice_loadamount);
    $row = (new \yii\db\Query())
    ->select('vehicle_lp')
    ->from('vehicles')
    ->where("vehicle_lp=$vehiclelp")
    ->all();
    }

}

A: So, the rule is that only one driver_identitynum and DateCreated combination can exist in the archive table.
To validate the driver_identity field for this you can use the native unique validator and specify the attributes that need to be unique together.
The corresponding rule would be:
[['driver_identitynum'], 'unique',
    'targetAttribute' => ['driver_identitynum', 'DateCreated'],
],

If this validation is called from another model, then it complicates matters a bit. In addition to the above:

*

*specify the target class

*declare a public date variable in the other model

*store current date in this field

*indicate the this date property should be used as value to check uniqueness of DateCreated

The adjusted rule would be:
[['driver_identitynum'], 'unique',
    'targetAttribute' => ['driver_identitynum', 'date' => 'DateCreated'],
    'targetClass' => '\app\models\Archive'
],


text:
Q: MicroBlaze AXI4 Exceptions I am wondering about Data Bus Exceptions for the MicroBlaze. In the MicroBlaze product manual it states that the exception can only occur on M_AXI_DC when the cache is turned off? This doesn't make sense to me; does it mean that if an error response is given on the M_AXI_DC line, no exception will be triggered if caching is enabled? I currently have C_DCACHE_ALWAYS_USED set to 1 so that is not an issue.
Thanks.
Excerpt from MicroBlaze product guide:
The data cache AXI4 interface (M_AXI_DC) exception is caused by:

    - An error response on M_AXI_DC_RRESP or M_AXI_DC_BRESP,
    - OKAY response on M_AXI_DC_RRESP in case of an exclusive access using LWX.

The exception can only occur when C_DCACHE_ALWAYS_USED is set to 1 and the
cache is turned off

A: Based on my hardware/software tests and using an AXI BRAM Controller to generate ECC fault injections, the MicroBlaze will not issue an data or instruction cache exception if caching is enabled, even if caching is disabled right before writing; and reenabled before reading to trigger the exception. This is also the case if the cache is flushed and invalidated, and then read immediately back.
This basically means that ECC is worthless in MicroBlaze designs that have caching enabled; as they do not trigger any hardware exceptions.
Even though the response by the AXI BRAM Controller is a SLVERR, the MicroBlaze will accept the data as is; as if nothing bad could possibly happen.
Who designed this. Seriously.
I guess the only surefire method is to use interrupts to detect ECC errors; which have a lower precedence than hardware exceptions.


text:
Q: Liberating email addresses from outlook I have outlook 2007, and I recently sent an email with a BCC of about 75 addresses.  I would like to copy and paste this BCC list into a spreadsheet to keep track of the names AND email addresses of the people I contacted.
The problem is, when I copy the BCC field from outlook, it only copies the names in the list, NOT the email addresses.
How do I liberate these email addresses from outlook's cold, dead hands?  Is there any way to force outlook to copy the email addresses, rather than the names? Does this useless feature have any purpose, other than frustrating users and preventing them from using competing email services?
Thank you.

A: I ended up using NK2Edit to solve this problem.  I had to manually select the emails I wanted, which was a little tedious, but it allowed me to copy the names and email addresses as a tab-delimited file.
I'm still curious why outlook has this strange behavior, and it there's a good way to stop it.