text:
Q: Rust - double mutable borrow in 'while let' statement Sorry if this is a dumb question, I'm relatively new with Rust and just can't crack this double mutable borrowing error. I'm trying to create an AVL tree method that finds an appropriate position into which a new node can be inserted. I don't understand what I need to do for the first borrow to drop.
I'm trying to do this without RC, RefCell or Unsafe - though it's becoming increasingly unclear to me if my approach is feasible.
Rust Playground Link
    pub fn find_pos(&mut self, key: &K) -> &mut Link<K, V>{
        let mut current = &mut self.root;
        while let Some(node) = current.as_mut() {  // <- first mutable borrow
            match node.key.cmp(&key) {
                Ordering::Equal => break,
                Ordering::Greater => {
                    current = &mut node.right;
                },
                Ordering::Less => {
                    current = &mut node.left;
                },
            }
        };
        current  // <- second mutable borrow
    }

I've also tried something similar to the solution described here, with no luck.
    pub fn find_pos(&mut self, key: &K) -> &mut Link<K, V> {
        let mut current = &mut self.root;
        loop {
            let tmp = current;
            if let Some(ref mut node) = *tmp {
               match node.key.cmp(&key) {
                   Ordering::Equal => {
                       current = tmp;
                       break
                   },
                   Ordering::Greater => {current = &mut node.right},
                   Ordering::Less => {current = &mut node.left},
               }
            } else {
                current = tmp;
                break
            }
        }
        current
    }

A: This is a known limitation of the borrow checker. The next-gen Polonius will solve this.
In the meantime, the solution (without unsafe) is to repeat the calculation. In your case, this means some unwrap()s:
pub fn find_pos(&mut self, key: &K) -> &mut Link<K, V> {
    let mut current = &mut self.root;
    while current.as_mut().is_some() {
        match current.as_mut().unwrap().key.cmp(&key) {
            Ordering::Equal => break,
            Ordering::Greater => {
                current = &mut current.as_mut().unwrap().right;
            }
            Ordering::Less => {
                current = &mut current.as_mut().unwrap().left;
            }
        }
    }
    current
}

See also:

*

*Cannot borrow as mutable in loop

*Returning a reference from a HashMap or Vec causes a borrow to last beyond the scope it's in?


text:
Q: SharePoint Approval Workflow customizing email notifications I am working in Sharepoint Designer on an approval workflow.  I am customizing the emails that are sent to the initiator and the approver.  How do I rebuild that link, so the approver can click the link right in the email and be routed to the infopath form the initiator filled out?  And how do I change name of the link (it currently says (no title))?
Thanks for the help!

A: This is the method I use - hope it helps:
http://punaro.com/2012/01/derek/modifying-a-sharepoint-2010-workflow-email/

Click edit workflow > approval > Under "Customization" click Change the behavior of a single task > Under the "When a Task is Pending" section, find the line that says "then Email task notification to Current Task:Assigned To" and click the underlined link.
The Define E-Mail Message window opens. Insert the highlighted text, select the text you wish to make a link, then click the Edit Hyperlink button.

A: What I usually do is get the address of the form directly (yes, InfoPath forms work for this too), copy that, and insert it as a hyperlink into the e-mail formatter. For your second question, I would just imagine that you insert a hyperlink and set the description as the word you want with the address of the form, the same way as much of SharePoint handles hyperlinks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java bytecode - checking if args is equal to null, will it ever run Got a java class and got it to bytecode. My question is will it ever go to _L2 based on the below? I wouldn't have thought so (I read another StackOverflow article that said it would never be null but I can't find it right now)
Secondly, if it does go to _L1, it just sets j to zero.... but what is the next step? Does it continue to _L7?
If it does hit _L2 where does it go from there?
public class testing

{

    public static volatile void main(String args[])
    {
        local;
        Object obj;
        int i;
        obj = ((String) (obj)).toCharArray();
        i = 0;
        if(args == null) goto _L2; else goto _L1
    _L1:
        int j = 0;
    _L7:
        if(j == -(~obj.length + 2)) goto _L4; else goto _L3
    _L2:
        if(args[0].length() != 32)
            break MISSING_BLOCK_LABEL_484;

A: args won't be null when you invoke the program normally, but one could always call the main method manually with a null argument.
That being said, the code you posted doesn't make much sense. Technically, the entire method is unreachable because the line obj = ((String) (obj)).toCharArray(); at the beginning will unconditionally throw, since obj is null here.
My guess is that it was obfuscated and that the decompiler you used is not decompiling it accurately. Instead of using a possibly buggy decompiler, I'd recommend using the Krakatau disassembler and posting the bytecode disassembly so we can see what is actually in the classfile in question.


text:
Q: polynomial time in? Related to exponential in terms of? (nonetheless different from it):
Assume that you have an algorithm (producing gizmos) whose inputs are three numbers t, d, and h, which are interpreted by a human as the number of thingums, doodahs, and hickeys. Suppose the running time of the algorithm is the function g, which depends on t, d, and h. Further, let g(t,d,h) ≤ dᶜ, where c is some expression exceeding 1 and depending on t and h, but not on d.
I would like to use plain English to express this fact (e.g., in an abstract) in a simplified way. Do we write

The algorithm runs in polynomial time in the number of doodahs.

or

The algorithm runs in polynomial time with the number of doodahs.

?
My English teacher corrected it to

The algorithm runs in polynomial time in terms of the number of doodahs.

I think this cannot be quite right.
Which version is correct? And how about

The algorithm runs in worst-case polynomial time in/with the number of doodahs.

Any better version?
I welcome answers from mathematicians who are native AmE speakers and have an excellent command of English.

A: Well, "polynomial time" is already jargon so you're out of the realm of "standard" English.  Unless there was a good reason not to, I would be explicit and use the actual math to describe exactly what the polynomial looks like and what factors into the equation.  Example from the Wikipedia article on Time complexity:

The Euclidean algorithm for computing the greatest common divisor of two integers is one example. Given two integers a and b the running time of the algorithm is bounded by O((log a + log b)2) Turing machine steps. This is polynomial in the size of a binary representation of a and b as the size of such a representation is roughly log a + log b.

If it's not necessary to be explicit, you can just say "the algorithm runs in polynomial time".  Otherwise there is probably a lot of leeway in how you phrase it, since statements like this rely more on the math than English grammar.

The algorithm runs in polynomial time (based on)/(relative to)/(varying with) the number of doodahs

A: This might be an idiomatic contraction of "in the domain of the numbers of doodahs". The polynomial is a function in the domain. Otherwise the preposition doesn't make much sense and I'd prefer "to run over/through the numbers".


text:
Q: Added isolcpus to Grub, restarted but cat /proc/cmdline doesn't show it added I've added isolcpus to the Grub file:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash isolcpus=2,3"

Restarted machine (Ubuntu 22.04)
However, when I run:
cat /proc/cmdline

it doesn't show my isolcpus change:
BOOT_IMAGE=/boot/vmlinuz-5.15.0-43-generic root=UUID=d0731368-37f5-4a83-84d9-a899d39f5a59 ro quiet splash vt.handoff=7

I can also see interrupts on those 2 cores.
Am I missing something to get this to work?

A: Merely editing the grub configuration does not suffice; a command must be run to rebuild the grub menu. On ubuntu, this command is update-grub so after editing the configuration file one must run
sudo update-grub

and only then reboot.


text:
Q: Split an ArrayList compared to an attribute I have an ArrayList<History>.
The History class has an attribute event
Is it possible to split the ArrayList<History> in multiples ArrayList<History> in relation to their event ?
Thank you

A: With Java 8:
List<History> list = Arrays.asList(new History("event1"),
                                   new History("event2"),
                                   new History("event1"));

Map<String, List<History>> result = list.stream()
                                        .collect(Collectors.groupingBy(History::getEvent));

Will produce map with event names as a key and list of History entries as a value.

A: You can use Group By on event field.
public class CreditCard {

    private String event;
    private String name;

    public CreditCard() {
        // TODO Auto-generated constructor stub
    }

    public CreditCard(String event, String name) {
        super();
        this.event = event;
        this.name = name;
    }

    public String getEvent() {
        return event;
    }

    public void setEvent(String event) {
        this.event = event;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "CreditCard [event=" + event + ", name=" + name + "]";
    }

    public static void main(String[] args) {
        List<CreditCard> list = new ArrayList<CreditCard>();
        list.add(new CreditCard("A", "John1"));
        list.add(new CreditCard("B", "John2"));
        list.add(new CreditCard("C", "John3"));

        list.add(new CreditCard("A", "mark1"));
        list.add(new CreditCard("B", "mark2"));
        list.add(new CreditCard("C", "mark3"));

        Map<String,List<CreditCard>> obj = list.stream().collect(Collectors.groupingBy(CreditCard::getEvent,Collectors.toList()));
    }
}


text:
Q: How to read hexadecimal value from xml file using java i am trying to fetch data from xml file using java.
using mysqldump the database table is converted to xml.
table contains one field which is in BLOB type.
Table structure :
CREATE TABLE `test` (
  `image` BLOB
) ENGINE=INNODB DEFAULT CHARSET=utf8

Back up data with hexadecimal value using following procedure
mysqldump -uuser -ppassword test test --compact --no-create-info --hex-blob > check.sql --xml

in xml blob field content is in hexadecimal values.
Java code that i tried is
public static void main(String args[]) {
    try {

        File fXmlFile = new File("E:\\check.sql");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("row");
        System.out.println("-----------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                System.out.println(" Image " + getTagValueUsingAttributeName("field","image", eElement));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static String getTagValueUsingAttributeName(String sTag, String attributeName, Element eElement){
    String value="";
    for(int i=0;i<eElement.getElementsByTagName(sTag).getLength();i++){
        if((eElement.getElementsByTagName(sTag).item(i).getAttributes().getNamedItem("name").getTextContent()).equalsIgnoreCase(attributeName)){
            System.out.println(" - "+eElement.getElementsByTagName(sTag).item(i).getAttributes().getNamedItem("name").getTextContent());
            NodeList nlList = eElement.getElementsByTagName(sTag).item(i).getChildNodes();
            System.out.println(1);
            Node nValue = (Node) nlList.item(0);
            if(nValue!=null)
                System.out.println(2+" - "+(nValue.getNodeType() == Node.TEXT_NODE));
            value = (nValue==null)?" ":nValue.getTextContent();
            break;
        }
    }
    return value;
}

But i can not read the xml file for parsing.
Note :
  I tried to put the xml file in stackoverflow but it does not allow me to add xml content.
please help me.

A: If you need to decode long value encoded as Hex you could use this class: http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html
For example, if you have your value stored in char[] array you may use Hex.decodeHex(char[] data) to convert it into raw byte[] array. I'm assuming that you you're treating your BLOB as binary content.


text:
Q: Inverse of a non-trivial exponential function I am asked to determine the inverse function of this function,
    $$f(x)=2^{x}+3^{x}$$
The inverse function can not be found explicitly, since there is no way to explicitly clear x, but this does not mean that it has no inverse.
I could show a way to find the inverse of this function
Edit  How can we find the inverse of this function with the problems that it presents in the clearance of the x?

A: You could, for example, write the solution to $2^x + 3^x = y$ as a series in powers of $y-2$:
$$\eqalign{x &= \frac{y-2}{\ln(6)} - \left(\ln(3)^2 + \ln(2)^2\right) \frac{(y-2)^2}{2 \ln(6)^3}\cr +& \left(2 \ln(3)^4 - \ln(3)^3\ln(2)+6\ln(3)^2\ln(2)^2-\ln(3)\ln(2)^3 + 2 \ln(2)^4\right)\frac{(y-2)^3}{6 \ln(6)^5}\cr - &\left(3 \ln(3)^6 - 4 \ln(3)^5 \ln(2) + 18 \ln(3)^4 \ln(2)^2 - 10 \ln(3)^3 \ln(2)^3 + 18 \ln(3)^2 \ln(2)^4 - 4 \ln(3)\ln(2)^5 + 3 \ln(2)^6 \right) \frac{(y-2)^4}{12 \ln(6)^7}
\cr + &\ldots }$$

A: This is basically the same as Robert Israel's answer.
Consider the more general case of $y=a^x+b^x$ and expand as a Taylor series around $x=0$ to get
$$y=2+x (\log (a)+\log (b))+\frac{1}{2} x^2 \left(\log ^2(a)+\log
   ^2(b)\right)+\frac{1}{6} x^3 \left(\log ^3(a)+\log ^3(b)\right)+O\left(x^4\right)$$ Now, proceed as in the link I gave in a comment to get
$$x=\frac{y-2}{\log (ab)}-\frac{(y-2)^2 \left(\log ^2(a)+\log ^2(b)\right)}{2
   \log^3 (ab)}+\frac{(y-2)^3 \left(-\log ^3(a) \log (b)-\log (a) \log
   ^3(b)+6 \log ^2(a) \log ^2(b)+2 \log ^4(a)+2 \log ^4(b)\right)}{6 \log^5 (ab)}+O\left((y-2)^4\right)$$

A: Given that
$$
y(x) = 2^{\,x}  + 3^{\,x} \quad 0 < y'(x) = \ln \left( 2 \right)2^{\,x}  + \ln \left( 3 \right)3^{\,x}
$$
and the function is convex, in alternative to espress $x(y)$ through an infinite series,
you may consider to express it as a sequence, using e.g. the Newton-Rapson method,
i.e.
$$
x(y) = \mathop {\lim }\limits_{n\; \to \;\infty } x_{\,n}  = x_{\,n - 1}  + {{y - f\left( {x_{\,n - 1} } \right)} \over {f'\left( {x_{\,n - 1} } \right)}}\quad \left| {\;x_{\,0}  = 0} \right.
$$
which is convenient specially from the computational point of view.
You can much improve the convergency rate if you apply the method to
$$
g(x) = \ln \left( y \right) = \ln \left( {2^{\,x}  + 3^{\,x} } \right)\quad g(x)' = {{\ln \left( 2 \right)2^{\,x}  + \ln \left( 3 \right)3^{\,x} } \over {g(x)}}
$$


text:
Q: EXtJS grid CheckColumn, How to execute function, after column is clicked/its state is checked? I have ExtJS GRID with checkcolumn, which is declared this way:
// the check column is created using a custom plugin
sel_column = new Ext.grid.CheckColumn({
   sortable: false,
   header: 'STE
SEL',
   dataIndex: 'sel',
   width: field_w,

    listeners:
    {

      "mousedown":
      {
        fn : function(e)
        {
            $.log( "Sel cellclick" , e );
        }
      }

    }

});

I want add some listener on changfe of it stae, or on mouse click.
Finaly - want id's of rows, where i click this column - to be stored in text field
For now i can understood how to catch click event, i use onMouseDown, this way:
// the check column is created using a custom plugin
sel_column = new Ext.grid.CheckColumn({
   sortable: false,
   header: 'STE
SEL',
   dataIndex: 'sel',
   width: field_w,

   onMouseDown: function( e )
   {
     $.log( e,"MouseDown" );
   }

});

But it fires, when i click ANY cell, not only checkboxed ...
Pls help me

A: checkbox plugin need modification, after which it can fire click event.

A: /*
**************************************************************
Sample to add event 'checkchange' in checkbox on checkcolumn,
works with ExtJS 4 or above
*/
//Add you checkcolumn   id:'op_check'. No need separate plugin.
//Put this code in You Grid

listeners:{
    afterrender:function(){
        g = this;   //This grid
        Ext.getCmp('op_check').on('checkchange', function(c, i){
            //Get id from row/record (if in store exist field 'id')
            //"i" - in this function is index row, where clicked checkbox
            rec = g.store.getAt(i);
            id = rec.get('id');
            console.log(id); //:)
        });
    }
}


text:
Q: How do I install jtransc? The jtransc Github README shows there is a gradle plugin I can add with:
plugins {
    id "com.jtransc" version "0.6.8"
}

But whenever I sync the project it shows the following error:
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find com.jtransc:jtransc-main:unspecified.
     Searched in the following locations:
       - https://plugins.gradle.org/m2/com/jtransc/jtransc-main/unspecified/jtransc-main-unspecified.pom
       - https://plugins.gradle.org/m2/com/jtransc/jtransc-main/unspecified/jtransc-main-unspecified.jar
     Required by:
         project : > com.jtransc:com.jtransc.gradle.plugin:0.6.8 > gradle.plugin.com.jtransc:jtransc-gradle-plugin:0.6.8

and if I go to those URLs in my browser, it returns a 404.
How can I get the jtransc gradle plugin to work in my project?

A: No idea why plugins block doesn't work, but the following does the job:
buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "com.jtransc:jtransc-gradle-plugin:0.6.8"
  }
}

apply plugin: "com.jtransc"

Maybe it's published incorrectly because this gradle.plugin. prefix here seems totally out of place.


text:
Q: xcode & (un)zip file I have an problem, I have develop one app where I actually need to unzip file. This files I receive from internet, save on Document folder of device and try to unzip.
But... unzip never occurs. The message I receive is:
Error Domain=SSZipArchiveErrorDomain Code=-1 "failed to open zip file" UserInfo=0xad36430 {NSLocalizedDescription=failed to open zip file}
Also I tried other library... but the result is the same.
The zip file is made by server (so we have no control over this part.) but we know that they use gzip to create this file.
I have already used "search"... but with no luck.
One more important note. If I unzip this file on my mac, than zip it again and point "localFilePath" to this new file, all works fine!. Also, the server guy say that they use this ZIP in other apps with no problems at all.
Any advice where do I need to look?
Thanks
The code:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://......"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];

    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *localFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[filePath lastPathComponent]];
    NSString *unzipFolder = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"/unzipfolder"];

    NSLog(@"localFilePath: %@",localFilePath);
    NSLog(@"unzip folder: %@",unzipFolder);

    NSError *erro = nil;
    [SSZipArchive unzipFileAtPath:localFilePath toDestination:unzipFolder overwrite:YES password:nil error:&erro delegate:self];
    NSLog(@"Erro: %@",erro);
}];
[downloadTask resume];


text:
Q: How to apply a skybox ARTexture3D, in Android KudanAR SDK? I am working with the Android KudanSDK and cannot get an environment cube/ skybox working. The model appears black. Could anyone give me a hint? That would be nice.
I am not sure, if in the constructor of ARTexture3D the path to the png files (one for each cube side) shall be passed.
What I have done so far:
    String s = "wave.png";
    ARTexture3D environmentTex = new ARTexture3D(s,s,s,s,s,s);
    ARLightMaterial lightMaterial = new ARLightMaterial();
    lightMaterial.setDiffuse(0.5f, 0.5f, 0.5f);
    lightMaterial.setAmbient(1f, 1f, 1f);
    lightMaterial.setSpecular(0.5f, 0.5f, 0.5f);

    lightMaterial.setTexture(shoeTexture);
    lightMaterial.setCubeTexture(environmentTex);
    lightMaterial.setReflectivity(1f);
    List<ARMeshNode> allNodes =  modelNodeArray[0].getMeshNodes();
    for(ARMeshNode meshNode : allNodes){
        meshNode.setMaterial(lightMaterial);
    }

Somewhere in Kudan's iOS Wiki, there is also mentioned that a Light object (for example ARDirectionalLight) shall be added to the scene, too. But, for Android I cannot find this class.
Any idea is appreciated.
Thanks in advance.


text:
Q: TCPDF UTF-8 symbols not showing up Im using latest TCPDF version(5.9). But have some strange problems with encoding. I need Lithuanian language symbols like: ąčęėįšųūž. But get only few of it. Other remain like ?????
So what should I do ? I use default times font(it comes with TCPDF download).
Any help would be appreciated.

A: To use TCPDF with special characters like ฿, 포 or others
you need to use a unicode font:

*

*download the font here:
ftp://ftp.fu-berlin.de/unix/X11/multimedia/MPlayer/contrib/fonts/arialuni.ttf.bz2

*create a test pdf file and load this font into TCPDF
example:
$fontname = $pdf->addTTFfont('/var/www/app/images/fonts/arialuni.ttf', 'TrueTypeUnicode', '', 32);

*this will create the fonts like:

application/libraries/tcpdf/fonts/arialuni.ctg.z
  application/libraries/tcpdf/fonts/arialuni.php
  application/libraries/tcpdf/fonts/arialuni.z

*now you can set the new font with :
$pdf->SetFont('arialuni', '', 10.5);

*and now you can use special unicode characters like ฿ and more....
Source :
http://myridia.com/dev_posts/view/852

A: You u have problem to read character like Karnātaka from database and display like this        karn?taka  I mean "?" which we don't want then do following things :

*

*Define charset for the connection (mysql_set_charset()):
$con = mysql_connect("localhost","root","");

if (!$con)
{
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("database_name", $con) or die(mysql_error());
mysql_set_charset('utf8',$con);

*Use  $pdf->SetFont('DejaVuSerif', '', 10); instead of $pdf->SetFont('helvetica', 'B', 12);

*

*For TCPDF Library of the PHP read character like Rājasthān instead of R?jasth?n from database

A: TCPDF is quite tricky with utf8. Best way to achieve what you want is to embed the font in generated PDF file itself. You can use freeserif font from the TCPDF package, it contains all the utf8 symbols, shows absolutely any character of any language, but adds ~700kb to the output file. That's probably the easiest way to get symbols you need if file size doesn't matter.
You could also make your own font to embed, containing the characters you need. That's probably the best solution, keeping it universal and small in size, but is more complex.
Alternatively, you can relay on core fonts, which are taken from the system, and if not found, replaced by a substitute. This makes output file extremely light, but adds the necessity of font subsetting to obtain exotic chars. Personally I haven't had a success with this, so I still think embedding font is the best solution, which also happens to be more universal..

A: IIRC, you can define an encoding when you create a new font, as described here.  Otherwise, you have to use the encoding that was defined when the font was created.  It sounds like the fonts that ship with TCPDF all use WinAnsiEncoding... a.k.a. code page 1252.
Clunky, but effective.

A: With default TCPDF package tested dejavusans and freeserif and both fonts works with lithuanian characters. I also typed few russian characters and they worked too. I used this code to test it:
$this->pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$this->pdf->AddPage();
$this->pdf->SetFont('dejavusans', 'B', 20); // UTF8 fonts with lithuanian support: freeserif, dejavusans
$this->pdf->Write(0, 'ąžūčšęėųįĄŽŪČŠĘĖŲĮ Превед Кросавчег!', '', 0, 'C', true, 0, false, false, 0);

A: With dejavusans font it worked fine for both Russian and Latvian letters.

A: there is a font included in the CPDF core fonts - dejavusans, it shows all the lithuanian characters. Just add the following:
$pdf->setHeaderFont(Array('dejavusans', '', 10, '', false));
$pdf->setFooterFont(Array('dejavusans', '', 8, '', false));
$pdf->SetFont('dejavusans', '', 10, '', false);

A: Set the $unicode parameter on the TCPDF constructor to false and the $encoding parameter to 'ISO-8859-1' or some other character map.
This will help you:
Default for UTF-8 unicode:
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

Example of constructor for European charset:
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, false, 'ISO-8859-1', false);

A: Set font to freeserif it will work.
I tested.
$pdf->SetFont('freeserif', '', 14, '', true);

A: Just discovered this same situation when trying to render Romanian text using the default Helvetica font. In doing some investigation I found that the tcpdf library treats it's default fonts (referred to as "core" fonts) as Latin1 characters so even if you tell it to use UTF-8 encoding and set the unicode flag, it will literally translate your text to Latin1 equivalents prior to rendering. The default behavior of the library is, if it finds a Latin1 equivalent, to translate each character that it can find an equivalent for otherwise it translates the character as '?'.
This can be found inside the TCPDF class in the following method chain:
Write() -> Cell() -> getCellCode() -> _escapetext().
Inside of _escapetext() you can see it is checking for $this->isunicode then checking the selected font to see if it's type is core|TrueType|Type1. If it is, it will take the string an "latinize" it for you by way of the UTF8ToLatin1() method. This is where the '?' translations are taking place.
My recommendation would be to use a custom unicode font (like Deja Vu Sans) that is similar to the default font you are after. That worked for me in my current situation.

A: With me it was a font problem. I used the font timesand my local multibyte chras wouldn't show up properly. When I changed it to freeserif they were working normally :)

A: For this use the following code of the parameter TCPDF constructor
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, false, 'ISO-8859-1', false);

It will help you.

A: $fontname = $pdf->addTTFfont('C:\xampp\htdocs\copyshop\fonts\07-TH-Sarabun-PSK\THSarabun.ttf', 'TrueTypeUnicode', '', 32);
    $pdf->SetFont($fontname, '', 16,'',FALSE); //Working

A: I had the same issue with Romanian characters and the problem wasn't the encoding, LC_CTYPE or other setting from TCPDF, but the font I used.
I mention that I used TWIG templating with Courier font.
You can try to change your font to freeserif

A: change the font to show normally ₹ and Lithuanian symbols
$pdf->SetFont('cid0cs', '', 12);

A: To faced this issue and I had to use dejavusans font which is a UTF-8 Unicode font. This help fix the encoding issue when render UTF-8 words like ąčęėįšųūž.
However, I was using helvetica font which is standard ASCII font, and changing document's font to dejavusans make it ugly.
To fix this I set two fonts to be loaded in the document and specified a part of the document to use dejavusans font
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

/*
 ......
 set margins and other options
 ......
 */

// Set font
// dejavusans is a UTF-8 Unicode font,
// if you only need to print standard ASCII chars,
// you can use core fonts like helvetica or times to reduce file size.
$pdf->SetFont('dejavusans', '', 12, '', true);
$pdf->SetFont('helvetica', '', 12, '', true);

$html = '
' . $clientName . '

' . $clientAddress . '
';

// Print text using writeHTMLCell()
$pdf->writeHTMLCell($w=0, $h=0, $x='', $y='', $html, $border=0, $ln=1, $fill=0, $reseth=true, $align='', $autopadding=true);

$pdf->Output('invoice.pdf', 'I');


text:
Q: Do we use static notifications or dynamic notifications for getting usernames and avatars from the server? I have read a ton on designing static/dynamic notifications. Everyone says use dynamic for more personalized data and try to stick with static since WatchOS often falls back to static anyway on low battery etc.
What I'm not clear about is if I can use a static notification for the same category "New Message" but each time changing the senders' names in the body to match the user object from the server.

*

*You have a new message from Karen

*You have a new message from Dave

*You have a new message from Jessica

*You have a new message from Tom

Also their avatar. Can each notification use a different user avatar from the server? With JSON payload we can get any data and populate any WatchKit ImageView / UILable even with a Static Notification?

In case I need to use a dynamic notification I have already created a subclass of WKUserNotificationInterfaceController for the dynamic notification controller with this method for testing dictionaries.
How would I populate the WK objects with the usernames/avatars?
override func didReceiveRemoteNotification(remoteNotification: [NSObject : AnyObject], withCompletion completionHandler: ((WKUserNotificationInterfaceType) -> Void)) {

    NSLog("remoteNotification Dictionary %@",remoteNotification);
    completionHandler(.Custom) // same as completionHandler(WKUserNotificationInterfaceType.Custom)

}

A: There is no need to be dynamic from my point of view.Let say we got the payload data like that :
{
     "img_url" : "exmaple.com/ssd.jpg",
     "sender" : "Kelvin",
     "type" : "(your type name)"
}

You can control your type with "New-Message" or "Video-Call" or "Reply".When you parse type,check it and show the user on UI.
If you are going to parse the payload data from server,what you will parse is the following key "imgu_url,sender,type" every time the notification arrive and you will get the data from them,right?Most notifications go with that.I mean static.So,what important to do is setting the common key name for your requirement.There is no need to be dynamic.
Try read this : Wat is the difference between static notification and dynamic notification?
What you should do is get the data and update the UI
APNS FORMAT AND BACKEND GUIDE :
Here what you should send exactly like that to iOS devices.If you don't set the payload like this format that was set by apple,you wont receive any notifications to your iDevices.
APNS Payload Data Format
And there is no need to create multiple apns file,try read their documentation on their server side script.Learn how they sent notifications to specific iOS devices : One Signal or you can learn from Parse too which become open-source now.
I am not a backend developer.So,I can't help you with that.Like I said,you can send the payload data base on what your application needs.


text:
Q: Image not found error while building and linking a c library that came with a Python project I downloaded this "pure Python" project which has a custom C library included.  However, when I ran the suggested make commands I get an "Image not found" error during execution of the test script that uses that library.
I rarely work with C so I'm not familiar with the build process. Is there another step I was supposed to do to build this library or should this single line do it all?
(torch) mymachine:zvm myusername$ make && make check
gcc -ansi -g -Wall -fPIC    -c -o cgfref.o cgfref.c
gcc -ansi -g -Wall -fPIC    -c -o cggestal.o cggestal.c
gcc -ansi -g -Wall -fPIC    -c -o cgmisc.o cgmisc.c
gcc -ansi -g -Wall -fPIC    -c -o cgstream.o cgstream.c
gcc -ansi -g -Wall -fPIC    -c -o cgstyle.o cgstyle.c
gcc -ansi -g -Wall -fPIC    -c -o cgwindow.o cgwindow.c
gcc -ansi -g -Wall -fPIC    -c -o cgschan.o cgschan.c
gcc -ansi -g -Wall -fPIC    -c -o cgdate.o cgdate.c
gcc -ansi -g -Wall -fPIC    -c -o cgunicod.o cgunicod.c
gcc -ansi -g -Wall -fPIC    -c -o main.o main.c
gcc -ansi -g -Wall -fPIC    -c -o gi_dispa.o gi_dispa.c
gcc -ansi -g -Wall -fPIC    -c -o gi_blorb.o gi_blorb.c
gcc -ansi -g -Wall -fPIC    -c -o gi_debug.o gi_debug.c
gcc -ansi -g -Wall -fPIC    -c -o cgblorb.o cgblorb.c
gcc -ansi -g -Wall -fPIC    -c -o glkstart.o glkstart.c
gcc -shared -o libcheapglk.so cgfref.o cggestal.o cgmisc.o cgstream.o cgstyle.o cgwindow.o cgschan.o cgdate.o cgunicod.o main.o gi_dispa.o gi_blorb.o gi_debug.o cgblorb.o glkstart.o
.................EEEEEEEEE
======================================================================
ERROR: testGestaltCharInputProvidesValidInformation (tests.glk_tests.CheapGlkTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/myusername/zvm/tests/glk_tests.py", line 141, in setUp
    self.glkLib = glk_test_program.CheapGlkLibrary()
  File "/Users/myusername/zvm/tests/glk_test_program.py", line 26, in __init__
    glk.GlkLib.__init__(self, lib_name)
  File "/Users/myusername/zvm/zvm/glk.py", line 299, in __init__
    self._dll = ctypes.CDLL(lib_name)
  File "/Users/myusername/opt/anaconda3/envs/torch/lib/python3.9/ctypes/__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: dlopen(cheapglk/libcheapglk, 6): image not found

... (more similar errors)

Here is the entire Makefile:
all:
    @(cd cheapglk && make)

clean:
    @(cd cheapglk && make clean)

check:
    @python3 run_tests.py

Here is the line from glk.py where the error occurred:
    def __init__(self, lib_name):
        """Instantiates the instance, binding it to the given shared
        library (which is referenced by name)."""

        self._dll = ctypes.CDLL(lib_name)

I notice there is no libcheapglk.a file in the library files.  Should there be?  I did try creating one using ar rcs libcheapglk.a ... but it did not solve the problem.
My system:

*

*Mac OS X 10.15 Catalina

*Python 3.9.12

*gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.29)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin


text:
Q: 90 degree phase shift I need to use a clock signal of 50% duty cycle of 2.5MHZ and I should make a circuit which phase shifts it to 90 degrees.

So now I have four signals...( **  PHASE SHIFT WITH RESPECTIVE CLOCK SIGNAL)
→ signal 3 ( 180 DEG  phase shifted) is just the inversion of the signal 1 ( 0 DEG  phase shifted)
→ signal 4 ( 90 DEG  phase shifted) is just the inversion of the signal 2 ( 90 DEG  phase shifted)
I could easily do with D flip flops, processors, but I'm interested in just using basic components (transistors, resistors, gates, etc.)

In the end, I solved it with flipflops. thank you everyone

A: You can generate fixed delays using R-C circuits and voltage comparators, like this:

simulate this circuit – Schematic created using CircuitLab
Adjust R1 and/or C1 to get the delay you want, which is 100 ns in this case. R2 and R3 establish a switching point at exactly Vcc/2, which is important in order to get equal delays on the rising and falling edges.
Note that you can get a 1% resistor with the value of 143 Ω, but then the overall accuracy of your delay would depend on the precision of the capacitor.

A: Think about this: a flip-flop or any other digital circuit needs an event (a signal changes state) to change the output. What are the "events" of your input clock? I only see the 0=>1 and 1=>0 events. Your outputs need an additional event "exactly in the middle" of the clock events. Is there a signal for that? So is what you want going to be possible with some flip-flops? If you can pull it off then please share because then I've been doing this wrong for the past 25 years!
With "only basic components" you can make a poly phase filter but that only works for sinusoidal signals. That's probably not what you're looking for.
You could generate the extra events you need by frequency multiplying the clock using a Phase Locked Loop. You could make 10 MHz from the 2.5 MHz. Then deriving the wanted signals is easy using some frequency divider logic circuit. That will be a lot more than some "basic components".

A: Phase shifting a square wave by a fixed amount is equivalent to introducing an equivalent fixed group delay. Applying the Fourier properties to an input \$y(t)\$ yields
$$\mathcal{F}[y(t-\tau)] = e^{-j2\pi f\tau}Y(f).$$
Hence a time delay results in linear phase shift in the frequency domain. You can achieve this with a Bessel filter or any similar filter with a linear phase response.

source
You may need to fiddle with the transfer function a bit to get the required group delay. Alternatively just use a PLL and preserve your sanity. There's a reason they were invented.


text:
Q: let docker bridge connect vlan interface Pre-Requisites:
sudo ip link add link eth0 name eth0.100 type vlan id 101

problem:
I want to start openvpn with docker in container, this step is easy:
sudo docker run -v $OVPN_DATA:/etc/openvpn -p 1194:1194/udp --privileged -e DEBUG=1 kylemanna/openvpn
Then I need to let container can continue route package to eth0.100, after openvpn recieved remote client data.
There is my idea about it, but not working all.

1:
First create bridge:
docker network create bridge vpn_bridge
Then start container with vpn_bridge
sudo docker run --net=vpn_bridge  -v $OVPN_DATA:/etc/openvpn -p 1194:1194/udp --privileged -e DEBUG=1 kylemanna/openvpn
Finally, I find can't join the vlan interface to the vpn_bridge

2:
Use macvlan:
sudo docker network create -d macvlan \
    --subnet=192.168.100.0/24 \
    --gateway=192.168.100.1  \
    -o parent=eth0.1000 pub_net
Then start container with pub_net:
sudo docker run --net=vpn_bridge  -v $OVPN_DATA:/etc/openvpn -p 1194:1194/udp --privileged -e DEBUG=1 kylemanna/openvpn
Although container join vlan, but I found can't connect the container's openvpn server even in local host.

Is there anybody can give me more good way (ps: I already use traditional way solve it that use linux's default bridge)


text:
Q: OnProvideAssistDataListener example Can someone please provide an example for a real case where I might need to use OnProvideAssistDataListener. I can't seem to wrap my head around it. I look at the source code, and then I look online. Someone online says

Application.OnProvideAssistDataListener allows to place into the
  bundle anything you would like to appear in the
  Intent.EXTRA_ASSIST_CONTEXT part of the assist Intent

I have also been reading through the Intent Docs.

A: There is an Now On Tap functionality implemented by Google. By long pressing the Home Button, you will get some  information displayed on the screen.  The information you get depends on what you're viewing on your screen at that time. (for eg: Music app displays information about music on the screen).
To provide additional information to the assistant, your app provides global application context by registering an app listener using registerOnProvideAssistDataListener() and supplies activity-specific information with activity callbacks by overriding onProvideAssistData() and onProvideAssistContent().
Now when the user activates the assistant, onProvideAssistData() is called to build a full ACTION_ASSIST Intent with all of the context of the current application represented as an instance of the AssistStructure. You can override this method to place anything you like into the bundle to appear in the EXTRA_ASSIST_CONTEXT part of the assist intent.
In the example below, a music app provides structured data to describe the music album that the user is currently viewing:
@Override
public void onProvideAssistContent(AssistContent assistContent) {
  super.onProvideAssistContent(assistContent);

  String structuredJson = new JSONObject()
       .put("@type", "MusicRecording")
       .put("@id", "https://example.com/music/recording")
       .put("name", "Album Title")
       .toString();

  assistContent.setStructuredData(structuredJson);
}

For more info refer https://developer.android.com/training/articles/assistant.html


text:
Q: UIPickerView select and hide How do you make a UIPickerView act like the one with a webview wherein there is a drop down selection box and instead of dropping down like usual websites do, the iphone makes it into a UIPickerView with all the selections in. When you select one, a check becomes visible beside your selection and changes the value of the drop box. And how do you put the "Done" button on top of the UIPickerView to dismiss the UIPickerView?
I already know that [pickerview setHidden:YES] is the method to use to hide the pickerview. I just don't know how to include the "Done" button in the UIPickerView.
Regards,
Chris

A: The "Done" button is placed in UIToolBar.
Use the below method of UIToolBar for adding the "Done" buttons.
- (void)setItems:(NSArray *)items animated:(BOOL)animated {

    UIToolbar*  mypickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
    mypickerToolbar.barStyle = UIBarStyleBlackOpaque;
    [mypickerToolbar sizeToFit];

    NSMutableArray *barItems = [[NSMutableArray alloc] init];

    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barItems addObject:flexSpace];

    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)];
    [barItems addObject:doneBtn];

    [mypickerToolbar setItems:barItems animated:YES];

}

A: This piece of code will slide out a picker view as keyboard and attached a done button on top of it. Basically, you want to set a inputAccessoryView with your input field.
You should call this method on a touch down event for your input field.
- (IBAction)showYourPicker:(id)sender {

// create a UIPicker view as a custom keyboard view
UIPickerView* pickerView = [[UIPickerView alloc] init];
[pickerView sizeToFit];
pickerView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
pickerView.delegate = self;
pickerView.dataSource = self;
pickerView.showsSelectionIndicator = YES;
self.yourPickerView = pickerView;  //UIPickerView

yourTextField.inputView = pickerView;

// create a done view + done button, attach to it a doneClicked action, and place it in a toolbar as an accessory input view...
// Prepare done button
UIToolbar* keyboardDoneButtonView = [[UIToolbar alloc] init];
keyboardDoneButtonView.barStyle = UIBarStyleBlack;
keyboardDoneButtonView.translucent = YES;
keyboardDoneButtonView.tintColor = nil;
[keyboardDoneButtonView sizeToFit];

UIBarButtonItem* doneButton = [[[UIBarButtonItem alloc] initWithTitle:@"Done"
    style:UIBarButtonItemStyleBordered target:self
    action:@selector(pickerDoneClicked:)] autorelease];

[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];

// Plug the keyboardDoneButtonView into the text field...
yourTextField.inputAccessoryView = keyboardDoneButtonView;

[pickerView release];
[keyboardDoneButtonView release];
}

Finally, your Done button calls the "pickerDoneClicked" method, where you should add
[yourTextField resignFirstResponder]; which will hide the picker view.


text:
Q: Positioning HTML5 video player controls I am working with the HTML5 native video player in Chrome and have an issue. The controls seem to float underneath the video itself, something which is acceptable on desktop but get quite visible on mobile devices. Is there any way to have it stay inside the video frame?
I don't really know where to begin as I can't find any way to target the controls specifically.
  #movie-player {
  padding: 0.7em;
  margin: 0 auto;
  width: -webkit-calc((100% - 3em) / 1);
  width: calc((100% - 3em) / 1);
  max-width: 600px;
  border: 1px solid #e7e7e7;
}

        <figure>
                    <video class="fadescript" id="movie-player" width="640" height="360" preload controls>
                        <source src="video/explainervideo.mp4" />
                        <source src="video/explainervideo.ogv" />
                        <source src="video/explainervideo.webm" />
                    </video>
        </figure>

Thanks

A: You can style the controls for the <video> element using Shadow DOM. It has very limited browser support at this time, but you say you are doing this in Chrome, and happily, Chrome is supported.
Sara Soueidan wrote an article about how to use Shadow DOM to hide video controls. You can use that as a starting point. It would seem that you are looking to style the video::-webkit-media-controls and/or its descendants.


text:
Q: Apply Math operations on loaded data inside PGF/Tikz plot for each column I am new to LaTeX plotting system and I have got lost in a problem,
I have a csv file which has 11 columns, and I want to plot columns 2 to 11 vs column 1. So I do it as given in the following code (Taken from stackexchange, Thanks). My question is as follows,
I want to divide x column by the maximum value in the x column and divide each y column by the maximum value in all y columns,
\documentclass{article}
\usepackage{pgfplots}
\usepackage{filecontents}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
width=1.0\textwidth,
scale only axis,
xlabel={$x$},
ylabel={Column Data}]

% Graph column 0 versus column 1
\addplot table[x index=0 ,y index=1,col sep=comma] {Axial.csv};
\addlegendentry{200}% y index+1 since humans count from 1

% Graph column 0 versus column 2
\addplot table[x index=0,y index=2,col sep=comma] {Axial.csv};
\addlegendentry{500}

% Graph column 0 versus column 3
\addplot table[x index=0,y index=3,col sep=comma] {Axial.csv};
\addlegendentry{1000}

% Graph column 0 versus column 4
\addplot table[x index=0,y index=4,col sep=comma] {Axial.csv};
\addlegendentry{2000}

% Graph column 0 versus column 5
\addplot table[x index=0,y index=5,col sep=comma] {Axial.csv};
\addlegendentry{3000}

% Graph column 0 versus column 6
\addplot table[x index=0,y index=6,col sep=comma] {Axial.csv};
\addlegendentry{4000}

% Graph column 0 versus column 7
\addplot table[x index=0,y index=7,col sep=comma] {Axial.csv};
\addlegendentry{5000}

% Graph column 0 versus column 8
\addplot table[x index=0,y index=8,col sep=comma] {Axial.csv};
\addlegendentry{6000}

% Graph column 0 versus column 9
\addplot table[x index=0,y index=9,col sep=comma] {Axial.csv};
\addlegendentry{7000}

% Graph column 0 versus column 10
\addplot table[x index=0,y index=10,col sep=comma] {Axial.csv};
\addlegendentry{8000}

\end{axis}
\end{tikzpicture}
\end{document}

I would really appreciate if you help me with this issue.
Best

A: OK, here we go then. I created a macro that find the minimal and maximal values of a column. The starting point was this answer but I modified it somewhat. And I would not at all be surprised if this function was already built in somewhere, at least internally it must be because of the way point meta works. Then I created new columns that emerge by the original ones by dividing by the maximal value, as requested. To this end I used copy & paste since this was quicker than fighting with expansion issues that happen in my naive attempts to do that in a loop. And I changed the code such that the csv file is only read once. Here's the code.
\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}

\newcommand{\findminmax}[1]{% https://tex.stackexchange.com/a/107364/121799
  % Count rows
  \pgfplotstablegetrowsof{\mytable}
  \pgfmathtruncatemacro{\numrows}{\pgfplotsretval-1}
  \typeout{\numrows\space rows}
  % Initiate max value
  \pgfplotstablegetelem{0}{#1}\of{\mytable}
  \pgfmathtruncatemacro{\mymax}{\pgfplotsretval}
  \pgfmathtruncatemacro{\mymin}{\pgfplotsretval}
  \typeout{initially:\space\mymin}
  \pgfplotsinvokeforeach {1,...,\numrows}{
    \pgfplotstablegetelem{##1}{#1}\of{\mytable}
    \pgfmathsetmacro{\mymax}{max(\pgfplotsretval,\mymax)}
    \pgfmathsetmacro{\mymin}{min(\pgfplotsretval,\mymin)}
   }
  \let\ymax=\mymax%
  \let\ymin=\mymin%
}

\begin{document}
\pgfplotstableread[col sep=comma,header=true]{%
Axial.csv}\mytable

\findminmax{0}
\let\xmax=\ymax
\pgfplotstablecreatecol[expr={(\thisrow{0})/\xmax}]{newx}{\mytable}
% \pgfplotsinvokeforeach{1,2,...,10}{\findminmax{#1}
% \typeout{#1:\ymin-\ymax}
% \pgfplotstablecreatecol[expr={(\thisrow{#1})/\ymax}]{new#1}{\mytable}
% }
%
% yes, the following is very ugly, but faster than fumbling with the expansion
% magic that comes with pgfplots(table), at least for non-wizards like me ;-)
\findminmax{1}
\pgfplotstablecreatecol[expr={(\thisrow{1})/\ymax}]{new1}{\mytable}
\findminmax{2}
\pgfplotstablecreatecol[expr={(\thisrow{1})/\ymax}]{new2}{\mytable}
\findminmax{3}
\pgfplotstablecreatecol[expr={(\thisrow{1})/\ymax}]{new3}{\mytable}
\findminmax{4}
\pgfplotstablecreatecol[expr={(\thisrow{1})/\ymax}]{new4}{\mytable}
\findminmax{5}
\pgfplotstablecreatecol[expr={(\thisrow{1})/\ymax}]{new5}{\mytable}
\findminmax{6}
\pgfplotstablecreatecol[expr={(\thisrow{1})/\ymax}]{new6}{\mytable}
\findminmax{7}
\pgfplotstablecreatecol[expr={(\thisrow{1})/\ymax}]{new7}{\mytable}
\findminmax{8}
\pgfplotstablecreatecol[expr={(\thisrow{1})/\ymax}]{new8}{\mytable}
\findminmax{9}
\pgfplotstablecreatecol[expr={(\thisrow{1})/\ymax}]{new9}{\mytable}
\findminmax{10}
\pgfplotstablecreatecol[expr={(\thisrow{1})/\ymax}]{new10}{\mytable}

\begin{tikzpicture}
\begin{axis}[
width=1.0\textwidth,
scale only axis,
xlabel={$x$},
ylabel={Column Data}]

% Graph column 0 versus column 1
\addplot table[x=newx ,y=new1,col sep=comma] \mytable;
\addlegendentry{200}% y index+1 since humans count from 1

% Graph column 0 versus column 2
\addplot table[x=newx,y=new2,col sep=comma] \mytable;
\addlegendentry{500}

% Graph column 0 versus column 3
\addplot table[x=newx,y=new3,col sep=comma] \mytable;
\addlegendentry{1000}

% Graph column 0 versus column 4
\addplot table[x=newx,y=new4,col sep=comma] \mytable;
\addlegendentry{2000}

% Graph column 0 versus column 5
\addplot table[x=newx,y=new5,col sep=comma] \mytable;
\addlegendentry{3000}

% Graph column 0 versus column 6
\addplot table[x=newx,y=new6,col sep=comma] \mytable;
\addlegendentry{4000}

% Graph column 0 versus column 7
\addplot table[x=newx,y=new7,col sep=comma] \mytable;
\addlegendentry{5000}

% Graph column 0 versus column 8
\addplot table[x=newx,y=new8,col sep=comma] \mytable;
\addlegendentry{6000}

% Graph column 0 versus column 9
\addplot table[x=newx,y=new9,col sep=comma] \mytable;
\addlegendentry{7000}

% Graph column 0 versus column 10
\addplot table[x=newx,y=new10,col sep=comma] \mytable;
\addlegendentry{8000}

\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: How do you parse both a file and JSON data out of one HTTP request with Go? I am stuck trying to figure out how to parse both a PDF document and JSON data out of one http request form from an Angularjs front end.
The request payload is
HTTP Request
Content-Disposition: form-data; name="file"; filename="Parent Handbook.pdf"
Content-Type: application/pdf
Content-Disposition: form-data; name="doc"
{"title":"test","cat":"test cat","date":20142323}
The "file" is the pdf and "doc" is the json data I want to parse.
My handler can parse and save the file just fine but fails to get anything out of the Json. Any ideas?
func (s *Server) PostFileHandler(w http.ResponseWriter, r *http.Request) {
    const _24K = (1 << 20) * 24
    err := r.ParseMultipartForm(_24K)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    doc := Doc{}
    jsonDecoder := json.NewDecoder(r.Body)
    fmt.Println(r.Body)
    err = jsonDecoder.Decode(&doc)
    if err != nil {
        fmt.Println(err.Error())
    }
    fmt.Println(doc.Title, doc.Url, doc.Cat, doc.Date)
    doc.Id = len(docs) + 1
    err = s.db.Insert(&doc)
    checkErr(err, "Insert failed")

    // files := m.File["myFile"]
    for _, fheaders := range r.MultipartForm.File {
        for _, hdr := range fheaders {
            var infile multipart.File
            infile, err = hdr.Open()
            // defer infile.Close()
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
            doc.Url = hdr.Filename
            fmt.Println(hdr.Filename)
            var outfile *os.File
            outfile, err = os.Create("./docs/" + hdr.Filename)
            // defer outfile.Close()
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
            _, err = io.Copy(outfile, infile)
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }

        }
    }
    s.Ren.JSON(w, http.StatusOK, &doc)
    // http.Error(w, "hit file server", http.StatusOK)
}

A: In your example you're trying to read r.Body as if it was stripped out of PDF part of the request, but it isn't. You need to process separately both parts, PDF and JSON.
Use http.(*Request).MultipartReader() for that.
r.MultipartReader() will return you mime/multipart.Reader object, so you can iterate over parts with r.NextPart() function and process each part separately.
So your handler function should be like this:
func (s *Server) PostFileHandler(w http.ResponseWriter, r *http.Request) {
    mr, err := r.MultipartReader()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    doc := Doc{}
    for {
        part, err := mr.NextPart()

        // This is OK, no more parts
        if err == io.EOF {
            break
        }

        // Some error
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        // PDF 'file' part
        if part.FormName() == "file" {
            doc.Url = part.FileName()
            fmt.Println("URL:", part.FileName())
            outfile, err := os.Create("./docs/" + part.FileName())
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
            defer outfile.Close()

            _, err = io.Copy(outfile, part)
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
        }

        // JSON 'doc' part
        if part.FormName() == "doc" {
            jsonDecoder := json.NewDecoder(part)
            err = jsonDecoder.Decode(&doc)
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
            fmt.Println(doc.Title, doc.Url, doc.Cat, doc.Date)
        }
    }

    doc.Id = len(docs) + 1
    err = s.db.Insert(&doc)
    checkErr(err, "Insert failed")

    s.Ren.JSON(w, http.StatusOK, &doc)
}


text:
Q: How to give myself maps that have already been created? I created a bunch of maps, copied the map numbers and coordinates, then went to put them in item frames.  But then Minecraft crashed and when I came back the maps were gone.  When I try to create a new map it starts above the last map number I created, so it seems the game does know about them.
How can I give myself these maps by numbers so I don't have to go through all the work of re-creating them (not to mention duplicate map numbers for the same coordinates)?
I tried:
/give @s filled_map 1 0 {"map":170}

But I got the error

Component 'map' was not an object.

I also tried upper-casing "Map" but got a similar error.
I also tried:
/give @s filled_map 1 170

But got the error:

Invalid map data provided.


text:
Q: Facebook beta SDK for Unity 7.0.1 Android issue I'm testing the new Facebook SDK 7.0.1 beta, and seems that the .jar file is missing from the distribution. As soon as I try to use the SDK on Android, I get a java.lang.exception class not found com.facebook.blah.blah, and checking the package indeed, I cannot find a .jar file while it was included in the previous releases. Any hint  ?

A: I have the same issue here. I added facebooksdk.jar from 6.2.2 just to test how far it could go. FB.init worked fine, but as expected other FB calls failed.


text:
Q: MSGraph - Is it possible to slice an attribute called from an API? I am using MGT (Microsoft Graph Toolkit) and was wondering if it was possible to slice an attribute.
Here is my code:
                <mgt-person person-query="me">
                  <template>
                   <div>
                    {{person.displayName}}
                   </div>
                  </template>
                <template data-type="loading">
                   Loading
                </template>
                 </mgt-person>

person.DisplayName Returns : "Smith, John"
How do just get the first name from this? I want to slice out the last name and the ",".
I know {{person.givenName}} will give you the first name but for various reasons, some users have a different name in their display name they prefer to be called by.
Please help.

A: You could use js to achieve this:
person.displayName.split(",")[0]


text:
Q: I want to get or set data to each cell of DataGridView based on combobox selection Please find my code , I need to know the relationship between combobox selection and datagridview. Basically if I set my area selection only those related to the Area shall be display not the whole database as I am getting now. Thanks.
        private void RTUModification_Load(object sender, EventArgs e) {
        //Select cell where checkbox to be display
        Rectangle rect = this.rtumodDGV1.GetCellDisplayRectangle(0, -1, true);
        chkbox.Size = new Size(18, 18);

        //set position of header checkbox where to places
        rect.Offset(4, 2);
        chkbox.Location = rect.Location;

        chkbox.CheckedChanged += rtucheckBoxCheckChanged;

        //Add CheckBox control to datagridView
        this.rtumodDGV1.Controls.Add(chkbox);

        // Create new DataTable instance
        dtDataTable = new System.Data.DataTable();
        if (null == dtDataTable)
        {
            MessageBox.Show("Insufficient memory.", "ERROR");
        }
        //load the datable and fill them with value
        strErrorMsg = Utilities.OpenSQLConnection(out m_SqlConn, true, false);   //load normal database
        if (false == string.IsNullOrEmpty(strErrorMsg))
        {
            MessageBox.Show(strErrorMsg, "SQL connection ERROR");
        }

        SqlDataAdapter sqlAdapter = null;
        strSelectCmd = "SELECT Area_ID, StationId, SystemId, CCNumber, LineNumber, RTUNumber, SRTUNumber, Description, SDescription FROM RTU_ADDRESS";
        SqlCommand sqlCmd = new SqlCommand();
        sqlCmd.Connection = m_SqlConn;
        sqlCmd.CommandText = strSelectCmd;
        sqlAdapter = new SqlDataAdapter();
        sqlAdapter.SelectCommand = sqlCmd;
        strErrorMsg = Utilities.FillDataTable(m_SqlConn, strSelectCmd, dtDataTable);
        if (string.IsNullOrEmpty(strErrorMsg) == false)
        {
            MessageBox.Show("Failed to retrieve information from database.", "ERROR");
            dtDataTable.Dispose();
            Utilities.CloseAndDisposeSQLConnection(m_SqlConn);
        }
        int iRetrievedNoOfRecords = dtDataTable.Rows.Count;
        if (iRetrievedNoOfRecords > 0)
        {

            for (int i = 0; i < iRetrievedNoOfRecords; i++)
                this.rtumodcomboBox.Items.Add((string)dtDataTable.Rows[i]["Area_ID"]);
        }
        strErrorMsg = Utilities.ExecuteSQLCommand(m_SqlConn, strSelectCmd);
        if (string.IsNullOrEmpty(strErrorMsg) == false)
        {
            MessageBox.Show(this, "Error!Loading into RTU datagrid");
        }

        //load the datagridview header
        rtumodDGV1.DataSource = dtDataTable;
    }

A: Here's the sample code that you might need.
  strSelectCmd = "SELECT Area_ID, StationId, SystemId, CCNumber, LineNumber, RTUNumber, SRTUNumber, Description, SDescription FROM RTU_ADDRESS where Area_ID="+cbxMyCombox.SelectedIndex;

other options other SelectedIndex could be SelectedItem or SelectedValue . Depending upon what you are using. Which is unclear right now.


text:
Q: What is the interface tension between ordered and disordered phases of the Potts model? I read in these papers(1,2) the concept of interface tension. I can't understand its definition. I can hardly imagine there is some tension in a model. Any help will be appreciated.

A: Symmetric case
I'll first explain the definition of the surface tension between two ordered phases of the Potts model, since the symmetry between the phases simplifies things. I'll work in dimension $3$ to be specific, but everything generalizes in a straightforward way to other dimensions.
So consider the $q$-states Potts model at inverse temperature $\beta$ in the $3$-dimensional cube $\Lambda_n=\{-n,\ldots,n\}^3$. If we consider constant $1$-boundary condition, i.e., fix all spins along the external boundary $\partial\Lambda_n$ to be in state $1$, then the finite-volume free energy of the system can be written as
$$
F^1_{\Lambda_n}(\beta) = -\frac1\beta\ln Z^1_{\Lambda_n;\beta} = f_{\rm bulk}(\beta) |\Lambda_n| + f_{\rm wall}(\beta) |\partial\Lambda_n| + o(|\partial\Lambda_n|),
$$
where $Z^1_{\Lambda_n;\beta}$ is the partition function, $f_{\rm bulk}(\beta)$ is the bulk free energy per unit volume, $f_{\rm wall}(\beta)$ is the surface-order contribution per unit area resulting from the interaction of the system with the boundary and $o(|\partial\Lambda_n|)$ takes into account higher-order corrections to the finite-volume free energy.
Now, let us consider instead a boundary condition enforcing coexistence of two ordered phases. A natural way of doing that is to use the so-called Dobrushin boundary condition which is constructed as follows: consider a plane $\Pi$ going through $0$ (say, with a normal $\vec m$ making an angle at least $\pi/4$ with the vertical). We then fix each spin along $\partial\Lambda_n$ to state $1$ if it lies above (or on) the plane $\Pi$, and to state $2$ if it lies below. The finite-volume free energy then becomes
$$
F^{1,2}_{\Lambda_n}(\beta) = -\frac1\beta\ln Z^{1,2}_{\Lambda_n;\beta} = f_{\rm bulk}(\beta) |\Lambda_n| + f_{\rm wall}(\beta) |\partial\Lambda_n| + \sigma_\beta(\vec m) |\Pi_n| + o(|\partial\Lambda_n|),
$$
where $Z^{1,2}_{\Lambda_n;\beta}$ is the new partition function, $|\Pi_n|$ denotes the area of the intersection of $\Pi$ with the cube $[-n,n]^3$. The quantity $\sigma_\beta(\vec m)$ represents the contribution to the finite-volume free energy,  per unit area, coming from the presence of the interface between the two phases $1$ and $2$ induced by the boundary condition (each phase occupying, at the macroscopic scale, the corresponding half of the box, with a well-defined planar interface separating them). This is the surface tension between the two ordered phases. It is important to note the following:

*

*the bulk free energy $f_{\rm bulk}(\beta)$ is the same for both phases $1$ and $2$;

*the wall free energy $f_{\rm wall}(\beta)$ is coming from the local interaction between the phase and the wall and is thus also equal to the quantity we introduced in the case of a single phase.

These observations provide a way of extracting the surface tension from the finite-volume free energy:
$$
\sigma_\beta(\vec m) \approx \frac1{|\Pi_n|} \bigl(  F^{1,2}_{\Lambda_n}(\beta) - F^1_{\Lambda_n}(\beta)\bigr).
$$
This leads us to the following definition:
$$
\sigma_\beta(\vec m) = -\lim_{n\to\infty} \frac1{\beta|\Pi_n|} \ln\frac{Z^{1,2}_{\Lambda_n;\beta}}{Z^1_{\Lambda_n;\beta}}
$$
Remark:
The fact that this quantity really plays the role of the thermodynamic surface tension can be seen in many ways. The most compelling might be its appearance when studying equilibrium crystal shapes: consider, to keep things as simple as possible, an Ising model with fixed magnetization $m\in(-m^*(\beta),m^*(\beta))$. It can be shown that, with probability going to $1$ in the thermodynamic limit, the system spontaneously creates a droplet, of deterministic macroscopic shape, of one phase inside the other. The shape can be proved to be the one minimizing the surface tension (defined as above) among all sets of the required volume. More information on that can be found here and there.
Non-symmetric case
Your question is about the surface tension between an ordered phase and the disordered phase of the Potts model at the transition temperature. The situation in that case is made slightly more complicated due to the absence of symmetry between the two phases. It is still true that the bulk free energies of the ordered and disordered phases coincide, but it is no longer the case that the wall free energies coincide, so that we cannot cancel them as easily as we did above. Let me explain the trick used to solve this problem.
Consider a system with two coexisting phases $A$ and $B$, not necessarily related by symmetry. As above, we can write
$$
F^A_{\Lambda_n} = f_{\rm bulk} |\Lambda_n| + f^A_{\rm wall} |\partial\Lambda_n| + o(|\partial\Lambda_n|),
$$
$$
F^B_{\Lambda_n} = f_{\rm bulk} |\Lambda_n| + f^B_{\rm wall} |\partial\Lambda_n| + o(|\partial\Lambda_n|),
$$
$$
F^{A,B}_{\Lambda_n} = f_{\rm bulk} |\Lambda_n| + f^{A,B}_{\rm wall} |\partial\Lambda_n| + \sigma(\vec m) |\Pi_n| + o(|\partial\Lambda_n|),
$$
Now, the thing to observe is that $f^{A,B}_{\rm wall} = \tfrac12(f^A_{\rm wall} + f^B_{\rm wall})$ since each of the two phases is in contact with half of the boundary of the box. Therefore, one way of extracting the surface tension in that case is to use
$$
\sigma(\vec m) \approx \frac1{|\Pi_n|} \bigl(  F^{A,B}_{\Lambda_n} - \tfrac12 ( F^A_{\Lambda_n} + F^B_{\Lambda_n} )\bigr).
$$
This leads to the definition:
$$
\sigma(\vec m) = -\lim_{n\to\infty} \frac1{\beta|\Pi_n|} \ln\frac{Z^{A,B}_{\Lambda_n}}{\sqrt{Z^A_{\Lambda_n}Z^B_{\Lambda_n}}}.
$$
This applies readily to the ordered/disordered interface in the Potts model. The only thing to explain is what boundary condition to use to induce the disordered phase. It turns out that this role can be played by the free boundary condition, i.e., not putting any spins along the corresponding part of $\partial\Lambda_n$. So, for example, to induce an interface as above, you'd associate $1$-spins to boundary vertices located above the plane $\Pi$ and no spins to vertices located below.
Let me finish by giving you a couple of references about these things in the context you are interested with (but there are many): this one or that one.


text:
Q: Tangents to two sets Find all the affine tangents that are simultaneously tangent to the set $E$ and $H$: $$H=\{(x,y)\in \mathbb R^2:xy=-5\}, E=\{(x,y)\in \mathbb R^2:\frac{x^2}{9}+\frac{y^2}{4}=1\}$$
I know that when the line is tangent to the set A at point a: $T_aA=\{v:<grad(h(a)),v>=0\}$ but I don't know how to combine this condition for both sets $ E, H $ to find all tangents

A: Any tangent to the given ellipse is $$y=mx \pm \sqrt{9m^2+4}$$, insert this in the Eq. of hyperbola:$xy=-5$, to get
$$mx^2+\pm\sqrt{9m^2+4}x+5=0$$
For tangency we impose $B^2=4AC$, Then
$$9m^2+4=20m \implies m=2, 2/9$$
The tangents are $$y=2x\pm 2\sqrt{10},~~ y=2x/9\pm2\sqrt{10}/3.$$


text:
Q: Board Assembly with constraints I am doing this problem but I am completely new to Prolog and I have no idea how to do it.
Nine parts of an electronic board have square shape, the same size and each edge of every part is marked with a letter and a plus or minus sign. The parts are to be assembled into a complete board as shown in the figure below such that the common edges have the same letter and opposite signs. Write a planner in Prolog such that the program takes 'assemble' as the query and outputs how to assemble the parts, i.e. determine the locations and positions of the parts w.r.t. the current positions so that they fit together to make the complete board.

I have tried solving it and I have written the following clauses:
complement(a,aNeg).
complement(b,bNeg).
complement(c,cNeg).
complement(d,dNeg).
complement(aNeg,a).
complement(bNeg,b).
complement(cNeg,c).
complement(dNeg,d).
% Configuration of boards, (board,left,top,right,bottom)
conf(b1,aNeg,bNeg,c,d).
conf(b2,bNeg,a,d,cNeg).
conf(b3,dNeg,cNeg,b,d).
conf(b4,b,dNeg,cNeg,d).
conf(b5,d,b,cNeg,aNeg).
conf(b6,b,aNeg,dNeg,c).
conf(b7,aNeg,bNeg,c,b).
conf(b8,b,aNeg,cNeg,a).
conf(b9,cNeg,bNeg,a,d).

position(b1,J,A).
position(b2,K,B).
position(b3,L,C).
position(b4,M,D).
position(b5,N,E).
position(b6,O,F).
position(b7,P,G).
position(b8,Q,H).
position(b9,R,I).

assemble([A,B,C,E,D,F,G,H,I,J,K,L,M,N,O,P,Q,R]) :-
    Variables=[(A,J),(B,K),(C,L),(D,M),(E,N),(F,O),(G,P),(H,Q),(I,R)],
    all_different(Variables),
    A in 1..3, B in 1..3, C in 1..3, D in 1..3, E in 1..3,
    F in 1..3, G in 1..3, H in 1..3, I in 1..3, J in 1..3,
    K in 1..3, L in 1..3, M in 1..3, N in 1..3, O in 1..3,
    P in 1..3, Q in 1..3, R in 1..3,
    % this is where I am stuck, what to write next

I don't know even if they are correct and I am not sure how to proceed further to solve this problem.

A: Trivial with CLP(FD):
:- use_module(library(clpfd)).

board(Board) :-
    Board = [[A1,A2,A3],
             [B1,B2,B3],
             [C1,C2,C3]],
    maplist(top_bottom, [A1,A2,A3], [B1,B2,B3]),
    maplist(top_bottom, [B1,B2,B3], [C1,C2,C3]),
    maplist(left_right, [A1,B1,C1], [A2,B2,C2]),
    maplist(left_right, [A2,B2,C2], [A3,B3,C3]),
    pieces(Ps),
    maplist(board_piece(Board), Ps).

top_bottom([_,_,X,_], [Y,_,_,_]) :- X #= -Y.

left_right([_,X,_,_], [_,_,_,Y]) :- X #= -Y.

pieces(Ps) :-
    Ps = [[-2,3,4,-1], [1,4,-3,-4], [-3,2,4,-4],
          [-4,-3,4,2], [2,-3,-1,4], [-1,-4,3,2],
          [-2,3,2,-1], [-1,-3,1,2], [-2,1,4,-3]].

board_piece(Board, Piece) :-
    member(Row, Board),
    member(Piece0, Row),
    rotation(Piece0, Piece).

rotation([A,B,C,D], [A,B,C,D]).
rotation([A,B,C,D], [B,C,D,A]).
rotation([A,B,C,D], [C,D,A,B]).
rotation([A,B,C,D], [D,A,B,C]).

Example query and its result:
?- time(board(Bs)), maplist(writeln, Bs).
11,728,757 inferences, 0.817 CPU in 0.817 seconds
[[-3, -4, 1, 4], [-1, -2, 3, 4], [4, -4, -3, 2]]
[[-1, 4, 2, -3], [-3, 4, 2, -4], [3, 2, -1, -4]]
[[-2, 1, 4, -3], [-2, 3, 2, -1], [1, 2, -1, -3]]

This representation uses 1,2,3,4 to denote positive a,b,c,d, and -1,-2,-3,-4 for the negative ones.

A: This is only a tiny improvement to @mat's beautiful solution. The idea is to reconsider the labeling process. That is maplist(board_piece,Board,Ps) which reads (semi-procedurally):

For all elements in Ps, thus for all pieces in that order: Take one piece and place it anywhere on the board rotated or not.

This means that each placement can be done in full liberty. To show you a weak order, one might take: A1,A3,C1,C3,B2 and then the rest. In this manner, the actual constraints are not much exploited.
However, there seems to be no good reason that the second tile is not placed in direct proximity to the first. Here is such an improved order:
     ...,
     pieces(Ps),
     TilesOrdered = [B2,A2,A3,B3,C3,C2,C1,B1,A1],
     tiles_withpieces(TilesOrdered, Ps).

tiles_withpieces([], []).
tiles_withpieces([T|Ts], Ps0) :-
   select(P,Ps0,Ps1),
   rotation(P, T),
   tiles_withpieces(Ts, Ps1).

Now, I get
?- time(board(Bs)), maplist(writeln, Bs).
% 17,179 inferences, 0.005 CPU in 0.005 seconds (99% CPU, 3363895 Lips)
[[-3,1,2,-1],[-2,3,2,-1],[2,4,-4,-3]]
[[-2,1,4,-3],[-2,3,4,-1],[4,2,-4,-3]]
[[-4,3,2,-1],[-4,1,4,-3],[4,2,-3,-1]]

and without the goal maplist(maplist(tile), Board),
% 11,010 inferences, 0.003 CPU in 0.003 seconds (100% CPU, 3225961 Lips)

and to enumerate all solutions
?- time((setof(Bs,board(Bs),BBs),length(BBs,N))).
% 236,573 inferences, 0.076 CPU in 0.154 seconds (49% CPU, 3110022 Lips)
BBs = [...]
N = 8.

previously (@mat's original version) the first solution took:
% 28,874,632 inferences, 8.208 CPU in 8.217 seconds (100% CPU, 3518020 Lips)

and all solutions:
% 91,664,740 inferences, 25.808 CPU in 37.860 seconds (68% CPU, 3551809 Lips)

A: In terms of performance, the following is no contender to @false's very fast solution.
However, I would like to show you a different way to formulate this, so that you can use the constraint solver to approximate the faster allocation strategy that @false found manually:
:- use_module(library(clpfd)).

board(Board) :-
    Board = [[A1,A2,A3],
             [B1,B2,B3],
             [C1,C2,C3]],
    maplist(top_bottom, [A1,A2,A3], [B1,B2,B3]),
    maplist(top_bottom, [B1,B2,B3], [C1,C2,C3]),
    maplist(left_right, [A1,B1,C1], [A2,B2,C2]),
    maplist(left_right, [A2,B2,C2], [A3,B3,C3]),
    pieces(Ps0),
    foldl(piece_with_id, Ps0, Pss, 0, _),
    append(Pss, Ps),
    append(Board, Bs0),
    maplist(tile_with_var, Bs0, Bs, Vs),
    all_distinct(Vs),
    tuples_in(Bs, Ps).

tile_with_var(Tile, [V|Tile], V).

top_bottom([_,_,X,_], [Y,_,_,_]) :- X #= -Y.

left_right([_,X,_,_], [_,_,_,Y]) :- X #= -Y.

pieces(Ps) :-
    Ps = [[-2,3,4,-1], [1,4,-3,-4], [-3,2,4,-4],
          [-4,-3,4,2], [2,-3,-1,4], [-1,-4,3,2],
          [-2,3,2,-1], [-1,-3,1,2], [-2,1,4,-3]].

piece_with_id(P0, Ps, N0, N) :-
    findall(P, (rotation(P0,P1),P=[N0|P1]), Ps),
    N #= N0 + 1.

rotation([A,B,C,D], [A,B,C,D]).
rotation([A,B,C,D], [B,C,D,A]).
rotation([A,B,C,D], [C,D,A,B]).
rotation([A,B,C,D], [D,A,B,C]).

You can now use the "first fail" strategy of CLP(FD) and try the most constrained elements first. With this formulation, the time needed to find all 8 solutions is:
?- time(findall(t, (board(B), term_variables(B, Vs), labeling([ff],Vs)), Ts)).
2,613,325 inferences, 0.208 CPU in 0.208 seconds
Ts = [t, t, t, t, t, t, t, t].

In addition, I would like to offer the following contender for the speed contest, which I obtained with an extensive partial evaluation of the original program:
solution([[[-4,-3,2,4],[2,-1,-4,3],[2,-1,-3,1]],[[-2,3,4,-1],[4,2,-4,-3],[3,2,-1,-2]],[[-4,1,4,-3],[4,2,-3,-1],[1,4,-3,-2]]]).
solution([[[-3,-4,1,4],[-1,-2,3,4],[4,-4,-3,2]],[[-1,4,2,-3],[-3,4,2,-4],[3,2,-1,-4]],[[-2,1,4,-3],[-2,3,2,-1],[1,2,-1,-3]]]).
solution([[[-3,-2,1,4],[-3,-1,4,2],[4,-3,-4,1]],[[-1,-2,3,2],[-4,-3,4,2],[4,-1,-2,3]],[[-3,1,2,-1],[-4,3,2,-1],[2,4,-4,-3]]]).
solution([[[-3,1,2,-1],[-2,3,2,-1],[2,4,-4,-3]],[[-2,1,4,-3],[-2,3,4,-1],[4,2,-4,-3]],[[-4,3,2,-1],[-4,1,4,-3],[4,2,-3,-1]]]).
solution([[[-3,-1,4,2],[4,-3,-4,1],[2,-1,-4,3]],[[-4,-3,4,2],[4,-1,-2,3],[4,-3,-2,1]],[[-4,-3,2,4],[2,-1,-2,3],[2,-1,-3,1]]]).
solution([[[-1,-3,1,2],[2,-1,-2,3],[4,-3,-2,1]],[[-1,-4,3,2],[2,-4,-3,4],[2,-3,-1,4]],[[-3,2,4,-4],[3,4,-1,-2],[1,4,-3,-4]]]).
solution([[[-1,-4,3,2],[-3,-2,1,4],[-1,-3,1,2]],[[-3,-4,1,4],[-1,-2,3,4],[-1,-2,3,2]],[[-1,4,2,-3],[-3,4,2,-4],[-3,2,4,-4]]]).
solution([[[4,-4,-3,2],[2,-4,-3,4],[2,-3,-1,4]],[[3,2,-1,-2],[3,4,-1,-2],[1,4,-3,-4]],[[1,2,-1,-3],[1,4,-3,-2],[3,2,-1,-4]]]).

The 8 solutions are found very rapidly with this formulation:
?- time(findall(t, solution(B), Ts)).
19 inferences, 0.000 CPU in 0.000 seconds
Ts = [t, t, t, t, t, t, t, t].


text:
Q: flex reads EOF twice In the extremely simple example below, I want to read in the language of a single a and assure that no remaining characters come after.
File: example.y
%{
#include <stdio.h>
#include <ctype.h>
int yylex(void);
int yyerror(char *s);
%}

%token A
%token END
%token JUNK

%% /* Grammar Rules */
accept: A END { printf("language accepted!\n"); }
;
%%

File: example.in
%{
#include "ex.tab.h"
#define YY_NO_INPUT
%}
%option nounput
%%
a printf("A found\n"); return A;
<<EOF>> { printf("EOF found\n"); return END; }
. { printf("JUNK found\n"); return JUNK; }
%%

The results of compiling and running this program with the following test input file:
a

produces the following output:
A found

EOF found
language accepted!
EOF found
Error: syntax error

Because EOF is read twice, I think that's why the program is not accepting my input language. My question is, why is EOF being read twice and how do I stop it?
Also, doing the above without the EOF rule causes inputs such as
abbbb

to print the "accept" message but then immediately fail because of the excess input. All I want is either a pass or a fail which is why I'm trying to use EOF to verify I will have one result.

A: I was able to use the following solution to scan in an EOF with flex and pass it to Bison without getting caught up matching EOF a second time.
Make bison reduce to start symbol only if EOF is found
The solution involves using a start condition to read when an EOF is next without actually reading in EOF. Once the "initial" EOF is triggered (END can be sent to Bison), then EOF is really read-in and completes the flex/bison parse naturaully. At least that's my understanding of it.
Flex
%x REALLYEND                                              <--- declare start condition
%option noinput nounput
%%
"END"                   { return END; }
.                       { return TOK; }
<INITIAL><<EOF>>        { BEGIN(REALLYEND); return EOP; } <---- trigger start condition
<REALLYEND><<EOF>>      { return 0; }                     <---- trigger EOF
%%

Bison
%%
prog : END EOP { printf ("ok\n"); }; <-- can use EOP just like END in my example
%%

A: bison (and all yacc derivatives I know of except for lemon) will not reduce the start production unless it is followed by an EOF token. In effect, it modifies the grammar to something like this:
$accept: accept $end;
accept: A END {...}

Your END token is not the same as the built-in $end token. So bison will happily reduce the accept rule (and therefore trigger your printf, which seems to have a different message in your code than in your output, which suggests that they come from different versions of your code) but it will not reduce its own $accept rule, and consequently will report a syntax error.
It's certainly the case that flex is prepared to match <<EOF>> more than once. I believe it will continue to do so as long as you ask for more tokens, but I could be wrong; certainly, it will match twice. But that's not your problem. Your problem is that you're trying to force bison to do what it would do anyway, except that you've made it impossible for it to do that.
In short, let flex return 0 for EOF, which is what it wants to do, and trust bison to only accept input which is terminated by an EOF. That will make your code much simpler.
(The tricky part is actually recognizing a sentence which does not go to the end of the input; for example, if you are embedding one language inside another -- javascript or CSS inside of HTML, for example. In that case, you do have to play some games, and I believe that is why lemon does not insert the usual augmented start rule.)

A: The answer is 3 fold
1) You should likely for most cases allow your bison parser to handle the EOF. It will likely be the easiest way to go. But this is not always possible.
2) Handling the <<EOF>> built in flex rule has some special requirements (obligatory link to the manual).
3) A note on the point 1. If you are first find that you have a grammar that appears to require an end of file token of some kind that is ok (some variants of c require this) but it is considered bad form (some editors have settings to add newlines at the end of files which can cause conflicts).


text:
Q: SoapUI/Groovy - How to copy a node? I just want to use groovy script in SoapUI to copy a simple node and rename it. But I don't have any clue on how to do that.
The input xml is like that :
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>

      <aa>...</aa>

      <aa>...</aa>

      <bb>...</bb>

      <bb>..</bb>

  </soap:Body>

I just need for each  to copy <bb> to <bb2> :
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>

      <aa>...</aa>

      <aa>...</aa>

      <bb>...</bb>
      <bb2>...</bb2>

      <bb>..</bb>
      <bb2>...</bb2>

  </soap:Body>

Because there are multiple "b" fields, I can't use property transfer with XPath tranformation, so I need to use groovy script, but I don't find any help on that specific purpose.
Does anyone can give me some hints ?
I have tried with daggett answer but my input is a SoapUI request/response.
def requestHolder = groovyUtils.getXmlHolder( "WSCall#Request" )

def xclone(Node n){
  return new XmlParser().parseText(XmlUtil.serialize(n))
}

for( item in requestHolder.getDomNodes( "//b" )){
  item.depthFirst().each{e->
    if(e.name()=='bb'){
      def e2 = xclone(e)
      e2.name = 'bb2'
      e.parent()?.append( e2 )
    }
  }
}

but I obtain a groovy.lang.MissingMethodException: No signature of method: org.apache.xmlbeans.impl.store.Xobj$ElementXobj.depthFirst() is applicable for argument types: () values: [] error at line: 34
with
requestHolder.getDomNodes( "//b" ).each{e->
  if(e.name()=='bb'){
    def e2 = xclone(e)
    e2.name = 'bb2'
    e.parent()?.append( e2 )
  }
}

I obtain an groovy.lang.GroovyRuntimeException: Cannot read write-only property: name

A: import groovy.xml.XmlUtil

def root = new XmlParser().parseText('''<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>

      <aa>...</aa>

      <bb>111</bb>

      <bb><cc>222</cc></bb>

</soap:Body>
</soap:Envelope>''')

def xclone(Node n){
    return new XmlParser().parseText(XmlUtil.serialize(n))
}

root.depthFirst().each{e->
    if(e.name()=='bb'){
        def e2 = xclone(e)
        e2.name = 'bb2'
        e.parent()?.append( e2 )
    }
}

println XmlUtil.serialize(root)

results
<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>

      <aa>...</aa>

      <bb>111</bb>
      <bb2>111</bb2>

      <bb>
        <cc>222</cc>
      </bb>
      <bb2>
        <cc>222</cc>
      </bb2>

  </soap:Body>
</soap:Envelope>


text:
Q: Error when Spark 2.2.0 standalone mode write Dataframe to local single-node Kafka The data source is from Databricks Notebook demo:Five Spark SQL Helper Utility Functions to Extract and Explore Complex Data Types!
But when I try these code on my own laptop, I always get errors.
First, load JSON data as DataFrame
res2: org.apache.spark.sql.DataFrame = [battery_level: string, c02_level: string]

scala> res2.show

+-------------+---------+
|battery_level|c02_level|
+-------------+---------+
|            7|      886|
|            5|     1378|
|            8|      917|
|            8|     1504|
|            8|      831|
|            9|     1304|
|            8|     1574|
|            9|     1208|
+-------------+---------+

Second, write data to Kafka:
res2.write
  .format("kafka")
  .option("kafka.bootstrap.servers", "localhost:9092")
  .option("topic", "test")
  .save()

All of those follows the notebook demo above and official steps
But errors shows:
scala> res2.write
         .format("kafka")
         .option("kafka.bootstrap.servers", "localhost:9092")
         .option("topic", "iot-devices")
         .save()

org.apache.spark.sql.AnalysisException: Required attribute 'value' not found;
  at org.apache.spark.sql.kafka010.KafkaWriter$$anonfun$6.apply(KafkaWriter.scala:72)
  at org.apache.spark.sql.kafka010.KafkaWriter$$anonfun$6.apply(KafkaWriter.scala:72)
  at scala.Option.getOrElse(Option.scala:121)
  at org.apache.spark.sql.kafka010.KafkaWriter$.validateQuery(KafkaWriter.scala:71)
  at org.apache.spark.sql.kafka010.KafkaWriter$.write(KafkaWriter.scala:87)
  at org.apache.spark.sql.kafka010.KafkaSourceProvider.createRelation(KafkaSourceProvider.scala:165)
  at org.apache.spark.sql.execution.datasources.DataSource.write(DataSource.scala:472)
  at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:48)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:58)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:56)
  at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:74)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:117)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:117)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:138)
  at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
  at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:135)
  at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:116)
  at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:92)
  at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:92)
  at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:610)
  at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:233)
  ... 52 elided

I assumed that it might be the Kafka problem, then I test the DataFrame read from Kafka to ensure the connectivity:
scala> val kaDF = spark.read
         .format("kafka")
         .option("kafka.bootstrap.servers", "localhost:9092")
         .option("subscribe", "iot-devices")
         .load()
kaDF: org.apache.spark.sql.DataFrame = [key: binary, value: binary ... 5 more fields]

scala> kaDF.show

+----+--------------------+-----------+---------+------+--------------------+-------------+
| key|               value|      topic|partition|offset|           timestamp|timestampType|
+----+--------------------+-----------+---------+------+--------------------+-------------+
|null|    [73 73 73 73 73]|iot-devices|        0|     0|2017-09-27 11:11:...|            0|
|null|[64 69 63 6B 20 3...|iot-devices|        0|     1|2017-09-27 11:29:...|            0|
|null|       [78 69 78 69]|iot-devices|        0|     2|2017-09-27 11:29:...|            0|
|null|[31 20 32 20 33 2...|iot-devices|        0|     3|2017-09-27 11:30:...|            0|
+----+--------------------+-----------+---------+------+--------------------+-------------+

So, the result shows that reading data in topic "iot-devices" from Kafka bootstrap.servers localhost:9092 does work.
I searched a lot online, but still can't solve it?
Can Anybody with Spark SQL experience tell me what is wrong in my command?
Thanks!

A: The error message clearly shows the source of the problem:

org.apache.spark.sql.AnalysisException: Required attribute 'value' not found;

The Dataset to be written has to have at least value column (and optionally key and topic) and res2 has only battery_level, c02_level.
You can for example:
import org.apache.spark.sql.functions._

res2.select(to_json(struct($"battery_level", "c02_level")).alias("value"))
  .writeStream
  ...


text:
Q: How to remove the highlight words? <input type="text" id="search">
<input type="button" id="button" onmousedown="doSearch(document.getElementById('search').value)" value="Find">

Hello World!

function doSearch(text) {
if (window.find && window.getSelection) {
    document.designMode = "on";
    var sel = window.getSelection();
    sel.collapse(document.body, 0);

    while (window.find(text)) {
        document.execCommand("HiliteColor", false, "yellow");
        sel.collapseToEnd();
    }
    document.designMode = "off";
} else if (document.body.createTextRange) {
    var textRange = document.body.createTextRange();
    while (textRange.findText(text)) {
        textRange.execCommand("BackColor", false, "yellow");
        textRange.collapse(false);
    }
}
}

Hey guys, I am facing a problem here. How to remove the highlighted word after i press the find button again?

A: you need to check if there is already an element which has the highlighted class. if yes then first remove all highlighted spans inside the content div p element.
 if(document.querySelector('span[style*="background-color: yellow;"]') !== null) {
        var elem = document.querySelector("#content p");
        var txt = elem.innerText || elem.textContent;
        elem.innerHTML = txt;
   }

function doSearch(text) {

   if(document.querySelector('span[style*="background-color: yellow;"]') !== null){
        var elem = document.querySelector("#content p");
        var txt = elem.innerText || elem.textContent;
        elem.innerHTML = txt;
   }

if (window.find && window.getSelection) {
    document.designMode = "on";
    var sel = window.getSelection();
    sel.collapse(document.body, 0);

    while (window.find(text)) {
        document.execCommand("HiliteColor", false, "yellow");
        sel.collapseToEnd();
    }
    document.designMode = "off";
} else if (document.body.createTextRange) {
    var textRange = document.body.createTextRange();
    while (textRange.findText(text)) {
        textRange.execCommand("BackColor", false, "yellow");
        textRange.collapse(false);
    }
}
}
<input type="text" id="search">
<input type="button" id="button" onmousedown="doSearch(document.getElementById('search').value)" value="Find">

Hello World!


text:
Q: Poisson distribution: P[-infinity] I am confused with how to handle the probabilty of $P[-\infty]$
Let X be a random variable with Poisson probability distribution and $\lambda = 1.$ What is the probability $P(X>1)$?
$P(X > 1) = 1 - P(X < 1)$
$P(X < 1) = P[0] + P[1] + P[-\infty]$
$P[0] = \frac{1^{0} \times e^{-1}}{0!} = e^{-1}$
$P[1] = \frac{1^{1} \times e^{-1}}{1!} = e^{-1}$
$P[-\infty] = \frac{1^{-\infty} \times e^{-\infty}}{\infty!} = ?$


text:
Q: Append JSON data from Yelp API to html I tried the JavaScript example from the Yelp developer site. Everything´s working but I wonder how to append the JSON data to an html list (ul). The list should contain restaurants in my town. Does anybody know how to do this?
P.S. PHP would be OK, too.
Edit:
Thank you for your answers but it still doesn´t work. I´m not able to give you more details because the Yelp API is poorly documented and I´m new to JSON and PHP.

A: If the JSON object is being returned as part of an Ajax request you'll need something vaguely like this:
$.post("yourajaxrequest.php", //calls .php file and transmits data via $_POST
                {
                    //variables required by the PHP file go here
                },
                //the function to perform when an object is returned from .php file
                function(toreceive){
                    var obj = JSON.parse(toreceive);
                    var first = obj.returnone;
                });

Without reading the Yelp documentation I'm not sure quite how you'll receive the object from Yelp, but the JSON.parse() method is the approach you should take to decode the object.
After parsing the object to a variable, you can assign the elements of the object by calling object.*insert array value here*;
This would be declared in PHP normally with something similar to:
$toencode = "The first string to be encoded";
$tosend['returnone'] = $toencode;
echo json_encode($tosend);
exit;

You can then append to a
 by using .append

In your