text:
Q: crypttab: location of luks header file Hi my crypttab looks as follows:
crypt_device /dev/sda luks,header=/boot/header.img
update-initramfs -u -k all works with success, but for some reason cryptsetup will not find the header.img which resides on the usb stick (that also contains the boot partition) during boot. It is stored on /boot/header.img
(using luks encryption with detached header, and seperate boot partition on usb, os: lubuntu 18)

A: Unless you've taken special steps to mount the /boot filesystem under initramfs, it won't be mounted yet. In a default boot sequence, the system only cares about the root filesystem (and possibly the swap partition) while executing in initramfs.
Once the real root filesystem has been checked (if applicable) and mounted, the rest of the filesystems, normally including /boot, are mounted. You would need to make some special arrangement to mount the /boot filesystem while still in initramfs to gain access to /boot/header.img. Or you could just include your header.img into initramfs.

A: Since your USB drive is also your boot drive, the system only loads the initramfs image to memory until the root partition is decrypted and newroot is remapped. This is where manual mount of the USB drive would be necessary from within the initramfs or an update to fstab needs to be made to mount the partition which contains the key file. Although you mentioned that that during boot it is stored in /boot/header.img it's because the USB is no longer mounted when the initramfs is loaded into RAM for the boot processs. Therefore when crypttab initiates, cryptsetup cant find the /boot/header.img file because the directory for /boot on the USB hasn't been mounted within the initramfs environment which is currently loaded to decrypt your hard drive's root folder.
To be sure, as telcoM explained, if you previously booted into your system and created a keyfile while the OS was unlocked and the partition was decrypted and then placing a copy of the keyfile.img within your /boot directory at that point in time (and again, and this is while the system is unencrypted and you're already accessing the system) then it's not the same /boot directory you find when you're booting up and the USB contains the boot drive; that's what we're both trying to say. This is because during the boot process, it has opened and copied the initrd-4.15.33-generic image (for example) and does not mount automatically the USB device as a storage container.
So to resolve, you need fstab to mount the USB to the /boot directory so that crypttab can locate the directory when it's called for by cryptsetup
See the fstab man page for explanations if needed for below:
e.g.
# First find the UUID of the partition holding your USB thumb drive
$ blkid

# You can also use grep or whatever you're more comfortable with as a text editor
$ nano /etc/fstab

# then add a line for your USB device
UUID={device partition UUID} {mount point} {filesystem} {mount options}  {dump order}{fsck order}
# Example
UUID=66E53SSD988 /boot ext4  defaults  0 1

However, I would suggest mounting the drive somewhere other than in the /boot directory unless that's just the directory within the USB and then modifying crypttab so that there's less confusion between what folder the header.img file is in.
i.e.
UUID=66E53SSD988 /mnt/usb ext4  defaults  0 1
Then, in the case of the changed mount point, crypttab would in turn need to be changed to the following :
crypt_device /dev/sda luks,header=/mnt/usb/boot/header.img


text:
Q: Brownian motion properties In my notes, the quadratic variation is defined as
$$Q[f]=\lim_{N\to \infty} \sum_{i=0}^{N-1} |f_{t_{i+1}}-f_{t_{i}}|^2$$
Take time period $[0,T]$ with $N$ partitions, so $dt=T/N$; $t_i=idt$.
Now, for Brownian Motion $W_t$,
$$Q[W_t]=\lim_{N\to \infty} \sum_{i=0}^{N-1} |W_{t_{i+1}}-W_{t_{i}}|^2=\lim_{N\to \infty} \sum_{i=0}^{N-1} |\pm \sqrt{dt}|^2=\lim_{N\to \infty} Ndt=T$$
My firstquestion is why $W_{t_{i+1}}-W_{t_{i}}=\pm \sqrt{dt}$ ?
I konw that according o the definition of Brownian motion,
$$dW_t=W_{t+dt}-W_t \text{ ~ } N(0,dt)$$
But this just imply that $Var[W_{t_{i+1}}-W_{t_{i}}]=dt$, so why the variance is dropped in the above? Or is this due to another reason?
And then it says,
for the variation, we have:
$$Q[W_t]=\lim_{N\to \infty} \sum_{i=0}^{N-1} |W_{t_{i+1}}-W_{t_{i}}|=\lim_{N\to \infty} \sum_{i=0}^{N-1} |\pm \sqrt{dt}|=\lim_{N\to \infty} N \sqrt{dt} \to \infty$$
"The Quadratic Variation property implies ${dWt}^2=dt$."
My second question is where this implication come from?
Thanks for help!

A: First of all some advice useful to keep in mind when you are dealing with math-related stuff: you have to be cautious about the real meaning of the notation.
In your case the first thing to notice is that $Q[W_t]=T$ doesn't make sense, since on the left of the equality you have a random variable and on the right a constant. The problem here is that you are defining $Q[W_t]$ as a limit but you are not saying in what sense you have to interpret this notation.
To be more concrete let's focus on the proof of your statement.
Let's fix some notation. Let $W:[0,T]\times\Omega\rightarrow\mathbb{R}$ be the standard Brownian motion, let $\pi:=\{0<\frac{T}{N}...<\frac{(N-1)T}{N}< T\}$ be your partition of $[0,T]$. We set $t_i=i\frac{T}{N}$, for $i=0,..,N$. We define the quadratic variation of $W$ with respect to the partition $\pi$ as $$S_{\pi}(W):=\sum_{i=1}^{N} (W_{t_{i}}-W_{t_{i-1}})^2.$$ What we want to  show is that $$\lim_{N\rightarrow\infty}S_{\pi}=T\ \ \ \  in \ \ \ L^2(\Omega),$$
which means that we have to show $$\lim_{N\rightarrow\infty}E[(S_\pi-T)^2].$$
Defining $Y_i=(W_{t_{i}}-W_{t_{i-1}})^2-(t_i-t_{i-1})$ we can write $S_\pi-T=\sum_{i=1}^{N}Y_i$. We observe that the random variables $Y_1,...,Y_N$ are independent since each $Y_i$ is a function of $W_{t_{i}}-W_{t_{i-1}}$ and by the definition of Brownian motion its increments are independent. Moreover
$$E[Y_i]=E[(W_{t_{i}}-W_{t_{i-1}})^2]-(t_i-t_{i-1})=Var(W_{t_{i}}-W_{t_{i-1}})-(t_i-t_{i-1})=0.$$
Using these two facts we obtain
$$E[(S_\pi-T)^2]=\sum_{i=1}^{N}E[Y_i^2].$$
We know that the distribution of $W_{t_{i}}-W_{t_{i-1}}$ is $N(0,t_{i}-t_{i-1})$ thus the distribution of $$Z:=\frac{W_{t_{i}}-W_{t_{i-1}}}{\sqrt{t_{i}-t_{i-1}}}$$ is $N(0,1)$. (Z doesn't depend on $i$ because we are interested only in its distribution and for every $i$ it is a standard normal). Using this fact we write
$$\sum_{i=1}^{N}E[Y_i^2]=\sum_{i=1}^N E[\ [(W_{t_{i}}-W_{t_{i-1}})^2-(t_{i}-t_{i-1})]^2\ ]=\\ \sum_{i=1}^N (t_{i}-t_{i-1})^2\  E[\ [\left( \frac{W_{t_{i}}-W_{t_{i-1}}}{\sqrt{t_i-t_{i-1}}}\right)^2-1]^2\ ]=\\
 \sum_{i=1}^N (t_{i}-t_{i-1})^2\  E[(Z^2-1)^2]=C\sum_{i=1}^N (t_{i}-t_{i-1})^2= \\ C \frac{T}{N}\sum_{i=1}^N t_{i}-t_{i-1}=C\frac{T^2}{N}$$ and the result follows for $N\rightarrow\infty$. $C:=E[(Z^2-1)^2]$ is a constant.
Hope this answer helps you clarify your totally justified doubts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: is there an equivalent for tag.innerHTML += x in BS4? When I try to use e.string to modify HTML in BS4, I get HTML entities. For example:
Code:
for i in soup.find_all('ism'):
    i.string = currentSpan
    # currentSpan is a string of HTML text and does not have entities

Result
Keep going until you see <ism type="cr">County Road 9</ism>

(ism is a custom tag name I am using).
Is there a function I can use to add tags and override entity conversion?

A: Nevermind, I answered it myself.
There's this property called 'tag.contents' which is a Tag that represents the HTML of the element.
To modify the HTML, I typed,
el.contents = BeautifulSoup(your_html, 'html.parser')

and that seemed to work.


text:
Q: nonemptycrossjoin not working as intended in pps I have 2 linked filters in PPS and there's connection formula between them:
   nonemptycrossjoin
    (
       [SAMPLECODE].[SAMPLECODE].members,
        { <<UniqueName>> }
    )

This nonemptycrossjoin supposedly should take out the SAMPLECODE-members from the filter that have no measures (ie. null values). And this MDX works when i try it in SSMS.
Any ideas why it's not working in PPS ?

A: If it is the exact same MDX statement that behaves different depending on the environment (SSMS vs PPS) on the same cube, then I only could imagine that connection parameters or some session settings would influence the result.
Nevertheless, NonEmptyCrossJoin is deprecated since SQL Server 2005. Instead of using this function, you could use the NON EMPTY axis modifier and an ordinary cross join, abbreviated as * as follows:
select [Measures].[ASD] on 0,
       non empty
       [DCode].[DCode].children * [SAMPLECODE].[SAMPLECODE].members
       on 1
  from p

EDIT
As - according to your comment - you get an error message for the non empty, I tried it on Adventure Works in AS2008R2, and the following query works fine:
select [Measures].[Internet Sales Amount] on 0,
       non empty
       [Customer].[Country].children * [Customer].[Gender].members
       on 1
  from [Adventure Works]

So, I would assume you have an error in the translation between the above query and your real query. I will not be able to find that without seeing your original query!


text:
Q: Crud module : Listing a OneToMany with a specific order I'm using Crud module and I can make it work well.
But when I displaying the form to add a new User (or edit an existing User), I have a list of Cities that are displayed in a non alphabetically way. I'd like to sort them based on the name.
I tried to add a @OrderBy to my model, but this doesn't work.
How can I do it?
Thanks for your help!
Here is my model for information :
@Entity
public class City extends Model {
    @Required
    @OrderBy  //doesn't work
    public String nomination; // I had to set this var to this name ...

    public String zipcode;

    public City(String nomination, String zipcode) {
        this.nomination = nomination;
        this.zipcode = zipcode;
    }

    @Override
    public String toString(){
        return this.nomination;
    }
}

A: EDIT ON UPDATE
I'm afraid it's nto trivial. In the framework the code that retrieves the list of cities is this one. As you can see it doesn't add any "order by" to the query as it's generic. The CRUD tag that paints the rels (here) just iterates over that field.
The simplest solution would be to use the CRUD customization capabilites (here) and use teh #{crud.custom} tag to paint your own dropdown with the ordered list of cities.
OLD ANSWER
I believe your error is on where the @OrderBy annotation is placed. You should put it on the relation:
  @Entity
    public class Foo{
       ...
       @OneToMany
       @OrderBy("nomination ASC")
       public List<City> cities;
       ...
    }

This way the list "cities" will be ordered by the parameter.
I just noticed that you mention you are using the CRUD module. In this case, as far as I remember, CRUD lists the fields ordered by the first column it displays. Try to change that column as per this page so the name is the first column.

A: I got this working by hacking JPAPlugin.java:
--- a/framework/src/play/db/jpa/JPAPlugin.java
+++ b/framework/src/play/db/jpa/JPAPlugin.java
@@ -771,7 +771,11 @@ public class JPAPlugin extends PlayPlugin {

    @SuppressWarnings("unchecked")
    public List<Object> list() {
        - return getJPAContext().em().createQuery("from " + field.getType().getName()).getResultList();
        + String query = "from " + field.getType().getName();
        + if (field.isAnnotationPresent(OrderBy.class)) {
            + query += (" order by " + field.getAnnotation(OrderBy.class).value());
        + }
        + return getJPAContext().em().createQuery(query).getResultList();
        }
    };
}

This way you can annotate the City attribute on your User model with @OrderBy("name"), and you will have an ordered drop-down when editing your User object using the CRUD module:
@Entity
public class User{
   ...
   @OneToMany
   @OrderBy("name ASC")
   public City city;
   ...
}

A: Ran into the same issue today.
If you don't want to hack JPAPlugin or create custom fields every time you have a OneToMany relationship, you can also reorder them client-side via a little bit of JavaScript.
Here is use jQuery but you could also easily do it in Vanilla
<script type="text/javascript">
    innerSort = function (a, b) {
        return (a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase()) ? 1 : -1;
    };
    $('select').each(function( index ) {
        var previousVal = $(this).val();
        $(this).find('option').sort(innerSort).appendTo($(this));
        $(this).val(previousVal);
    });
</script>

Just place this bit of code into the CRUD/layout.html template (you can override it to make your own, see Play tutorial), at the end of the page


text:
Q: Copy sheet from main workbook to new sheet with the included macros i have a working code from a previeous thread in here, but i would like to see if there are any possibillities to change/ rework the code so when i copy the sheet from the main workbook to new sheet that the images thats in the sheet will be small images that stay in the sheet.   Today i need either to have the images in a folder or access to internet "if using url" to see the images.  I would like to be able to see the images if i change pc or are offline etc.
The old thread is her : Rename or add macro to module in a copied sheet from main workbook with vba
Here is the code i use for copying the sheet:
    Dim sh As Shape, wbNew As Workbook, ws As Worksheet

ThisWorkbook.Sheets("Import").Copy
Set wbNew = ActiveWorkbook
Set ws = wbNew.Sheets("Import")

For Each sh In ws.Shapes
    'relink only if has action set
    If Len(sh.OnAction) > 0 Then
        sh.OnAction = ws.CodeName & ".Zoom_Click"
    End If
Next sh

Adding some more info here:
This code below are the one i use to import the pictures and i guess this is the reason the images are not showing when i use the workbook og t.eg another pc without internet.  From what i understand the images here are imported as shapes/objects and its linked to the image files instead of actually have the image within the woorkbook, am i correct here?
This is from the main Workbook where i use the coda above to copy from.
Private Sub CommandButton2_Click()

    Dim theShape As shape
    Dim xRg As Range
    Dim xCol As Long
    On Error Resume Next
    Application.ScreenUpdating = False
    Set rng = Worksheets("Import").Range("A4:B1000")
    For Each cell In rng
        Filename = cell
        If InStr(UCase(Filename), "JPG") > 0 Then
            Worksheets("Import").Pictures.Insert(Filename).Select
            Set theShape = Selection.ShapeRange.Item(1)
            LinkToFile = msoFalse
            SaveWithDocument = msoTrue
            If theShape Is Nothing Then GoTo isnill
            xCol = cell.Column
            Set xRg = Cells(cell.Row, xCol)
            With theShape
                .LockAspectRatio = msoFalse
                .ScaleHeight 0.13, msoFalse
                .ScaleWidth 0.13, msoFalse
                .Top = xRg.Top + (xRg.Height - .Height) / 2
                .Left = xRg.Left + (xRg.Width - .Width) / 2
            End With
isnill:
            Set theShape = Nothing
            Range("e1").Select
        End If
    Next
    Application.ScreenUpdating = True

    Debug.Print "Done " & Now

End Sub


text:
Q: Addition using recursion printing garbage I have this very small piece of code. But it is giving me garbage values instead of a proper answer. Working on mvs 2010. The program does not also terminate normally.
 long  sumsq_diff (int arr1[],int size1, int arr2[],int size2, int i)
{
    if(i < size2)
    {
        return ( (arr1[i]-arr2[i]) * (arr1[i]-arr2[i]) ) +
                sumsq_diff (arr1,size1,arr2,size2, i + 1) ;
    }
    else
        return 0 ;
}

int main ()
{
     const int size1 = 5 ;
     const int size2 = 5 ;
     int arr1 [size1] = {1, 2, 3, 4, 5} ;
     int arr2 [size2] = {0, 0, 0, 0, 0} ;
     int ans =  sumsq_diff (arr1,size1,arr2, size2, 0) ;
     cout << ans ;
     return 0 ;
}

Thanks.


text:
Q: ClassCastException - TestNGMethod to TestNGScenario Eclipse/Maven/Java/Selenium/TestNG
My very simple test:
@DataProvider( name="suite")
public Object[][] dpMethod_suite() {
    return new Object[][] {{"diamonds"},{"hearts"},{"clubs"},{"spades"}};
}

@Test( dataProvider="suite")   //  <---- throws the errmsg
public void Test_01( String suite) {
    boolean testPassed = true;

    System.out.println("suite passed in: " + suite);

    Assert.assertEquals( testPassed, true);
}

should produce 4 executions of test Test_01 but instead throws a runtime error
java.lang.ClassCastException: org.testng.internal.TestNGMethod cannot be cast to com.qmetry.qaf.automation.step.client.TestNGEcenario

which is exactly the problem discussed in https://github.com/qmetry/qaf/issues/247
so I adjusted my pom so qaf stuff is brought in before testng stuff.
<parent>
  <groupId>com.xxxxx.eqe</groupId>
  <artifactId>xxxxx.lib.eqe.parent</artifactId>
  <version>2.3</version>
</parent>
<dependencies>
  <dependency>
    <groupId>com.qmetry</groupId>
    <artifactId>qaf</artifactId>
    <version>2.1.14</version>
    <exclusions>
      <exclusion>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
      </exclusion>
    </exclusions>
  </dependency>
  <dependency>
    <groupId>com.qmetry</groupId>
    <artifactId>qaf-support</artifactId>
    <version>2.1.14</version>
  </dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.10</version>
  </dependency>
</dependencies>

Results of
mvn dependency:tree

yields
+- com.xxxxxxx.eqe:xxxxxxx-eqe-automation.jar
  +- com.qmetry:qaf
    +- org.hamcrest stuff
    +- com.sun.jersey stuff
    +- org.aspectj stuff
    ..... alot of stuff but NO testng stuff
  +- com.qmetry:qaf-support
  +- org.seleniumhq:selenium-java
     .....
  +- org.seleniumhq:selenium-support
     .....
  .... more stuff but NO testNG stuff
+- org.testng:testng
  +- com.beust:jcommander
+- some other stuff

so I'm pretty confident testng is brought in after all QAF stuff as indicated by the github article
So either a) I'm wrong, b) the solution on github is wrong or c) who knows?
Any solutions/idea/constructive criticisms would be appreciated.
TIA,
Still-Learning Steve

A: I'm not completely sure, but I think you should upgrade the versions of the tools you are using.
You should use 7.4.0 version of the TestNG
And 3.0.x version of qmery
This should work:
<dependencies>
  <!-- https://mvnrepository.com/artifact/com.qmetry/qaf -->
  <dependency>
    <groupId>com.qmetry</groupId>
    <artifactId>qaf</artifactId>
    <version>3.0.0</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.testng/testng -->
  <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.4.0</version>
    <scope>test</scope>
  </dependency>
</dependencies>


text:
Q: Issue with stimul soft report in margin left I use Stimul soft 2013 for reporting in ASP .NET.
When I show my report in A5 letter, it shows like this:

My text from left did not show correctly. I suppose if I could add margin from left to my text, it will solve my problem.
Consider that, I added html tag justify to my text
any body.
Can you help me with this problem?

A: In Stimul you can shrink your text.
For this problem is better that you set Shrink Text to "True", set a Minimum Size for it, and set Word Wrap to "True".
And sometimes you must put an empty text box to fix it.


text:
Q: React: How to route correctly on form submission? I have a one form app that is comprised of:

*

*NavBar component

*Form component (containing form fields)

*Checkbox component (terms and conditions)

*SubmitButton component

*ThankYouPage component

Components 1-4 are initially showing on the screen when the user is filling out the form. When the user clicks the submit button I want him or her to be routed to the Thank You page. After watching a tutorial and adding a route, the only thing that happens when the user clicks the submit the ThankYouPage component text appears below the form. I want all the other components to disappear and the only thing left being the ThankYouPage compenent. Can someone tell me what I am doing wrong?
App.js
import React from 'react';
import NavBar from './Components/NavBar'
import Form from './Components/InfoForm'
import SubmitButton from './Components/SubmitButton';
import Container from '@material-ui/core/Container';
import Checkbox from './Components/Checkbox';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import './App.css';
import ThankYou from './Components/ThankYou';

function App() {

    const [state, setState] = React.useState({
        checkbox: false,
    });

    const [values, setValues] = React.useState({
        name: '',
        age: '',
        email: ''
    });

    const handleChangeForm = name => event => {
      setValues({ ...values, [name]: event.target.value });
    };

    const handleChange = event => {
      setState({ ...state, [event.target.name]: event.target.checked });
    };

    return (
        <Router>

                 <Container maxWidth="md">
                 <NavBar />
                 <Form values={values} handleChangeForm={handleChangeForm} />
                 <Checkbox name="checkbox" onChange={handleChange} checked={state.checkbox} />
                 <SubmitButton isEnabled={state.checkbox} values={values}/>
                 </Container>

                <Route path="/thankyou" component={ThankYou} />
        </Router>
    );
}

export default App;

SubmitButton.js
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import { Link } from 'react-router-dom';

export default function ContainedButtons(props) {
  const classes = useStyles();

  const onClickBtn = () => {

    const textBuilder = () => {
      var doc = "";
      for (const key in props.values) {
       doc += key + ": " + props.values[key] + "
";
      }
      return doc;
    }

    window.Email.send({
      Host : "smtp.elasticemail.com",
      Username : "mine@gmail.com",
      Password : "xxxx-xxxx-xxx-xxx",
      To : 'mine@gmail.com',
      From : "mine@gmail.com",
      Subject : "New Client Info",
      Body : textBuilder()
  }).then(
    message => alert(message)
  );
  };

    return (

        <Link to="/thankyou">
          <Button variant="contained" color="primary" className={classes.button} disabled = {!props.isEnabled} type="submit" onClick={onClickBtn}>
            Submit
          </Button>
        </Link>

    );
}

ThankYouPage.js
import React from 'react';

function ThankYou() {
  return (

Thank you and get ready to become a work of art!

  );
}

export default ThankYou;

A: You can think of Route as the component that renders the said component in it's place when the route matches.
So, when you have:
<Router>

     <Container maxWidth="md">
        <NavBar />
        <Form values={values} handleChangeForm={handleChangeForm} />
        <Checkbox name="checkbox" onChange={handleChange} checked={state.checkbox} />
        <SubmitButton isEnabled={state.checkbox} values={values}/>
     </Container>

  <Route path="/thankyou" component={ThankYou} />
</Router>

it means, that the top part inside Container is fixed, whichever route you go to.
Instead what you need is to render the Container inside a route so that it goes away when route changes. Something like:
<Router>
  <Route exact path="/" component={FormContainer} />
  <Route path="/thankyou" component={ThankYou} />
</Router>

When submitting a form, there are probably validations to perform. So the best way would be navigate programmatically.
submitForm = () => {
  // assuming this component is in a route
  const { router } = this.props'
  router.push("/thankyou");
}
render() {
  return (
    <form onSubmit={this.submitForm}>
     <button type="submit">Submit</button>
    </form>
  );
}

More info on Programmatic Navigation
Regarding your sending emails from client side, Don't. The password is accessible for everyone accessing your site. Write a server side script or use a mailto link


text:
Q: How can I type the instance of an untyped class? I am extending a class which comes from an external library and is sadly not typed.
To makes matters even more complicated, it's instantiation is done via a static method in the untyped class. The change of this as it stands is not an option. It would look something like this:
class MyUntypedClass {
  constructor (context) {
    this.someAttribute = ''
    this.someOtherAttribute = ''
  }

  static createNewInstanceWithStuff () {
    // do a bunch of stuff prior to creating the instance
    const instance = new this(context)

    return instance
  }
}

As mentioned I then extend it and make sure to type my methods:

class MyTypedClass extends MyUntypedClass {
  private myNewAttribute = ''

  constructor() {
    super({ stuff })
    this.myNewAttribute = myNewAttribute
  }

  private myNewMethod (param: string, otherParam: number): string {
    // do stuff
  }
}

However, I must instantiate it via the static method from MyUntypedClass, and I end up losing the types I had written for my methods. Code looks something like this:
const instance = MyTypedClass.createNewInstanceWithStuff()

const value = instance.myNewMethod('some string', 123) // if I try to check  the params or return type it is any

Is there anyway to type my methods whenever the instance is created from the untyped parent class?

A: If you want the static createNewInstanceWithStuff method of MyTypedClass to be of a more specific type than that of the MyUntypedClass but you don't want to change the runtime behavior, you can use the declare property modifier to tell the compiler that.  This will have no effect on the emitted JavaScript.  It looks like this:
class MyTypedClass extends MyUntypedClass {
  /* ... */
  declare static createNewInstanceWithStuff: () => MyTypedClass; // <-- declare this
  /* ... */
}

Note that you have to use a function-typed field annotation instead of a method, because the declare property modifier is not currently supported for methods (see microsoft/TypeScript#38008 for the relevant feature request).
Now it should work as expected:
const instance = MyTypedClass.createNewInstanceWithStuff();
// const instance: MyTypedClass
const value = instance.myNewMethod('some string', 123)
// const value: string;

Playground link to code


text:
Q: Pagination - works on local but not live dev! Can anyone please shed some light as to why the following to print out page numbers works on my local dev server but not on my live server?
Both server are running same version of PHP.
My Loop
<?php
global $paged;
$args = array(
    'orderby' => 'post_date',
    'posts_per_page' => 5,
    'paged' => $paged
);
$query = new WP_Query($args);
if($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
//do stuff
endwhile; ?>

My Pagination
<?php echo '

[First]';
for($i=1;$i<=$query->max_num_pages;$i++)
echo ''.$i.'';
echo 'max_num_pages).'">[Last]

';
endif;
wp_reset_query();
?>

The issue clearly lies within:
for($i=1;$i<=$query->max_num_pages;$i++)

The first & last print out fine - the page numbers do not.
Thanks in advance
EDIT
If i do this it works:
for($i=1;$i<=99;$i++)

So the issue is with:
$query->max_num_pages;

Any more thoughts?

A: try this
<?php
//global $wp_rewrite;
$loop->query_vars['paged'] > 1 ? $current = $loop->query_vars['paged'] : $current = 1;

$pagination = array(
    'base' => @add_query_arg('page','%#%'),
    'format' => '',
    'total' => $loop->max_num_pages,

    'current' => 0,
    'show_all' => true,
    'prev_next'    => true,
    'prev_text'    => __('« Back'),
    'next_text'    => __('Newxt»'),
    'type' => 'plain'
    );

if( $wp_rewrite->using_permalinks() )
    $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged    ' );

    echo "
";
echo paginate_links( $pagination );
echo "
";
?>


text:
Q: VBA Mis-Match Error 13 I'm relatively new to VBA, I wrote a Sub to parse CSV information that is contained in a single cell and return certain pieces of data to other cells in the spreadsheet. Its a relatively simple code but I can't find the error. Its a Err 13 Mismatch on the line Moods = Application.Index(fullArray, 0, 3) Any help would be greatly appreciated.
Private Sub parseCSV()
'Parse "Notes" column and return Moods/Keywords to their apropriate cells

    Dim CSV As String
    Dim fullArray As Variant
    Dim lRow As Long
    Dim Keywords As Variant
    Dim Moods As Variant
    Dim i As Long

    lRow = ActiveSheet().Range("BL" & ActiveSheet().Rows.Count).End(xlUp).Row

    For i = 3 To lRow

        CSV = ActiveSheet.Range("BL" & i)
        fullArray = Split(CSV, Chr(10))
        Moods = Application.Index(fullArray, 0, 3)
        Keywords = Application.Index(fullArray, 0, 2)

        ActiveSheet.Range("CD" & i).Value = Moods
        ActiveSheet.Range("CE" & i).Value = Keywords

    Next i

End Sub

I tested the parse function below:
Private Sub parseCSVTest()
'Parse "Notes" column and return Moods/Keywords to their apropriate cells

    Dim CSV As String
    CSV = ActiveSheet.Range("BL5")

    Dim fullArray As Variant
    fullArray = Split(CSV, Chr(10))

    Dim Moods As Variant
    Moods = Application.Index(fullArray, 0, 3)

    Dim Keywords As Variant
    Keywords = Application.Index(fullArray, 0, 2)

    ActiveSheet.Range("CD5").Value = Moods
    ActiveSheet.Range("CE5").Value = Keywords

End Sub

Works just fine. So I tested my loop.
Private Sub loopTest()

    Dim i As Long
    Dim lRow As Long
    lRow = ActiveSheet().Range("BL" & ActiveSheet().Rows.Count).End(xlUp).Row

    For i = 3 To lRow
        ActiveSheet.Range("CD" & i).Value = "testing"
    Next i

End Sub

Works fine. I don't know where to go from here.

A: You are using CSV before you have assigned a value to it.

A: I Got it. Thanks for all the help everyone, this was a brain buster. For some reason
Moods = Application.Index(fullArray, 0, 3)
Keywords = Application.Index(fullArray, 0, 2)

won't return a value while specifying an entire column ( (0, 0) = all rows in columns in VBA Arrays ). I simply changed the array references to be (1, 3) and (1, 2). The full working code is below. This is the simplest way I've found online to parse to data from a cell and slice the array. Thanks to everyone that helped with this.
Private Sub parseCSV()
'Parse "Notes" column and return Moods/Keywords to their apropriate cells

    Dim CSV As String
    Dim fullArray As Variant
    Dim lRow As Long
    Dim Keywords As Variant
    Dim Moods As Variant
    Dim i As Long

    lRow = ActiveSheet().Range("BL" & ActiveSheet().Rows.Count).End(xlUp).Row

    For i = 3 To lRow

        CSV = ActiveSheet.Range("BL" & i)
        fullArray = Split(CSV, Chr(10))
        Moods = Application.Index(fullArray, 1, 2)
        Keywords = Application.Index(fullArray, 1, 3)

        ActiveSheet.Range("CE" & i).Value = Moods
        ActiveSheet.Range("CD" & i).Value = Keywords

    Next i

End Sub


text:
Q: Peterson-2 mutual algorithm The contention-free complexity of the Peterson's 2-proccess algorithm is 4 (performs 3 two accesses to shared-registers memory in the entry code and and one in the exit code ) .
How can I modify the Peterson's 2-proccess algorithm so that  its contention-free complexity will be 3?
Thanks.


text:
Q: PHP SOAP / Understanding WSDL Figured it out, see Update below.
I'm trying to work with a particular web service via PHP (tried both the native and Zend SOAP clients) and it only returns a failure status.
I suspect that it has something to do with the multiple beans in the retrieveMemberInfo method call (authBean, memberInfoBean).
Could someone take a look at the WSDL and point me in the right direction for this particular method call via the PHP client?
Here is what I have so far:
$service = new SoapClient('https://qa.everbridge.net/ws3/services/WebServices3?wsdl');
$result = $service->retrieveMemberInfo(array('loginId', 'orgName', 'password'), array('firstname', 'lastname'));
var_dump($result);

Update
The problem was not with the WSDL call as originally thought. It was the format for the parameters used in the retrieveMemberInfo method call. Here is the full solution that correctly returns the SOAP response:
$params->authBean->loginId = 'username';
$params->authBean->orgName = 'orgName';
$params->authBean->password = 'password';
$params->memberInfoBean->firstName = 'firstName';
$params->memberInfoBean->lastName = 'lastName';

$service = new SoapClient('https://qa.everbridge.net/ws3/services/WebServices3?wsdl');
$result = $service->retrieveMemberInfo($params);

var_dump($result);

Now I just have to figure out how to parse the returned stdObject.
Thanks for the assistance.

A: This is apparently a bug in PHP. The file is not completely read. There's nothing wrong with the WSDL itself.
The XML parsing error is this:

object(LibXMLError)#1 (6) {
  ["level"]=>
  int(3)
  ["code"]=>
  int(5)
  ["column"]=>
  int(5)
  ["message"]=>
  string(41) "Extra content at the end of the document
"
  ["file"]=>
  string(56) "https://qa.everbridge.net/ws3/services/WebServices3?wsdl"
  ["line"]=>
  int(537)
}

Line 537 is quite before the end of the file.
I suggest you report this to http://bugs.php.net/

A: The problem seems to come before that method call:

Fatal error: Uncaught SoapFault
  exception: [WSDL] SOAP-ERROR: Parsing
  WSDL: Couldn't load from
  'https://qa.everbridge.net/ws3/services/WebServices3?wsdl'
  : Extra content at the end of the
  document in /.../wsdl.php:2 Stack
  trace: #0 /.../wsdl.php(2):
  SoapClient->SoapClient('https://qa.ever...')
  #1 {main} thrown in /.../wsdl.php on line 2

<?php
$service = new SoapClient('https://qa.everbridge.net/ws3/services/WebServices3?wsdl');
//$result = $service->retrieveMemberInfo(array('loginId', 'orgName', 'password'), array('firstname', 'lastname'));

echo '
';
var_dump($result);
echo '
';
?>

I fetched from that URL with wget and I didn't notice anything extra at the end of the returned document.  Not that I know much about WSDL, but I would track the cause of this error.
Update:
After confirming Artefacto's findings, I was motivated to try a workaround:
$curl = curl_init('https://qa.everbridge.net/ws3/services/WebServices3?wsdl');
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true);

$wsdl_string = curl_exec($curl);

file_put_contents('/var/tmp/wsdl.xml',$wsdl_string);

try
{
    $service = new SoapClient('/var/tmp/wsdl.xml');
    $result = $service->retrieveMemberInfo(array('loginId', 'orgName', 'password'), array('firstname', 'lastname'));

    print '
';
    var_dump($result);
    print '
';
}
catch (Exception $e)
{
    print '
';
    var_dump(libxml_get_last_error());
    print '
';
}

Of course, remove the debugging code.  You may also want to delete the temporary file after using it.

A: I've tried copying it locally and using the example provided in the PHP bug submission.
$tmpWsdlPath = tempnam(sys_get_temp_dir(), 'wsdl');
copy("https://qa.everbridge.net/ws3/services/WebServices3?wsdl", $tmpWsdlPath);
$service = new SoapClient($tmpWsdlPath);
$result = $service->retrieveMemberInfo(array('loginId', 'orgName', 'password'), array('firstName', 'lastName'));

It correctly grabs the WSDL file and writes it to the temp folder. It is the entire file.
It still returns the failure status.


text:
Q: Poor classification of ring morphisms $\mathbb{Z} \to \mathbb{Z}_n$ I've found issues with questions in my algebra textbook before, and I believe that I've found another erroneous question.
L. E. Sigler Algebra Chapter 2 "Rings: Basic Theory" Section 7 "Morphisms and Quotient Rings" Exercise 4:

Let $m$ be different from $0$ and $1$ and belong to $\mathbb{N}$. Show that $f: \mathbb{Z} \to \mathbb{Z}_n$ such that $f(x) = mx$ is a morphism if and only if $n = m(m-1)$.

As a first thing, I think that $f(x) = \overline{mx}$ or $f(x) = mx + n\mathbb{Z}$ is what the textbook meant. So, with that adjustment, I think that the forward direction of the implication is false.
A counterexample to the contrapositive of the forward implication can be found with $m = 9$ and $n = 12 \neq 9(9-1)$. Let $x,y \in \mathbb{Z}$. Then
$$
f(x + y) = 9(x + y) + 12\mathbb{Z} = 9x + 9y + 12\mathbb{Z} = (9x + 12\mathbb{Z}) + (9y + 12\mathbb{Z}) = f(x) + f(y)
$$
$$
f(xy) = 9xy + 12\mathbb{Z} = (9 + 12\mathbb{Z}) (xy + 12\mathbb{Z}) = (9 + 12 \cdot 6 + 12\mathbb{Z}) (xy + 12\mathbb{Z}) = (81 + 12\mathbb{Z}) (xy + 12\mathbb{Z}) = (9^2 + 12\mathbb{Z}) (xy + 12\mathbb{Z}) = 9^2xy + 12\mathbb{Z} = (9x + 12\mathbb{Z}) (9y + 12\mathbb{Z}) = f(x)f(y).
$$
So $f: \mathbb{Z} \to \mathbb{Z}_{12}$ such that $f(x) = \overline{9x}$ is a morphism of rings, counter to what the textbook claims.
My questions are: Did I do anything wrong? If not, how can this question be edited into something which works?

A: Indeed, if $1 \mapsto m$ (I neglect overlines), then $ab \mapsto abm$ on the one hand, and on the other this has to equal $(am)(bm) = abm^2.$ So you would need $m^2 = m$ in the domain. This is what you try to show in the proof: $9^2$ is really equal to $9$ modulo $12$: their difference is $72,$ which is divisible by $12$ indeed.
What does $m^2 \equiv m \text{ mod} (n)$ mean? This means that $m^2 - m = m(m-1)$ is divisible by $n$, so it's equal to $kn$ for some $k$ rather than just $n$.


text:
Q: How to use base64 string from database to display an image How can I use base64 string from database to display an image? I can't see any function to convert this by using jQuery DataTables.
oTableImage = $('#tbl_image').DataTable({
        "processing": true,
        "destroy": true,
        "paging":false,
        "bFilter": false,
        // "scrollY": "200px",
        "ajax":{
            "type":"POST",
            dataType: "json",
            "url":"{{ URL::to('ajax/per-seller-image') }}",
            "data":function(d){
                d.rtd_id =rtd;
            }
        },

        "columns":[
            {data: 'start_image', name: 'start_image'}
        ]
    });
});

A: You can show a base64 encoded image in HTML like this:

And then render the  tag in DataTable:
"columns": [
    {
        "render": function (data, type, row) {
            return '';
        }
    }
],

A: Base64 data will be automatically rendered by browser itself. You don't have to convert.


text:
Q: Vim how to copy to a real (no relative) line number I'm working with NeoVim, but for the case I think it's the same if we talk about vim. I have set relative line numbers (set nu rnu) and I know how to copy from the line I currently have the cursor to line x with yxj, but I need to copy more lines than I can see, so I first go to line 247, then I go back to line 127 and I don't know if there's a way to specify that I want to copy to line number 247 (without subtracting, of course).
Regards

A: The relevant documentation is :help change.txt. I'll highlight a few commands
appearing in the :help copy-move sections of the change.txt help
documentation (there is much more in there!).
You can use the command line to specify the lines to yank (i.e. copy, see
:help :y):
:127,247y

It also works with relative numbers (and patterns - see :help range):
" yank lines 25 before cursor through 3 lines after
" cursor
:-25,+3y

In addition, if you know where you want to put them you can use the t
command (see :help :t):
" copy lines 10 before cursor through 2 lines after
" cursor to 5 lines after the cursor
:-10,-2t+5

You can even mix and match relative and absolute lines (and patterns - see
:help range):
" copy from line 23 through to 10 lines before cursor to
" line 51
:23,-10t51

For completeness there is the m command to move (i.e. cut and paste lines,
see :help :t):
" move lines 12 before the cursor through to the current
" line to line 27
:-12,.m27

The traces.vim plugin
I find this plugin very nice - it highlights ranges for Ex commands as you
type them on the command line (and shows you how the :substitute command will
affect your file as you compose it). It really helped me start to use the
command line more. I have this in my vimrc:
" fyi: there is extensive help documentation that's not on the github page

"immediately highlight numerical ranges once you put the comma :N,N
let g:traces_num_range_preview = 1

" window used to show off-screen matches (just 5 since I only want the gist).
let g:traces_preview_window = "below 5new"

" if value is 1, view position will not be changed when highlighting ranges or
" patterns outside initial view position. I like this since I see it all in the
" preview window setting above
let g:traces_preserve_view_state = 1

A: *

*Move to line 247,

*set a mark, e.g. a, via ma

*move to line 127

*yank from there to the mark y'a
All in all: 247ggma127ggy'a


text:
Q: Crashing when trying to parse a hex string I have a hex string in the form of "404C49474854" .
I am trying to extract the text string out of it with :
void  textFromHexString(char *hex,char *result)
{

    for(int k=1;k<strlen(hex);k+=2)
    {
         char temp[3]={0};
        sprintf(temp,"%c%c",hex[k-1],hex[k]);
        *result=char((int)strtol(temp, NULL, 16));
         result++;
        *result ='\0';
         print(temp);   //**** edit

    }

}

I call it from inside another function, with :
void somefunction()
{
            // I have p here, which prints "404C49474854"
           char text[TEXT_MAX_SIZE]={0};
            textFromHexString(p,text);
}

It works, but it works 80% of the time. in some cases it crashes, where :
-incoming hex pointer is : "404C49474854". for sure .
-where the pointer temp get a completely other values that are not even inside hex.
Is there something basically wrong with this method ?
EDIT:
Check where the line that prints inside the loop, it will print this in a very specific situation :
4Hello, world

How temp, that consist of numbers only, gets this string ? (the "Hello world", is just a string I print at the beginning of the program, also temp size is 3)

A: You can use sscanf() to directly read hexadecimal numbers of a given length, like so:
while(hex[0] && hex[1]) {
  int value;
  sscanf(hex, "%2x", &value);
  printf("%c", value);
  hex += 2;
}
printf("\n");

A: It seems as if most errors were found by the commenters, so here is code that works under the assumption that I guessed right what you want.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

// ALL CHECKS OMMITTED!

void textFromHexString(char *hex, char result[])
{
  // work on copy
  char *p = result;

  // this has more steps than necessary for clarity
  for (size_t k = 1; k < strlen(hex); k += 2) {
    // normalize input
    char first = tolower(hex[k - 1]);
    char second = tolower(hex[k]);
    // convert hexbyte to decimal number
    int f1 = (isdigit(first)) ? first - '0' : (first - 'a') + 10;
    int f2 = (isdigit(second)) ? second - '0' : (second - 'a') + 10;
    // two byte number from LSB hex to decimal (e.g.: "ab" = 171)
    int num = f1 * 16 + f2;
    // needs to store min. 3 characters plus NUL
    char temp[4] = { 0 };
    // sprintf is a bit too much for it but simple
    sprintf(temp, "%d", num);
    // concatenate temp to the result-string
    strcat(p, temp);
    // For debugging, I guess, or further work?
    printf("%s\n", temp);
  }
}

#define TEXT_MAX_SIZE 64
int main()
{
  // 0x404C49474854 = 70696391100500
  char *p = "404C49474854";
  // allocate some scratchspace on the stack
  char text[TEXT_MAX_SIZE] = { 0 };

  textFromHexString(p, text);
  // the function textFromHexString() does it in chunks of two bytes,
  // so the result is 647673717284 here
  printf("Result: %s\n", text);

  exit(EXIT_SUCCESS);
}


text:
Q: How do I deal with infinite P-values? Should I remove it? I ordered a list of genes by P-value in the form of a top.genes.matrix expression matrix. The dat.filtered dataframe is in log2 scale, which is filtered from the original dat dataframe.
Most of my top genes have infinite values. Is there an error in my code? How should I treat the infinite values? Remove it?
# Convert dat to numeric matrix
samp.matrix <- data.matrix(dat[, (3:ncol(dat))])

# Correlation Matrix
dat.cor  <- cor(samp.matrix, method="pearson", use="pairwise.complete.obs")

# Average correlation plot
dat.avg <- apply(dat.cor, 1, mean, na.rm=T)
# Remove Outlier(s)
samp.matrix <- samp.matrix[, -(grep(names(outlier), colnames(samp.matrix)))]

# Eliminate probes with rowMeans less than 0 on a log2 scale
dat.fil <- subset(samp.matrix, log2(rowMeans(samp.matrix)) > 0)
removed <- nrow(samp.matrix) - nrow(dat.fil)

# Eliminate probes with rowMeans less than 3 on a log2 scale
dat.filtered <- subset(dat.fil, rowMeans(dat.fil) > 3)
dat.filtered <- as.data.frame(dat.filtered)
removed  <- nrow(dat.fil) - nrow(dat.filtered)

# Student's t-test function
rawp <- c()
t.test.all.genes <- function(x,s1,s2) {
  x <- as.numeric(x)
  x1 <- x[s1]
  x2 <- x[s2]
  x1 <- as.numeric(x1)
  x2 <- as.numeric(x2)
  t.out <- t.test(x1,x2, alternative="two.sided",var.equal=T)
  out <- as.numeric(t.out$p.value)
  return(out)
}
# Raw p-value for ontrol and glioma samples
rawp <- apply(dat.filtered, 1, t.test.all.genes, s1=is.ctl, s2=is.glioma)

# Ordering the highest genes (by P-value) in the form of a data.frame
# Note: dat.filtered is still in log2 scale
best.genes    <- order(rawp)[1:length(rawp)]
best.genes.df <- data.frame(index=best.genes, exp=2^dat.filtered[best.genes, ], rawp=rawp[best.genes])
# Expression matrix with the 'best.genes' in the original scale (based on P-value ranking)
top.genes.matrix <- 2^dat.filtered[best.genes, ]

> dput(dat[1:5, 1:5])
structure(list(ID_REF = c("1007_s_at", "1053_at", "117_at", "121_at",
"1255_g_at"), IDENTIFIER = c("MIR4640", "RFC2", "HSPA6", "PAX8",
"GUCA1A"), NB_GSM97800 = c(4701.5, 282.7, 769.6, 1616.3, 232.7
), NB_GSM97803 = c(4735, 347.9, 287.9, 1527.2, 204.8), NB_GSM97804 = c(2863.9,
355, 199, 1793.8, 119.3)), row.names = c(NA, 5L), class = "data.frame")

> dput(dat.filtered[1:5, 1:5])
structure(list(NB_GSM97800 = c(4701.5, 282.7, 769.6, 1616.3,
232.7), NB_GSM97803 = c(4735, 347.9, 287.9, 1527.2, 204.8), NB_GSM97804 = c(2863.9,
355, 199, 1793.8, 119.3), NB_GSM97805 = c(5350.2, 319.9, 182.8,
1880, 180.2), NB_GSM97807 = c(4789.4, 294.2, 204.3, 1012, 156.7
)), row.names = c("1007_s_at", "1053_at", "117_at", "121_at",
"1255_g_at"), class = "data.frame")

> > head(rawp)    1007_s_at      1053_at       117_at       121_at    1255_g_at      1294_at
> 6.631006e-14 1.111397e-05 5.772347e-02 9.229543e-02 7.378613e-24 1.027390e-05
>
> dput(best.genes.df[1:5, 1:5])
structure(list(index = c(29035L, 49756L, 23236L, 49011L, 15902L
), exp.NB_GSM97800 = c(960, 819.6, 3156.3, 1809.7, 2540.5), exp.NB_GSM97803 = c(1509.1,
732.7, 4206.9, 1851.2, 3455.3), exp.NB_GSM97804 = c(1121.2, 138.3,
3442.1, 645.4, 1764.5), exp.NB_GSM97805 = c(1365.6, 431.6, 2783.3,
1261.8, 1990.1)), row.names = c("219752_at", "240512_x_at", "213938_at",
"239767_at", "206456_at"), class = "data.frame")
>
> dput(top.genes.matrix[1:5, 1:5])
structure(list(NB_GSM97800 = c(9.7453140114e+288, 5.29888441356601e+246,
Inf, Inf, Inf), NB_GSM97803 = c(Inf, 3.67009936848685e+220, Inf,
Inf, Inf), NB_GSM97804 = c(Inf, 4.2899121663437e+41, Inf, 1.92645647596287e+194,
Inf), NB_GSM97805 = c(Inf, 8.40516277768061e+129, Inf, Inf, Inf
), NB_GSM97807 = c(Inf, 5.18689446110124e+179, Inf, Inf, Inf)), row.names = c("219752_at",
"240512_x_at", "213938_at", "239767_at", "206456_at"), class = "data.frame")

A: This is kind of a shot in the dark given your presented data is slightly murky, but a quick survey shows that:
2^(c(1e1, 1e2, 1e3, 1e4, 1e5))
[1]  1.024000e+03  1.267651e+30 1.071509e+301           Inf           Inf

So if any(dat.filtered[best.genes, ] > 1e4) that will clue you in to where R is converting values that are 'too large' for it to think about to Inf.


text:
Q: JTA Transaction Scope I am using JTA transaction manager in a spring message listener application. The Database interface is maintained in a seperate project and added as dependency to the listener and the class is annotated with Transactional and the context file in the dependent project is configured with jta transaction manager bean definition.
In this case what will be the scope of transaction, for example if there is a delay in the listener will it come under the scope of transaction since the context is not imported to the main listener project? Also how do the transaction time out works, Is it applicable only for classes annotated with @Transactional or if there is any delay in other methods outside of this class, do jta manage this?


text:
Q: onclick doesn't work properly with bootstrap I tried to use onclick event with Bootstrap radio-buttons to get names and attributes but some how it didn't go well.
Some of the radio-buttons triggered the event but didn't get the name or class ("undefined") and some didn't respond at all.

  <input type="radio" class="myClass" name="options" id="option1" onclick="updateODid()" autocomplete="off" > Radio 1
  <input type="radio" class="myClass" name="options" id="option2" onclick="updateODid()" autocomplete="off"> Radio 2
  <input type="radio" class="myClass" name="options" id="option3" onclick="updateODid()" autocomplete="off"> Radio 3
  <input type="hidden" class="findme" value="found me!">

      <input type="radio" class="myClass" name="options" id="option1"       onclick="updateODid()" autocomplete="off" > Radio 1

      <input type="radio" class="myClass" name="options" id="option2" onclick="updateODid()" autocomplete="off"> Radio 2

      <input type="radio" class="myClass" name="options" id="option3" onclick="updateODid()" autocomplete="off"> Radio 3

jsfiddle.net/2sc8mc7L/6/

A: It's not working because you have mixed javascript and jquery in a wrong way.
Please check updated snippet : https://jsfiddle.net/2sc8mc7L/12/
The onclick function should be as below :
$(".myClass").on('click',function(){
  radioButtonClick($(this));
});

$("label.btn-primary").on('click',function(){
  radioButtonClick($(this).find('.myClass'));
});

function radioButtonClick(_this){
  alert("I'm in!")
  alert (_this.attr('name'));
  alert (_this.attr('class'));
  alert (_this.closest(".theContainer").find(".findme").val());
}

A: You can try like this, Use updateODid(this) for onclick and it will use current instance

function updateODid(button)
 {
  //alert("I'm in!")
  alert ($(button).attr('name'));
    alert ($(button).attr('class'));
    alert ($(button).closest(".theContainer").find(".findme").val())
 }

    <input type="radio" class="myClass" name="options" id="option1" onclick="updateODid(this)" autocomplete="off" > Radio 1

    <input type="radio" class="myClass" name="options" id="option2" onclick="updateODid(this)" autocomplete="off"> Radio 2

    <input type="radio" class="myClass" name="options" id="option3" onclick="updateODid(this)" autocomplete="off"> Radio 3

    <input type="hidden" class="findme" value="found me!">

      <input type="radio" class="myClass" name="options" id="option1"       onclick="updateODid(this)" autocomplete="off" > Radio 1

       <input type="radio" class="myClass" name="options" id="option2" onclick="updateODid(this)" autocomplete="off"> Radio 2

       <input type="radio" class="myClass" name="options" id="option3" onclick="updateODid(this)" autocomplete="off"> Radio 3


text:
Q: Why does a method reference to ctor that "throws" ... throw as well? I am looking for an elegant way to create a factory for dependency injection. In my case, the factory simply has to call a one-argument constructor. I found this answer outlining how to use a Function<ParamType, ClassToNew> for such purposes.
But my problem is: in my case, my ctor declares to throw some checked exception.
What I don't get: creating that Function using a method reference to that constructor doesn't work. As in:
import java.util.function.Function;

public class Mcve {
    public Mcve(String s) throws Exception {
        // whatever
    }
    public static void main(String[] args) {
        Function<String, Mcve> mcveFactory = Mcve::new;
    }
}

tells me about "Unhandled exception: java.lang.Exception" for Mcve::new. Although this code is not invoking the constructor.
Two questions:

*

*why that error? The above code does not invoke the ctor (yet)?

*are there any elegant ways to solve this puzzle? ( simply adding throws Exception to my main() does not help )

A: You need to provide a custom interface ThrowingFunction which has one method that throws Exception.
public interface ThrowingFunction<ParameterType, ReturnType> {
    ReturnType invoke(ParameterType p) throws Exception;
}

public class Mcve {
    public Mcve(String s) throws Exception {
        // whatever
    }
    public static void main(String[] args) {
        ThrowingFunction<String, Mcve> mcveFactory = Mcve::new;
    }
}

Using this approach results in calling mcveFactory.invoke("lalala"); forcing you to handle the exception thrown by the constructor.
Reason for the error is that the actual function reference you want to store  (not 100% sure about the terminology) throws an exception and therefore the types simply do not match up. If you could store Mcve::new inside a function then whoever calls the function no longer knows an Exception can be thrown. What would then happen if the exception would actually be thrown? Both throwing the exception and discarding it do not work.

Alternative: if you need to actually retrieve a Function<String, Mcve> in the end then you need to write a function (or lambda) that invokes the constructor, catches the exception and either discards it or rethrows it wrapped inside a unchecked RuntimeException.
public class Mcve {
    public Mcve(String s) throws Exception {
        // whatever
    }

    public static void main(String[] args) {
        Function<String, Mcve> mcveFactory = parameter -> {
            try {
                return new Mcve(parameter);
            } catch (Exception e) {
                throw new RuntimeException(e); // or ignore
            }
        };
    }
}

I would argue that the error message itself is at least a bit misleading since you normally see it when actually invoking the method. I can certainly understand the confusion resulting in the first sub-question. It would be clearer (sadly not possible) to state something like

Incompatible types Function<String,Mcve> vs. Function<String,Mcve> throws Exception.

A: I had to do that just recently... If you can change the class definition, you could use the infamous sneaky throws way of doing things:
static class OneArg {

    private final String some;

    @SuppressWarnings("unchecked")
    public <E extends Exception> OneArg(String some) throws E {
        try {
            this.some = some;
            // something that might throw an Exception...
        } catch (Exception e) {
            throw (E) e;
        }
    }

    public String getSome() {
        return some;
    }
}

Function<String, OneArg> mcveFactory = OneArg::new;

A: I've been thinking about this for a while and indeed - if you want to have a Function that declares clearly your intention, I think that you need to have a Function that would extend the java.util.Function, something like this:
@FunctionalInterface
public interface ThrowingFunction<T, R> extends Function<T, R> {

    R applyWithExc(T t) throws Exception;

    @Override
    default R apply(T t) {
        try {
            return applyWithExc(t);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

You can btw choose which method you call when you define your constructor reference - the one that would throw an Exception and one that would silently wrap it with a RuntimeException.


text:
Q: Default Sort on a Spring Data JPA Repository Method with Custom Query and Pageable Parameter I have the following repository method that works exactly the way I need it to iff the user provides a sort column in the page parameter:
public interface IdentityRepository extends JpaRepository<Identity, String> {

    @Query("select distinct ident from Identity ident left outer join ident.authorities authority "
        + "where ("
            + "(:src is null or ident.source = :src) and "
            + "(:org is null or ident.organization = :org) and "
            + "(:auth is null or authority.authority = :auth) and "
            + "(:authSrc is null or authority.authoritySource = :authSrc))")
    @RestResource(path="filter")
    public Page<Identity> findWithFilter(
        @Param("src") String source,
        @Param("org") String org,
        @Param("auth") Authority auth,
        @Param("authSrc") AuthoritySource authSrc,
        Pageable page);
...
}

If the caller provides a page count, but not a sort column, they will get back the correct number of results when retrieving all the pages. However, many of the entities will be duplicated, so even though the result count is correct, many expected entities are missing and others are duplicated (or triplicated).
What I'm wondering is if there is a way to provide a default sort column and direction if the user does not specify one. I've learned that @EnableSpringDataWebSupport can help here, but we're not using Spring MVC, so I don't have any controllers to attach the @SortDefaults to. We are using Spring Data Rest though. Also, I've tried changing the method name to findWithFilterOrderByIdAsc, but that did not seem to help. Ran across this issue in the Spring JIRA, which I believe is exactly what I need, but until it's resolved, does anyone know of a work around?
Here's my entity...
@Entity
@Table(name = "identity", indexes = { @Index(columnList = "user_id", unique = true) })
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Audited
public class Identity implements Serializable, Identifiable<String> {

    /**
     * The unique identifier for this identity within the IDD application.
     */
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "IDDUidGenerator")
    @GenericGenerator(name = "IDDUidGenerator")
    private String id;
    /**
     * The name of the identity provider wherein this identity is originally defined.
     */
    @Column(name = "source")
    private String source = INTERNAL_SOURCE;
    /**
     * The unique identifier for this identity within the customer's identity provider.
     */
    @NotNull
    @Column(name = "user_id", nullable = false, unique = true)
    private String userId;
    /**
     * The roles this identity is authorized to perform.
     */
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "identity", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<IdentityAuthority> authorities = new HashSet<>();
...
}

And its sub-entity...
@Entity
@Table(name = "identity_authority")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Audited
public class IdentityAuthority implements Serializable, Identifiable<Long> {

    private static final long serialVersionUID = -5315412946768343445L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @XmlTransient
    @JsonIgnore
    private Long id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "identity_id", nullable = false)
    @XmlTransient
    @JsonIgnore
    private Identity identity;

    @Enumerated(EnumType.STRING)
    @Column(name = "authority", length = 20, nullable = false)
    private Authority authority;

    @Enumerated(EnumType.STRING)
    @Column(name = "authority_source", length = 30, nullable = false)
    private AuthoritySource authoritySource;
...
}

Here's the test case I ran to demonstrate the problem...
@Test
public void testPagedRequestsReturnAllResults() {
    // Create identities
    String source = "One Hundred Identities Generator";
    int numIdentities = 100;
    int pageSize = 5;
    List<Identity> input = new ArrayList<>();
    for (int i=0; i<numIdentities; i++) {
        Identity identity = new Identity();
        identity.setUserId(UUID.randomUUID().toString());
        identity.setSource(source);
        input.add(identity);
    }

    // Save identities
    List<Identity> output = repository.saveBulk(input);
    Set<String> savedIds = collectIds(output, null);
    assertThat(savedIds.size()).isEqualTo(numIdentities);

    // Test Sorted Find Filter with Paging (THIS PASSES)
    Pageable pageRequest = new PageRequest(0, pageSize, new Sort(Direction.ASC, "id"));
    Set<String> foundPagedIds = new HashSet<>();
    do {
        Page<Identity> page = repository.findOrderByIdAsc(source, null, null, null, pageRequest);
        List<Identity> foundIdentities = page.getContent();
        foundPagedIds = collectIds(foundIdentities, foundPagedIds);
        pageRequest = page.nextPageable();
    } while (pageRequest != null);
    assertThat(foundPagedIds.size()).isEqualTo(numIdentities);
    assertThat(foundPagedIds).isEqualTo(savedIds);

    // Test Unsorted Find Filter with Paging (THIS FAILS)
    pageRequest = new PageRequest(0, pageSize);
    foundPagedIds = new HashSet<>();
    do {
        Page<Identity> page = repository.findOrderByIdAsc(source, null, null, null, pageRequest);
        List<Identity> foundIdentities = page.getContent();
        foundPagedIds = collectIds(foundIdentities, foundPagedIds);
        pageRequest = page.nextPageable();
    } while (pageRequest != null);
    assertThat(foundPagedIds.size()).isEqualTo(numIdentities);
    assertThat(foundPagedIds).isEqualTo(savedIds);
}


text:
Q: How to set DropDownChoice selected at particular index/choicedata in apache wicket? Hi I have created DropDownChoice component of apache wicket. now what I want to do is that after component creation I want to set some choice as a default selected based on certain condition. I am not getting it anyhow. Anyone can plz help me out.
Thanks in advance.

A: If you need to select multiple options then you should use org.apache.wicket.markup.html.form.ListMultipleChoice#ListMultipleChoice(java.lang.String, org.apache.wicket.model.IModel<? extends java.util.Collection<T>>, org.apache.wicket.model.IModel<? extends java.util.List<? extends T>>). The first model holds the selections, and the second holds all possible options.


text:
Q: use of expediency and entail? I wonder if the following sentence conveys the right meaning.

Even if they make a big mistake, expediency entails to forgive each other for the bigger cause of friendship.

Can expediency entail something?

A: Expediency is convenience, and entails roughly means requires (or "necessarily involves", since "requires" evokes a sense of active command rather than passive prerequisite). So expediency can indeed entail something, such as forgiveness. Grammatically though (as Prof. Lawler pointed out), it cannot "entail to forgive", since entail doesn't take an infinitive complement:

Even if they make a big mistake, expediency entails forgiving each other for the bigger cause of friendship.

Now it's grammatical, but the sentence appears bloated to me because of using the words expedience, entails, and for the bigger cause of, which are OK in their place, but not among conventional words like big mistake; and elementary confustications such as ... they make a big mistake, which sounds like they're both doing it alongside each other, and any apology would have to be made to a third party.

Even if one of them makes a big mistake, convenience requires forgiveness because of their friendship.

After all that, I find myself disagreeing with the statement. Friendship is rarely structured on convenience. You might mean to say that their friendship entails forgiveness. I'm not sure where expediency came from in the first place.


text:
Q: react-native unable to push recent version of ios code to simulator I am building a react-native application that should work in both the Android simulator and the iOS simulator.  I've been developing primarily on my Windows machine, and I would use command prompt react-native run-android to see my changes in an Android simulator.  Once in a while, I would go to my mac mini, do a git pull origin master, and then run react-native run-ios to see my changes in an iOS simulator.
Everything has been working fine until a few days ago.  Now when I'm on my mac mini, the following will happen:

*

*if I run react-native run-android from my terminal, I see my latest react-native changes in the android simulator, which is perfect

*if I run react-native run-ios from my terminal, I see an EARLIER/OLDER version of my react-native changes of the ios simulator.  This is NOT what I want.  I want my ios simulator to show my latest changes the way a developer would expect.  I tried typing garbage, syntax errors, deleting files in my react-native project to see if the compiler will respect these errors and fail, but it does not.  The react-native run-ios command ignores my clearly broken project and continues to build the same earlier version of my react-native project and puts it in the ios simulator.  I tried deleting the project, and doing a fresh new git pull, but still the same issue occurs and simulator shows the same earlier version of my project.

Why won't my react-native run-ios command build the latest version of my react-native code and put it in the ios simulator?

A: Ok, I found a workaround.
I started a completely new react-native project with the react-native init <sameprojectnameasmybrokenproject>.  Then I copied all my react components and project files (The ones that I created, and not the stuff that react creates boiler templates for) and my package.json file from my broken project to my new project.  Then I ran react-native run-ios to make sure this new project works fine.

EDIT
I also copied these four files from my new project into my broken project, and it got the broken project to show the latest build versions again.

*

*ios/nutriag.xcodeproj/project.pbxproj

*ios/nutriag.xcodeproj/xcshareddata/xcschema/nutriag.xcscheme

*ios/nutriag/AppDelegate.m

*ios/nutriag/Info.plist

So something about these four files was broken in my broken project.


text:
Q: communicate with ADSF using SAML2.0 using C# I am totally new on ADFS and SAML2.0. I don't know more and want to check whether component space can meet my requirement or not.
Background:
we're using the windows AD help to store the user info using for authorization. So, we need to implement SSO function with their ADFS4.0 version Service with Saml2.0.
TODO:
Need to connect the ADFS server and get the token and authorize the same for SSO once user login to adsf login page implement this we have metadata XML file.
AS We dnt have any idea how to start working with it.

Technology need to use is with .NET core 3.1

Any help will be appreciated

A: Yes, you can use ComponentSpace.
Look here for some samples.
In addition, they have very good documentation.
Download the free trial and look at the step by step docs. for ADFS.


text:
Q: How to create a virtual machine on Azure using a python code? I am new to using the azure sdk and working with it.
I read quite a few example on how to create a virtual machine but none of them worked for me.
I am getting an error in the sms.add_os_image method prior to creating a virtual machine.
Can a VM be created without that method? what should be used as the media link and image name in that case?
A part of my current erroneous code looks like this:
#storage account:
result = sms.create_storage_account(name, desc, label, affinity_group=name)

operation_result = sms.get_operation_status(result.request_id)
print('Operation status: ' + operation_result.status)

result = sms.list_storage_accounts()
for account in result:
print('Service name: ' + account.service_name)
print('Affinity group: ' + account.storage_service_properties.affinity_group)
print('Location: ' + account.storage_service_properties.location)
print('')

#blob service:

storage_response=sms.get_storage_account_keys(name)
print "finished getting primary key " + storage_response.storage_service_keys.primary
account_key = storage_response.storage_service_keys.primary
blob_service = BlobService(account_name=name, account_key=account_key)

#container:

blob_service.create_container('containermaryland13')
target_blob_name = name+'.vhd'
os_image_url='https://{}.blob.core.windows.net/containermaryland13/{}'.format(name, target_blob_name)
image_name = '03f55de797f546a1b29d1b8d66be687a__CoreCLR-x64-Beta5-Linux-PartsUnlimited-Demo-App-201504.29'
sms.add_os_image(label=image_name, media_link=os_image_url, name=image_name, os='Linux')

linux_config = LinuxConfigurationSet(host_name='hostname', user_name='username', user_password='mypassword', disable_ssh_password_authentication=True)
os_hd = OSVirtualHardDisk(source_image_name=image_name, media_link=os_image_url)

sms.create_virtual_machine_deployment(service_name=name,
                                  deployment_name=name,
                                  deployment_slot='production',
                                  label=name,
                                  role_name=name,
                                  system_config=linux_config,
                                  os_virtual_hard_disk=os_hd,
                                  role_size='Small')
                                  """

Can someone please help me resolve this error?
Thanks!

A: Generally, if this image has already in your IMAGES Gallery , you will encounter the error as "Conflict" when you add it repeatedly. So I suggest you check this image whether has registered in your IMAGE Gallery. If your IMAGE Gallery already has the image, you can use its Image name and URL directly.
Also, I created a project for testing this method:
os_image_url='https://**.blob.core.windows.net/communityimages/**-**-**-1.vhd'
image_name = 'ub-13-4-test'
sms.add_os_image(label=image_name, media_link=os_image_url, name=image_name, os='Linux')

Before you create VM, you need create a cloud service as container for your VM.
You can see this code:
name = 'myvmPython'
location = 'East Asia'
sms.create_hosted_service(service_name=name,
    label=name,
    location=location)
linux_config = LinuxConfigurationSet(host_name=name, user_name='*', user_password='*', disable_ssh_password_authentication=True)
os_hd = OSVirtualHardDisk(source_image_name=image_name, media_link=os_image_url)

sms.create_virtual_machine_deployment(service_name=name,
                                  deployment_name=name,
                                  deployment_slot='production',
                                  label=name,
                                  role_name=name,
                                  system_config=linux_config,
                                  os_virtual_hard_disk=os_hd,
                                  role_size='Small')

By the way, I used the Python 2.7. Also, you could share your error message with us for further helps.

A: You could check your Image whether it is existed from Image Panel, as this picture shown:

Also, you can add image into Image Gallery:

If image is in your image repository, you can use its name and URL directly.

According to error message, it is mean that your project don't find VHD resource, please check your Blob URL.


text:
Q: Xcode: how to build a static library project correctly? This question will be easy for Xcode pros but for a MonoTouch developer it seems to be impossible to resolve. :-)
I'm using Xcode 4.5 and I want to target iOS 5.1 and above and iOS Simulator 5.1 and above.
I have a a library project here and it is coming with a prebuilt binary named "DemoLib" (no extension and it is 11MB in size). The library is a fat lib for Simulator and iOS 5.1+.
I can use that library without any problem.
However if I try to build the library myself, I end up with a "DemoLib.a" file (notice the extension and the size of 30MB). How can I get the same build result? What is a .a file compared to the file without extension?
I tried to build the project "for running", and "for archiving" in Xcode. Both results in the same 30MB .a file.
I was expecting some dropdown in Xcode where one could select "DEBUG" or "RELEASE" build and the latter one would create the smaller lib.

A: Of course I could never tell without seeing the framework's project file. Having said that, there is an excellent guide to creating and compiling iOS frameworks here: https://github.com/jverkoey/iOS-Framework
Using the above guide, you should be able to recreate your framework's project from scratch, add the files you have to it, and properly compile it.
Hope this helps! :)

A: Did it come with a Makefile? Create a new target, set the build settings of the target to what's in the Makefile, then set your project to depend on that new target.
A file with the .a is a static library, which means it depends on nothing external and all the code it needs is compiled inside it. I think no extension generally implies dynamic library, which means it'll depend on some dependencies being present on your system to link against. Maybe that's why the .a is so much bigger. I think Xcode will build static by default because iOS does not allow the use of dynamic libraries.
The dropdown for what to build is in your scheme. Command+shift+< to view your scheme. Within the scheme you can edit which environment each method of building will use.


text:
Q: OnDraw( ) not getting called when invalidate is called I am using a View extended from View group and the onDraw is not getting called when I call invalidate.Can any one please explain?
 The code is given below
public class BarGraph extends View {
private int viewHeight;
private int viewWidth;                          // height and width of bar graph dynamically calculated.
private int mGraphColor;                        // the colour of the bar graph.

private ArrayList<Integer> mTodays;             // The array list that handles the input to draw the graph.
private final int barCount  =   20;             // Number of bars in the bar graph...here set as 20.

/*
 * The maximum action value a bar can take.
 * This is calculated based on the action array
 * passed to the chart.
 */

private int yMax    =   0;

private Paint graphColor;

public BarGraph(Context context, int graphColor) {
    super(context);
    this.setWillNotDraw(false);
    mGraphColor     =   graphColor;
    setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    initializePaintObjects();
}

public BarGraph(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setWillNotDraw(false);
    initializePaintObjects();
}

private void initializePaintObjects(){
    graphColor = new Paint();
    graphColor.setColor(mGraphColor);
    graphColor.setStyle(Style.FILL);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if(mTodays == null)                     // If the array list is empty.
        return;
    if(yMax <= 0)
        return;
    int left    =   0;

    viewHeight  = getHeight();
    viewWidth   = getWidth();

    if((viewWidth % barCount) > 0){     //adjusting the view width so that bars correctly fits in
        int newWidth    =   (int) (Math.floor(viewWidth / barCount) * barCount);
        left            =   (int) Math.floor(((viewWidth - newWidth)/2));
        viewWidth       =   (int) Math.floor((viewWidth / barCount) * barCount);
    }

    int columnWidth     =   2;
    columnWidth         =  (int) Math.floor(viewWidth / barCount);

    int xFactor         =   1;
    xFactor             =   (int) Math.ceil(columnWidth * 0.33);

    int barWidth        =   1;
    barWidth            =   columnWidth - xFactor;

    graphColor.setStrokeWidth(barWidth);

    int j = 0;

    for(int i = 0; i < mTodays.size() ; i++){
        int todayValue      =   mTodays.get(i);
        float todaysHeight;
        if(todayValue == 0){
            todaysHeight    =   (float) (viewHeight-viewHeight*(.001));
        }else{
            todaysHeight    =   getYValue(todayValue);
        }

        canvas.drawLine(((j*columnWidth)+xFactor + left) , viewHeight, ((j*columnWidth)+xFactor + left), todaysHeight, graphColor);
        j++;
    }

}

public void setData(ArrayList<Integer>todays){

    mTodays         =   todays;

    yMax            =   0;
    for (int val : mTodays){
        yMax        =   yMax > val ? yMax : val;
    }
    invalidate();
}

private int getYValue(int item){
   int percent = (item * 100)/yMax;
   return (viewHeight) - ((percent * viewHeight)/100);
}

}

A: Thanks for all your attempts.The problem was actually in the Main Activity.
The following is the correct code
final Handler handler = new Handler();
                Timer timer2 = new Timer();
                TimerTask testing = new TimerTask() {
                    public void run() {
                        handler.post(new Runnable() {
                            public void run() {
                                for(int j=0;j<19;j++){
                                    todays.set(j, todays.get(j+1));
                                }
                                Random diceRoller = new Random();
                                todays.set(19,  diceRoller.nextInt(100)*10+1);
                                MainActivity.this.runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        // TODO Auto-generated method stub
                                        bargraph.setData(todays);
                                    }
                                });
                            }

                        });

I had not written the runOnUiThread at first...My bad...


text:
Q: UNION types text and jsonb cannot be matched PostgreSQL I have 3 tables on which I am trying to union all, one of the tables contains many jsonb columns.
I am doing this query,
  CREATE
  OR replace view datasets_dashboard AS WITH core AS
  (
    SELECT
      'twitch' AS tab_name,
      tw.id,
      tw.oid,
      tw.channel,
      tw.language,
      tw.mature,
      tw.partnered,
      tw.metadata,
      NULL AS alternate_text,
      NULL AS archived_url,
      NULL AS base_meme_name,
      NULL AS file_size,
      NULL AS md5_hash,
      NULL AS meme_id,
      NULL AS meme_page_url,
      NULL AS charge,
      NULL AS energy,
      NULL AS event,
      NULL AS invariant_mass,
      NULL AS run,
      NULL AS momemtum,
      NULL AS phi_angle,
      NULL AS pseudorapidity,
      NULL AS transverse_momemtum
    FROM
      public.twitch AS tw
    UNION ALL
    SELECT
      'memegen',
      meme.id,
      meme.oid,
      NULL AS channel,
      NULL AS language,
      NULL AS mature,
      NULL AS partnered,
      NULL AS metadata,
      meme.alternate_text,
      meme.archived_url,
      meme.base_meme_name,
      meme.file_size,
      meme.md5_hash,
      meme.meme_id,
      meme.meme_page_url,
      NULL AS charge,
      NULL AS energy,
      NULL AS event,
      NULL AS invariant_mass,
      NULL AS run,
      NULL AS momemtum,
      NULL AS phi_angle,
      NULL AS pseudorapidity,
      NULL AS transverse_momemtum
    FROM
      public.memegen AS meme
    UNION ALL
    SELECT
      'collision',
      collision.id,
      collision.oid,
      NULL AS channel,
      NULL AS language,
      NULL AS mature,
      NULL AS partnered,
      NULL AS metadata,
      NULL AS alternate_text,
      NULL AS archived_url,
      NULL AS base_meme_name,
      NULL AS file_size,
      NULL AS md5_hash,
      NULL AS meme_id,
      NULL AS meme_page_url,
      collision.charge,
      collision.energy,
      collision.event,
      collision.invariant_mass,
      collision.run,
      collision.momemtum,
      collision.phi_angle,
      collision.pseudorapidity,
      collision.transverse_momemtum
    FROM
      public.collision_electron AS collision
  )
  SELECT * FROM core;

from above these columns are jsonb

*

*tw.metadata

*collision.charge,

*collision.energy,

*collision.event,

*collision.invariant_mass,

*collision.run,

*collision.momemtum,

*collision.phi_angle,

*collision.pseudorapidity,

*collision.transverse_momemtum

I am trying to make them NULL for other tables where they wont exist but its throwing me such error as types text and jsonb cannot be matched. I have seen a few other answered question regarding this, But I am not sure where to use CAST in the query to make it work for jsonb type.
any help would be wonderful thank you.

A: Cast NULL to jsonb as in:
NULL::jsonb AS base_meme_name,

Most (if not all) types can be casted to text which is why postgres assumes text (I assume:-) if no other information is given. One could argue that it should be possible to infer the correct type from the union, but I once again guess that it does not for practical reasons.


text:
Q: Are there any examples of PyParsing which add types to output as well as structured tokenization? All the PyParsing examples I've seen end of up producing a structured nested list of tokens like this :
["eat",["stolen","food"]]

etc.
I can't seem to find an example that would tag these outputs with types to give me something like :
[{"type":"verb","value":"eat"},[{"type":"adj","value":"stolen"},{"type":"noun","value":"food"}]]

Can PyParsing do this? (Even if the format is different.) And, if so, can anyone point me to an example?
cheers
Phil

A: See "How to structure the returned ParseResults" in the PyParsing quick reference.


text:
Q: Thread termination difference between C & Java From my understanding, a C process will be terminated as soon as the main (parent) thread returns or reaches the end of execution. (This can be changed using pthread_join in the main thread).
However, a Java process will still keep running until all the threads finishes their execution even if the main thread has returned or finished. (This can be changed by making the child threads run as daemons in Java).
Why did Java choose to do it this way?
C code sample:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>

pthread_t tid[2];

void *doSomeThing(void *arg) {
    unsigned long i = 0;
    pthread_t id = pthread_self();

    if (pthread_equal(id, tid[0])) {
        printf("\n First thread processing\n");
    }
    else {
        printf("\n Second thread processing\n");
    }

    for (i = 0; i < (0xFFFFFFFF); i++);

    printf("\n Threads finished.\n");
    return NULL;
}

int main() {
    int i = 0;
    int err;

    while(i < 2)
    {
        err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
        if (err != 0)
            printf("\ncan't create thread :[%s]", strerror(err));
        else
            printf("\n Thread created successfully\n");

        i++;
    }

    sleep(2);
    printf("\nProcess Exit\n");
    return 0;
}

C Output
Thread created successfully

First thread processing

Thread created successfully

Second thread processing

Process Exit

Neither thread finishes it's task before process exits.
However, in Java:
Java Code Sample
public class ThreadTermination implements Runnable {

    @Override
    public void run() {
        System.out.println("Thread running.");
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread ending.");
    }

    public static void main(String[] args) {
        ThreadTermination t1 = new ThreadTermination();
        ThreadTermination t2 = new ThreadTermination();

        Thread thr1 = new Thread(t1);
        System.out.println("Thread 1 starting.");
        thr1.start();
        Thread thr2 = new Thread(t2);
        System.out.println("Thread 2 starting.");
        thr2.start();

        System.out.println("Main thread finished.");
    }
}

Java Ouptut
Thread 1 starting.
Thread 2 starting.
Thread running.
Main thread finished.
Thread running.
Thread ending.
Thread ending.

Both threads completes its task even though the main thread has finished long back. As can be seen, there are no daemon threads.
Edit: From Java doc:
The Java Virtual Machine continues to execute threads until all threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method

A:
From my understanding, a C process will be terminated as soon as the main (parent) thread returns or reaches the end of execution.

No. A C process will not terminate just because the first thread reaches the end of its execution. To prove it, change your code from:
    sleep(2);
    printf("\nProcess Exit\n");
    return 0;
}

To:
    sleep(2);
    printf("\nThread Exit\n");
    pthread_exit(0);
    return 0; // will never execute
}

The process will terminate if the first thread returns from main. The C standard (section 5.1.2.2.3) says that returning from main is equivalent to calling exit, and this is what terminates the process. The thread then terminates because the process terminates, not the other way around.

A: Your statement is incorrect in several aspects:

*

*The Java application will exit upon the main thread terminates, unless you have any daemon threads.

*And the C++ program won't immediately terminate - after the main thread finishes, there are still clean up to do before the entire process is finished.


text:
Q: FileStream or WebClient I'm currently generating some preview with the Wopi and the Office Web App technologies from Microsoft, and i'm having an issue. Sorry for my bad english, but i'll try to express myself as well as possible.
So ! I'm generating the preview by downloading a file's content and storing it into an HttpContent.
First, i tried this on files that were in the ~/App_Data/ of my project. I read it's content with the FileStream class and transformed it into HttpContent byusing this : StreamContent(myFileStream). So, THIS is working perfectly !
BUT, i need my project to deal with files that are stored on servers only reachable from the internet (So physical urls should look like this : http://myServer/res/file.pdf for example). I couldn't use the FileStream class here, so i did it like this :
byte[] tmp;
using (WebClient client = new WebClient())
{
    client.Credentials = CredentialCache.DefaultNetworkCredentials;
    tmp = client.DownloadData("http://myServer/res/file.pdf");
}
myHttpContent = new ByteArrayContent(tmp);

The thing is that this little sample seems to be working, but the preview isn't generated after that, and it is the only piece of code that i changed. I checked some stuff befor posting here, so : i do have access to the file and i am allowed to read it.
So, my question is, it this a good way to get the files content, is it outdated, what should i do to try to patch this ?
I hope my post is clear enough and thanks for reading !

A: I think you can do the following
MemoryStream ms;
using (WebClient client = new WebClient())
{
    client.Credentials = CredentialCache.DefaultNetworkCredentials;
    ms = new MemoryStream(client.DownloadData("http://myServer/res/file.pdf"));
}

Then use the memory stream should behave identically to your filestream.


text:
Q: How to Disable Optimization for One File in Xcode My Xcode project depends on another library, that cause errors in my project when I built it with [-O3] option.
The errors are in just one file. So I want to turn off the [-O3] option for that file.
Is it possible?

A: Open the target, look under Build Phases. Open the Compile Sources step. Locate the file in question, and click the Compiler flags column to the right.
Enter -O0 to turn off optimisation.


text:
Q: WM6.5 Read recived email with pocket outlook I'm out of ideas. Tried many solution for hours without solving.
Problem:
Programmatically read received emails and download attachments.
Okey, so got configured outlook mail on device.
Tried with Pocket Outlook dll and nothing.
Going to jump over the windows.

A: "Tried with Pocket Outlook dll and nothing" is not at all helpful.  What did you try?  What, exactly, was the result?  Reading emails is done with the Pocket Outlook Object Model (POOM).  You don't even say what language you're trying to use, but here are some places to start.
For Managed code use the EmailMessage class in the Microsoft.WindowsMobile.PocketOutlook namespace namespace.
For native code, it's a little less intuitive that you have to use MAPI, but it's still well documented.  Here's an example of getting an email body.