text:
Q: Passing fstream reference as function parameter in C++11 I've just encountered an problem today: The following code seems to work in MSVC++ 2010 but not with Clang LLVM 4.1 (with GNU++11).
#include <fstream>

void foo(std::fstream& file){
    file << "foo";
}
int main() {
   std::fstream dummy("dummy");
   foo(dummy);
   return 0;
}

generates
Invalid operands to binary expression (std::fstream (aka basic_fstream<char>) and const char[4])

on Clang. I thought passing iostream arguments by reference would be common practice in C++. I'm not even sure if this is related to clang, C++11 or anything else.
Any idea how I can pass streams to functions then?

A: I assume that your original code (that you only partially posted in your original question) looked something like this:
#include <iosfwd>

void foo(std::fstream& file){
    file << "foo";
}

int main() {
   std::fstream dummy("dummy");
   foo(dummy);
   return 0;
}

Indeed, this gives the following error message with clang++ 3.2
Compilation finished with errors:
source.cpp:4:10: error: invalid operands to binary expression ('std::fstream' (aka 'basic_fstream<char>') and 'const char [4]')
file << "foo";
~~~~ ^ ~~~~~
source.cpp:8:17: error: implicit instantiation of undefined template 'std::basic_fstream<char, std::char_traits<char> >'
std::fstream dummy("dummy");
^
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../include/c++/4.7/iosfwd:118:11: note: template is declared here
class basic_fstream;
^
2 errors generated.

Unfortunately, you only posted the first error message but not the second.
From the second error message, it is obvious that you only #include <iosfwd> but not #include <fstream>. If you fix that, everything will be OK.
Please post both the complete code and all the error messages next time.


text:
Q: p:commandButton action not working in p:confirmDialog I have a functionality where I have to call my managed bean through my confirmation dialog box which is for delete button. When the user clicks on delete button there is a confirmation dialog box that pops up and onclick of "Yes" my relative managed bean should get called. But I am not able to do it.
<p:commandButton id="Delete" action="#{tbeanId.delete}" icon="ui-icon ui-icon-trash"
   value="Delete" title="GDeleteButton" ajax="false" onclick="PF('groupDeleteConfirm').show();" type="button">
   <p:confirm header="Delete Record" message="Are you sure about deleting this record?" icon="ui-icon-alert"/>
</p:commandButton>

<p:confirmDialog global="true" showEffect="fade" hideEffect="explode" widgetVar="groupDeleteConfirm">
   <p:commandButton title="GDelYesButton" value="Yes" oncomplete="PF('groupDeleteConfirm').hide()" " />
   <p:commandButton title="GDelNoButton" value="No" onclick="PF('groupDeleteConfirm').hide()" type="button" />
</p:confirmDialog>

A: When you use a p:commandButton for the action that needs to be done on the server, you can not use type="button" because that is for Push buttons which are used to execute custom javascript without causing an ajax/non-ajax request to the server.
For this purpose, you can dispense the type attribute (default value is "submit") or you can explicitly use type="submit".
Hope this will help someone!

A: When you use the p:confirmDialog with global="true" the confirm/cancel buttons are (somewhat unintuitively) identified by these 2 styleClasses:
styleClass="ui-confirmdialog-yes"
styleClass="ui-confirmdialog-no"

Then the action will be called and show()/hide() will happen automatically. Ajax should be true on the main button and you don't need type="button" so all in all it will be much simpler:
<p:commandButton id="delete"
                 action="#{trafficExpenseItemsMBean.deleteExpenseItemsGroup}"
                 icon="ui-icon ui-icon-trash"
                 value="Delete"
                 title="GDeleteButton">
    <p:confirm header="Delete Record"
               message="Are you sure about deleting this record?"
               icon="ui-icon-alert"/>
</p:commandButton>

<p:confirmDialog global="true" showEffect="fade" hideEffect="explode">
    <p:commandButton title="GDelYesButton" value="Yes" styleClass="ui-confirmdialog-yes"/>
    <p:commandButton title="GDelNoButton" value="No" styleClass="ui-confirmdialog-no" />
</p:confirmDialog>

Another option would be to make it non-global. Then you'd need to move the action to the yes-button and the message to the p:confirmDialog as in
<p:commandButton id="delete"
                 icon="ui-icon ui-icon-trash"
                 value="Delete"
                 title="GDeleteButton"
                 onclick="PF('groupDeleteConfirm').show()">
</p:commandButton>
<p:confirmDialog message="Are you sure about deleting this record?"
                 showEffect="fade"
                 hideEffect="explode"
                 widgetVar="groupDeleteConfirm">
    <p:commandButton title="GDelYesButton"
                     value="Yes"
                     action="#{trafficExpenseItemsMBean.deleteExpenseItemsGroup}"
                     oncomplete="PF('groupDeleteConfirm').hide()"
                     update=":growl"/>
    <p:commandButton title="GDelNoButton"
                     value="No"
                     oncomplete="PF('groupDeleteConfirm').hide()"/>
</p:confirmDialog>

I'm not sure you really want those title's on the buttons though, as they are shown to the user.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate React Components After Typing npm install --save-dev create-react-component-folder it runs the script but as far as i can tell never makes the folder does anyone know where this folder would be located thanks.

A: 'npx crcf myComponent' is what's needed to create the folder.

A: use npx crcf myComponent as the script runs globally from terminal
as in description
$ npm install --save-dev create-react-component-folder
$ npx crcf myComponent


text:
Q: link to a sample database for tests Oracle 11g express edition Could someone please provide me with a link to some database script (creation with values inserted), like the one used in W3C schools tutorials ?
 I want to use it to test some SQL scripts.

A: A friend provided me with the following link to google code, a project that aims at converting northwind database SQL code to be compatible with many DBMS.


text:
Q: Child Route not displaying correctly in angular I am using a stepper in angular and I need to display a component in one of the steps. I need to click on a button to load that component. I can see the child component getting inserted but it's not displaying correctly. When I inspect and go to that element in "Elements" tab then I can see the component inserted and when I hover then browser highlights at the right most corner. Here is routing module:
const routes: Routes = [
  {
      path: '',
      redirectTo: 'items',
      pathMatch: 'full'
  },
  {
    path: 'items',
    component: ItemsComponent,
    pathMatch: 'full'
  },
  {
    path: 'item/:id',
    component: ItemStepperComponent,
    children: [
      {path: 'subitem', component: SubItemComponent, pathMatch: 'full'}
    ]
  },
];

@NgModule({
  declarations: [],
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ]
})

parent-stepper.html
<mat-horizontal-stepper #stepper [linear]="true">
   <mat-step *ngFor = "let step of steps; let i=index" [editable]="true">
     <button type="button" mat-raised-button (click) = "load()">Add Sub Item</button>
       <router-outlet></router-outlet>
   </mat-step>
</mat-horizontal-stepper>

parent-stepper.component.ts
load(){
   this._route.navigate(['subitem'], {relativeTo: this._ac});
}

If someone can suggest what I'm doing wrong here?
Note: I figured out that the problem is primarily with Material stepper. If I add a condition in  then it displays it correctly. But the problem with this is that it loads the same component multiple times. If someone can suggest a more elegant solution.

A: If you are having child component you need to add  in it's parent i.e ItemStepperComponent html. which renders its child router from it's html file.

A: try this code your problem will rectify
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {MainComponent} from './main/main.component';
import {Test1Component} from './test1/test1.component';
import {Test2Component} from './test2/test2.component';
import {Test3Component} from './test3/test3.component';
import {Test4Component} from './test4/test4.component';

const routes: Routes = [
  {path:'',redirectTo:'main', pathMatch:'full'},
  {
    path:'main', component:MainComponent,
    children: [
      { path:'',redirectTo:'Test1',pathMatch:'full'},
      { path:'Test1',component:Test1Component },
      { path:'Test2',component:Test2Component },
      { path:'Test3',component:Test3Component },
      { path:'Test4',component:Test4Component },
    ]
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

                    Test1

                    Test2

                    Test3

                    Test4

    <router-outlet></router-outlet>


text:
Q: Stuck at Grub2 Prompt I have Windows XP installed in my system. For some work, I downloaded an ISO of the light version of Kali on a separate internal hard disk partition (G:) and installed Grub2 on the same drive to boot it from there (I had not yet booted Kali)
Now when I restart my computer, I get stuck at the Grub2 prompt and unable to do anything from here.
I would like to boot into my installed Windows and remove the Grub Bootloader. Any suggestions on how I can do that?
Edit: My disk drive is corrupted. Any methods relying on this won't be of much help.

A: *

*Insert your Windows XP USB or PXE and boot it

*Open the recovery console

*Type: fdisk /mbr

*Reboot

In recovery console, other options include:
Type 'help' for the commands that the RC can run.

*

*Try 'fixboot'. This re-writes the boot record.

*Try 'fixmbr'; again, this may damage a partition table that it doesn't understand, so be wary of taking this step... you may want to use this as a last resort and only if you have a single partition on the disk.

src: https://www.wikihow.com/Use-Windows-Recovery-Console-from-XP-CD

A: Boot from a Windows XP installation media and press R at the "Welcome" screen to get into Recovery Console. Then use the fixmbr command to overwrite Grub2 with the standard Windows MBR code.


text:
Q: How to Correctly Type Next.js getStaticPaths as a Function Declaration I'm working with typing getStaticPaths (guide docs, API reference docs) but all of the documentation that I can find relates to declaring it as a function expression. I'm looking to code it as a function declaration but can't find any documentation on it and am having trouble getting it to work.
As a function expression (this works):
import { GetStaticPaths } from 'next';

export const getStaticPaths: GetStaticPaths = async () => {
  return {
    paths: [{ params: { id: 'example' } }],
    fallback: false,
  }
}

How can I properly use a function declaration for getStaticPaths and get the typing right?

A: This is achieved by making use of the GetStaticPathsResult type from next.
import {GetStaticPathsResult} from 'next';

export async function getStaticPaths(): Promise<GetStaticPathsResult> {
  return {
    paths: [{ params: { id: 'example' } }],
    fallback: false,
  }
}


text:
Q: MySQL Error: Lock wait timeout exceeded; try restarting transaction Query I found many people got the same error message from MySQL with the same error state=41000 amd same error code=1205.
However most of them involved 2 transactions and a deadlock.
Based on SHOW ENGINE INNODB STATUS output, there is only 1 transaction:

=====================================
140715  4:42:37 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 21 seconds
----------
SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 1630, signal count 1612
Mutex spin waits 0, rounds 10461, OS waits 205
RW-shared spins 2051, OS waits 1024; RW-excl spins 407, OS waits 380
------------
TRANSACTIONS
------------
Trx id counter 0 8450727
Purge done for trx's n:o < 0 8450719 undo n:o < 0 0
History list length 10
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 8967, OS thread id 140114720237312
MySQL thread id 31142, query id 6206904 localhost root
SHOW ENGINE INNODB STATUS
---TRANSACTION 0 8450588, not started, process no 8967, OS thread id 140114589861632
MySQL thread id 30909, query id 6153062 [my IP] [my username]
---TRANSACTION 0 8450484, not started, process no 8967, OS thread id 140114719172352
MySQL thread id 30899, query id 6152893 [my IP] [my username]
---TRANSACTION 0 8450702, not started, process no 8967, OS thread id 140114586134272
MySQL thread id 28747, query id 6206903 [my IP] [my username]
---TRANSACTION 0 8450726, ACTIVE 34 sec, process no 8967, OS thread id 140114484233984 inserting
mysql tables in use 1, locked 1
LOCK WAIT 3 lock struct(s), heap size 1216, 1 row lock(s)
MySQL thread id 31147, query id 6206832 [my IP] [my username] update
INSERT INTO [My table] [the rest of the statement....]
------- TRX HAS BEEN WAITING 34 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 45066 n bits 432 index `PRIMARY` of table `[My DB]`.`[some table]` trx id 0 8450726 lock mode S locks rec but not gap waiting
Record lock, heap no 359 PHYSICAL RECORD: n_fields 6; compact format; info bits 0
 0: len 8; hex 000000000000bdca; asc         ;; 1: len 6; hex 00000080f2a0; asc       ;; 2: len 7; hex 80000000390110; asc     9  ;; 3: len 6; hex 73797374656d; asc system;; 4: len 1; hex 02; asc  ;; 5: len 4; hex 53c4b11b; asc S   ;;

------------------
---TRANSACTION 0 8450725, ACTIVE 35 sec, process no 8967, OS thread id 140114588530432
MySQL thread id 31146, query id 6206822 [my IP] [my username]
Trx read view will not see trx with id >= 0 8450726, sees < 0 8450720
---TRANSACTION 0 8450720, ACTIVE 36 sec, process no 8967, OS thread id 140114590127872
393 lock struct(s), heap size 47088, 31495 row lock(s), undo log entries 229
MySQL thread id 31145, query id 6206823 [my IP] [my username]
--------
FILE I/O
--------
I/O thread 0 state: waiting for i/o request (insert buffer thread)
I/O thread 1 state: waiting for i/o request (log thread)
I/O thread 2 state: waiting for i/o request (read thread)
I/O thread 3 state: waiting for i/o request (write thread)
Pending normal aio reads: 0, aio writes: 0,
 ibuf aio reads: 0, log i/o's: 0, sync i/o's: 0
Pending flushes (fsync) log: 0; buffer pool: 0
10744 OS file reads, 25629 OS file writes, 18087 OS fsyncs
0.00 reads/s, 0 avg bytes/read, 0.00 writes/s, 0.00 fsyncs/s
-------------------------------------
INSERT BUFFER AND ADAPTIVE HASH INDEX
-------------------------------------
Ibuf: size 1, free list len 5, seg size 7,
519 inserts, 519 merged recs, 76 merges
Hash table size 17393, node heap has 12 buffer(s)
0.00 hash searches/s, 0.00 non-hash searches/s
---
LOG
---
Log sequence number 5 2505544157
Log flushed up to   5 2505544157
Last checkpoint at  5 2505544157
0 pending log writes, 0 pending chkp writes
15981 log i/o's done, 0.00 log i/o's/second
----------------------
BUFFER POOL AND MEMORY
----------------------
Total memory allocated 21017578; in additional pool allocated 1048576
Dictionary memory allocated 466176
Buffer pool size   512
Free buffers       0
Database pages     498
Modified db pages  0
Pending reads 0
Pending writes: LRU 0, flush list 0, single page 0
Pages read 12504, created 289, written 10838
0.00 reads/s, 0.00 creates/s, 0.00 writes/s
Buffer pool hit rate 1000 / 1000
--------------
ROW OPERATIONS
--------------
0 queries inside InnoDB, 0 queries in queue
2 read views open inside InnoDB
Main thread process no. 8967, id 140114495788800, state: waiting for server activity
Number of rows inserted 38311, updated 16430, deleted 36, read 6456822
0.00 inserts/s, 0.00 updates/s, 0.00 deletes/s, 0.00 reads/s
----------------------------
END OF INNODB MONITOR OUTPUT
============================

mysql> SELECT @@GLOBAL.tx_isolation, @@tx_isolation, @@session.tx_isolation;
+-----------------------+-----------------+------------------------+
| @@GLOBAL.tx_isolation | @@tx_isolation  | @@session.tx_isolation |
+-----------------------+-----------------+------------------------+
| REPEATABLE-READ       | REPEATABLE-READ | REPEATABLE-READ        |
+-----------------------+-----------------+------------------------+
1 row in set (0.00 sec)

This problem doesn't exist if I establish my connection with auto commit set to true (I am using Apache Common DBCP 1.4).

A: I found the issue.
The issue is that MySQL expects all queries within the same transaction to be done in the same TCP connection while each SQL execution through QueryRunner can potentially initiate a new TCP connection to the DB (though it can be controlled in couple ways).


text:
Q: Extracting a ContainerVisual from a UIElement ElementCompositionPreview class allows for extracting the backing Visual from a UIElement via GetElementVisual API. Is there a way to extract a ContainerVisual from a UIElement? Since a Visual is just the base class for all types of Visuals, is there a way to determine what kind of Visual this extracted Visual is? I tried resorting to dynamic_cast but that yields a nullptr on trying to cast it to a ContainerVisual. Does that indicate that this is just a plain Visual class instance that can't be used as anything else and restricts usage to only the Visual interface?
Edit:
To add more context to how I'm going about this. Here's what I have in my code
FrameworkElement^ elem = new UserControl();
auto visual = ElementCompositionPreview::GetElementVisual(elem);
if(auto container = dynamic_cast<ContainerVisual^>(visual)) {
  //Use ContainerVisual APIs and use it's children property to insert visuals in the visual tree
}

A: You could create a ContainerVisual from a Compositor instance which is extracted from a UIElement.
Please check the following code:
FrameworkElement^ elem =ref new UserControl();
auto _compositor = ElementCompositionPreview::GetElementVisual(elem)->Compositor;
auto containerVisual= _compositor->CreateContainerVisual();
if (containerVisual)
{
    //Test if the containerVisual is a null value
    containerVisual->Comment = "1122";
}
auto str = containerVisual->Comment;


text:
Q: Trying to extend one class to another Currently I have a working class called Humane32 and I want to extend my class Fysikere42 with this one, I have 2 arguments in Human, age and name, and one additional on the Fysikere42. The Humane32 class is currently looking like this:
import java.util.List;
import java.util.Arrays;
import java.util.Random;
import java.util.ArrayList;

public class Humane32{
    public static class Human{
        private static final List<String> names = Arrays.asList("Rutger","Oscar","Aram","Noak","Hilda","Dahl");
        public Random rand=new Random();
        public String name;
        public int age;

        public Human(int age, String name){
            this.age=age;
            this.name=name;

        }
        public Human(){
            this.age=rand.nextInt(101);
            this.name=names.get(rand.nextInt(names.size()));
        }

        public String getName(){
            return this.name;
        }
        public int getAge(){
            return this.age;
        }
        public String toString(){
            return "åldern är:"+this.age+"\n"+"namnet är:"+this.name;
        }

    }
    public static void main(String[] args){
        ArrayList<Human> humaner=new ArrayList<Human>();
        int q;
        for (q=0;q<=15;q++){
            humaner.add(new Human());
            System.out.println(humaner.get(q).toString());
        }

    }
}

And my new class is currently looking like this:
import java.util.List;
import java.util.Arrays;
import java.util.Random;
import java.util.ArrayList;

public class Fysikere42 extends Humane32{
    public static class Fysikerere42{
        public int year;

        public Fysikere42(int age, String name,int year){
            this.age=age;
            this.name=name;
            this.year=year;

        }
        public int getYear(){
            return this.year;
        }
    }
    public static void main(String[] args){
        System.out.println("hej");
    }
}

But I'm getting the error message, "invalid method declaration, return type required". Where did it go wrong?

A: You're defining a constructor for Fysikere42 inside the static inner class Fysikerere42 since the names do not match it does not read it as a constructor for Fysikerere42 and hence it is asking for a return type for this method. (Since constructor methods don't have return types but it doesnt think this is a constructor).
Change the name of the constructor to Fysikerere42:
public class Fysikere42 extends Humane32{
    public static class Fysikerere42{
        public int year;

        public Fysikerere42(int age, String name,int year){
            this.age=age;
            this.name=name;
            this.year=year;

        }


text:
Q: Flutter - Scrollable List of Widgets I have a screen that displays a list of widgets, something like this:
Column(
    children: listW,
),

The listW object is of type List<Widget>. The first index contains a ListTitle and all others are of type Card. The number of cards are added dynamically. Now the problem is that when the list has lets say 10 Card objects, it is hidden below the screen. I need some sort of a ScrollableView to contain my list. How can I do that since SingleChildScrollableView can bear only one widget. How can I deal with this issue?

A: Try changing you code to this
ListView(children: listW,)

A: You can use a ListView() for this.
ListView(
    children: <Widget>[
         //Your widgets
    ]
)

Keep in mind, that a list view renders all the items currently in the list, which means huge lists will cause performance issues. You can get around this using a ListView.builder, since this creates items as they are scrolled on the screen.
class FruitList extends StatelessWidget{
  final List<String> fruits = [ "Apple", "Banana", "Pear", "Orange", "Kiwi" ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
          padding: EdgeInsets.all(5),
          child: ListView.builder(
            itemBuilder: _buildFruitItem,
            itemCount: fruits.length,
          )
        )
    );
  }

  Widget _buildFruitItem( BuildContext context, int index ){
    return Card(
      child: Text( fruits[index] ),
    );
  }

}

You can checkout more documentation on this here: https://flutter.io/docs/cookbook/lists/long-lists


text:
Q: How to handle an empty result set in tempojs? The documentation is not quite clear on this, or I may not be understanding how to implement this in the HTML, but how do you handle a template in tempojs that has an empty list/array of items coming from JSON output? Is there a template directive that can be used to display something when the data list is empty (i.e. like the else empty in normal conditional code)?
Here's an example:
Javascript:
$(function() {
    /*var data = [
        {id:'1',name:'Test One',coordinates:'12.0012,-122.92'}
    ];*/
    var data = [];
    Tempo.prepare('userLocs').render(data);
});

HTML:
...

        {{name}}
        {{coordinates}}
        Delete

        Javascript is not available.

...


text:
Q: Logic statements in R: Are values in column X found in column Y? I am still a beginner programmer so please forgive my ignorance if this questions is extremely simplistic.
Let's suppose I have a dataframe defined by the following:
> data=as.data.frame(c('white','brown','black','blue','red','yellow'))
> colnames(data)='Colors'
> data
  Colors
1  white
2  brown
3  black
4   blue
5    red
6 yellow

Assume now that I need to know if the values of this dataframe are contained within another dataframe 'valid' of different length, where 'valid' is defined by the following:
> valid=as.data.frame(c('red','blue','white'))
> colnames(valid)='valid colors'
> valid
valid colors
1          red
2         blue
3        white

Now I would like to create a new column in 'data' that flags whether or not the color in the first column of data is contained within the 'valid' dataset to get the following:
> data
  Colors valid
1  white   Yes
2  brown    No
3  black    No
4   blue   Yes
5    red   Yes
6 yellow    No

The dataset I am working with is extremely large so doing this manually or over a loop is not a good option. I am sure there is an easy way of doing this but after hours of search, I am turning to you.
Thanks.

A: Try using %in%:
data$valid <- data$Colors %in% valid$"valid colors"

> data
  Colors valid
1  white  TRUE
2  brown FALSE
3  black FALSE
4   blue  TRUE
5    red  TRUE
6 yellow FALSE


text:
Q: How can I create an .exe file of a code (using python) that need a variable file path to work? I'm new in IT field and I need some advice for how can I solve this problem, using python. It's a volunteer work for a Non-Profit Organization.
My script is done, but in the code there is reference to specific file path that only will work in my PC. I need to convert the script to .exe (pyinstaller), but it won't work in other PCs, because the path will create an error.
My code use data from a xlsx and it also use an image .png, and both files are referenced in the code with the path that they are saved in my PC. How can I convert to .exe in a way that the program still working in other PCs? I need a way to pack both files and the script in the .exe (in this case, what do I put to replace the path in my code for a reference to this "packed file"?) or insert a variable path instead the specific path related only with mt PC. What are the ways to solve that?
Edit:
In resume, I need that this line of code work in other PCs after I convert the .py to an .exe file, using for that the pyinstaller:
import pandas as pd
dados = pd.read_excel(r"/Users/lucas/Documents/UDV/NE/Dados.xlsx")

As the path is only related with my PC, if I try to convert to exe and open in other machine, it will result in a error message.
Thanks!
Obs: The .exe will be used for normal users, so I expected that in the final the person only will click on the .exe and it will do the job without hard commands by the user.


text:
Q: orientdb query linklist too slowly I have tow class: NOrder and NPassenger, relationship 1 : n, so NOrder has a filed named "passengers",whose type is linklist.
I want to select NOrder by NPassenger's field "passengerName",
I used sql
select from NOrder where 'John' in passengers.name

the NOrder ducuments count is 3 millon, this sql works too slowly, how can I do it?
thanks a lot

A: You can insert an index on the field name of the class NPassenger.
You can use this query
select expand(distinct(rid)) from (FIND REFERENCES (select from NPassenger where name = "John"))

Let me know.


text:
Q: Error installing a python module I am trying to install a python module with the standard python setup.py install but I get the following error. I am fairly new to python but I have been able to install other modules in this way in the past. I am under the impression this module setuptools is not something I am supposed to have gotten separate from my python installation. Do I need to be in a specific directory or something?
Error:
Traceback (most recent call last):
  File "setup.py", line 3 in <module>
    from setuptools import setup, find_packages
ImportError: No module named setuptools

A: Surprisingly, setuptools does NOT come pre-packaged with Python, despite how often and casually everyone refers to it. I also had this problem when learning Python.
Setuptools is available on the Python Package Index.

A: Apparently, that package requires you to have setuptools to install it. Setuptools is a module that provides easy installation of Python packages. You can get it on pypi, here.


text:
Q: iPhone 4S using 3G to download songs from iCloud after iOS 5.1 update I have a limited 3G plan on my iPhone 4S and I also have iTunes Match service.
In order to keep the phone from downloading songs from iCloud, while under 3G connection, I had set 'Settings>Store>Use Cellular Data' to OFF. This seemed to work just fine until I downloaded the iOS 5.1 update.
A couple of days ago I was surprised to find that while listening to shuffled music, I had ran out of credit because the Music App had been fetching songs from iCloud using 3G, even though the Setting was still OFF.
I've been forced to turn off my 3G every time I want to listen to music on the go, which is really annoying.
Is this a known bug? Is anyone else experiencing the same problem? Is there a fix?
Thanks!

A: You need to turn off "Use Cellular Data" in the "Music" section in Settings. Then, when you go to play a song from iTunes Match when you're on 3G, it'll give you a message saying you need to be on Wi-Fi.


text:
Q: How to set dynamic column in linq query I have following code,
public List<MemberDto> GetMembers(out int rowCount,int pageIndex,int pageSize,  string seachBy = "", string searchTerm = "", string sortBy = "", string sortDiection = "")
{
    var members = (from m in context.Members
                   where (string.IsNullOrEmpty(searchTerm) || m.MemberNumber.Equals(searchTerm))
                         || (string.IsNullOrEmpty(searchTerm) || m.LastName.Equals(searchTerm))
                   select m).AsEnumerable();

    if (!string.IsNullOrEmpty(sortBy))
    {
        PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(EFModel.ClientData.Member)).Find(sortBy, true);
        members = (sortDiection.ToLower() == "descnding") ? members.OrderByDescending(x => prop.GetValue(x)).ToList() : members.OrderBy(x => prop.GetValue(x)).ToList();
    }

    rowCount =  (!string.IsNullOrEmpty(searchTerm)) ? members.Count() : rowCount = context.Members.Count() ;

    members = members.Skip(pageIndex).Take(pageSize).ToList();

    List<MemberDto> memberDtos = new List<MemberDto>();
    mapper.Map(members, memberDtos);
    return memberDtos;
}

*

*In the above method string seachColumn value can be memberno or lastname or sometime empty. when seachColumn value is memberno. I only need to search searchTerm value in MemberNumber column.

*when seachColumn value is lastname. I only need to search searchTerm value in LastName column.

*sometimes searchTerm can be empty. when it happen I need all the records without considering any search terms.
Above query is working bit. the problem is that when there is a value for searchTerm, That result is given regardless of the column. How can i do this.

A: public List<MemberDto> GetMembers(out int rowCount,int pageIndex,int pageSize,  string seachColumn = "", string searchTerm = "", string sortBy = "", string sortDiection = "")
{
   var query = context.Members;
  if(string.IsNullOrWhitespace(searchTerm)
  {
        return query.ToList();
  }

//if you want to check strings equality in ignore-case mode, you should change your db collation using the link below.

return query
        .Where(m => m.MemberNumber.Equals(searchTerm) ||  m.LastName.Equals(searchTerm))
        .ToList();
}

String equality check in ef using db collation


text:
Q: SQL - # used while creating a temp table I'm just wondering why # was used while creating this temporary table.
create table **#tmp** (
  Things to wonder about
)

The query works perfectly fine with/without it.

A: vc74 answered the question
In SQL server a single # needs to prefix the name of local temporary tables. If you omit it, you're actually creating a non temporary table. – vc 74


text:
Q: Regex to replace the character after pattern match For my Java app, i have a string that looks like:
value1: *sample", test
test: "test"
newtest: *newtest"

I need to match the character " when the string starts with *.
Tried the regex:
"(?!.*")
But this selected all the " in the input.
Was planning to replaceAll(regex, "") to remove the character.
Desired Output:
value1: *sample, test
test: "test"
newtest: *newtest

How do i get this output?

A: You can use
.replaceAll("(\\*\\w+)\"", "$1")

Details:

*

*(\*\w+) - Group 1 ($1 refers to the text captured in this group)

*" - a " char (just matched, not captured, so eventually removed).


text:
Q: An array for multiple LHS assignment cannot contain LEX_TS_STRING error New to programing in matlab. I am currently trying to make a MATLAB program that will find the critical values of a multi-variable function and tell me whether each are a minimum, maximum, or saddle point. Unfortunately I always get the error : An array for multiple LHS assignment cannot contain LEX_TS_STRING
Any help will be very appreciated.
here's the code:
function [c,d] = critcalpoints(f)

syms x y
f(x,y)=x^3-3*x^2+5*x*y-7*y^2;
gradf = jacobian(f(x,y));
hessmatf = jacobian(gradf,[x,y]);
[xcr,ycr]=solve(gradf(1),gradf(2));
H1=subs(hessmatf,[x,y],[xcr(1),ycr(1)]);
H2=subs(hessmatf,[x,y],[xcr(2),ycr(2)]);
eig(H1);
eig(H2);
c = double(eig(H1));
d = double(eig(H2));
if (c(1) > 0 && d(1) > 0) || (c(2) > 0 && d(2) > 0)
print([xcr,ycr],' is a minimum')
elseif (c(1) < 0 && d(1) < 0) || (c(2) < 0 && d(2) < 0)
print( [xcr, ycr], ' is a maximum')
elseif (c(1) < 0 && d(1) > 0) || (c(1) > 0 && d(1) < 0)
print( [xcr, ycr], ' is a saddle point')
elseif (c(2) < 0 && d(2) > 0) || (c(2) > 0 && d(2) < 0)
print( [xcr, ycr], ' is a saddle point')
elseif (c(1)==0 || d(1)==0)
print( [xcr, ycr], ' is degenerate')
elseif (c(2)==0 || d(2)==0)
print( [xcr, ycr], ' is degenerate')
end

A: Cannot reproduce your error.  The code can work but you need to change print to something else as print doesn't do what you think it does.  The print function prints a figure that is open to file.  Change it so that you display xcr and ycr first then display the right condition to satisfy after. Use disp instead:
syms x y
f(x,y)=x^3-3*x^2+5*x*y-7*y^2;
gradf = jacobian(f(x,y));
hessmatf = jacobian(gradf,[x,y]);
[xcr,ycr]=solve(gradf(1),gradf(2));
H1=subs(hessmatf,[x,y],[xcr(1),ycr(1)]);
H2=subs(hessmatf,[x,y],[xcr(2),ycr(2)]);
eig(H1);
eig(H2);
c = double(eig(H1));
d = double(eig(H2));
disp([xcr, ycr]); % Display the solutions first

if (c(1) > 0 && d(1) > 0) || (c(2) > 0 && d(2) > 0)
disp('is a minimum')
elseif (c(1) < 0 && d(1) < 0) || (c(2) < 0 && d(2) < 0)
disp('is a maximum')
elseif (c(1) < 0 && d(1) > 0) || (c(1) > 0 && d(1) < 0)
disp('is a saddle point')
elseif (c(2) < 0 && d(2) > 0) || (c(2) > 0 && d(2) < 0)
disp('is a saddle point')
elseif (c(1)==0 || d(1)==0)
disp('is degenerate')
elseif (c(2)==0 || d(2)==0)
disp('is degenerate')
end

I get:
[     0,       0]
[ 59/42, 295/588]

is a maximum


text:
Q: Not only.... but also Is this sentence grammatically correct?

He doesn't only like football but also likes tennis.

and if it's wrong, why so?
Specifically, is there any problem with omitting the subject in the second clause?
Also, is there any problem with the verb form likes?

A: I would rephrase the sentence as

He likes not only football but also tennis

in the style of the first of the examples here. This rephrasing avoids repeating the verb after but also if it is the same verb that came before the not only (compare with the second example in the link, where there are two different verbs).
Note that here the not only... but also... construction is used to amplify the object of the sentence, which essentially is of the form "He likes THIS". That's why it is not necessary to repeat neither the verb "like" nor the subject "he" inside the object.

A: Analyzing : "He doesn't only like football but also likes tennis."
Normal usage is "not only X but also Y", but here "not" is getting merged with "does" , the usage looks odd.
More-over, "only like" refers to "like" , not "football", so using "tennis" later looks odd.
"He not only likes football but also excels in it."
Here, we have the normal usage of "not only X but also Y" & "likes" goes along with "excels", both in terms of football.
When you want to state that he likes football & tennis, then try this:
"He likes not only football but also tennis."
Here, "football" goes along with "tennis".
Reference :
The Cambridge Grammar Of The English Language :
https://archive.org/stream/TheCambridgeGrammarOfTheEnglishLanguage/The%20Cambridge%20grammar%20of%20the%20English%20language#page/n1327/mode/2up
Here, the common format of "not only X but also Y" is stated, with some possible variations.

A: Yes, there is something wrong with this sentence, and it does have to do with omitting the subject in the second clause.  "But" is a coordinate conjunction which (like "and" and "or") connects phrases of the same type.  It can connect two sentences, two verb phrases, or two of various other things.  In your example, since the subject of the second clause is omitted, "but" must be connecting two verb phrases.
Now, coordinate constructions have a peculiar property, discovered and investigated by John Ross, which he called the Coordinate Structure Constraint (CSC).  As McCawley phrases it, it requires both parts of a coordinate structure to be treated equally by any grammatical process.  I think that is what has gone wrong in your example: the first verb phrase of the two that are connected with "but" is not treated the same way as the second one.
The "s" at the end of "likes" expresses the present tense of the verb, of course, and although in the second verb phrase, it appears at the end of the verb where it belongs, in the first verb phrase it is missing.  The "s" present ending in the first verb phrase had to be moved to the left, because of the "not", and the auxiliary verb "do" was added to carry the tense.
The CSC does not allow this, because the "s" was moved away from the verb of the first verb phrase, but the same thing did not happen to the corresponding verb of the second verb phrase.
This was a difficult example, and I hope I got it right.

A:
When using a correlative conjunction, both clauses have to be parallel. That means you have to use them before two nouns, two adjectives, two verbs etc.

When we look at the sentence

He doesn't only like football but also likes tennis.

we see that the verb is 'like' and the two nouns are 'Football' and 'Tennis'. If we go by the above mentioned rule, it implies that when 'not only' is followed by the verb 'like', 'but also' will be followed immediately by another 'verb' describing the same subject 'football' and not another subject, as in this case, tennis. With two different nouns and the common verb 'like', 'not only...but also' is to be used immediately before the nouns. So, the correct sentence would be:

He likes not only football but also tennis.

Reference 1
Reference 2

A: You asked if there was something grammatically wrong with your phrasing - the answer is no. Some people are suggesting you may choose the more traditional:
"He likes not only football but also tennis",
but it's boring, and the word "not only" sound disgusting to my ears. Yours, while non-traditional, actually pops out more, and reads better. You repeat the word "likes" which actually sounds better because it emphasizes how much he likes both sports.
I say, keep it the way it is.
PS- you asked about the verb form "likes". To me, it's a sexy five letter word that is very under used.

A: To stick to the proposed form, I would also rephrase it like this : "He doesn't only like football but also tennis."
Or : "He doesn't only like football but he also likes tennis".
Beside grammar concepts, the reason is because if you skip the middle he, in colloquial speech, then there is no need to keep likes which would be a 2nd verb for the same subject, first word of the sentence, when you want to be direct.


text:
Q: Analytic integral of diverging function Is it possible to obtain the result of the following integral analytically?
$$\int_0^x \cfrac{{\rm d}u}{1-u^n}$$
I've tried using quadrature, but the function goes to infinity at $u=1$, hence the integral.
EDIT
I suppose an analytic solution is not possible, so is there any way to calculate it numerically for $u>1$? I managed to write:
from math import *
from scipy.integrate import quad
f = lambda u,n: 1./(1.-(u**n))
eps = 0.0001; n=2.6;
# from 0 to 1.005
print quad(lambda x:f(x,n),0.0,1.-eps)[0]+ quad(lambda x:f(x,n) ,1.+eps,1.005)[0]

I implemented the Cauchy principle value method in python 2.7 using scipy. Is there are particular reason for it not to work. For (u=1.005, n=2.6, x=u) the result should have been 2.022 (according to this (Open-Channel Flow by Subhash C. Jain, p78)). Instead, it is 2.48. Am I missing something? Can we say that $$\int_0^{x+\epsilon}\frac{\mathrm{d}u}{1-u^n} = \int_0^{x-\epsilon}\frac{\mathrm{d}u}{1-u^n}$$
Here are the numerical solutions that are supposedly correct:

Solution:
Here is a snippet in python2.7 using the hyp2f1() function from the mpmath package
def F(u,n):
    if u < 1:
        return u*mpmath.hyp2f1(1/n,1,1/n+1,u**n)
    elif u >1:
        return (u**(1-n))/(n-1)* \
            mpmath.hyp2f1(1-1/n, 1 , 2-1/n ,u**(-1*n)) #+ pi/n/tan(pi/n)
    else:
        return 0.

A: The integral can be given a value for $x\gt1$ using the Cauchy Principal Value. That is, for $x\gt1$,
$$
\mathrm{PV}\int_0^x\frac{\mathrm{d}u}{1-u^n}
=\lim_{\epsilon\to0}\left(\int_0^{1-\epsilon}\frac{\mathrm{d}u}{1-u^n}
+\int_{1+\epsilon}^x\frac{\mathrm{d}u}{1-u^n}\right)
$$

Cauchy Principal Value over $\mathbf{\mathbb{R}^+}$
Consider the contour
$\hspace{3cm}$
Using this answer, we get
$$
\int_0^\infty\frac{\mathrm{d}u}{1+u^n}=\frac\pi n\csc\left(\frac\pi n\right)
$$
Thus, the integral on the blue line is
$$
-e^{i\pi/n}\frac\pi n\csc\left(\frac\pi n\right)=-\frac\pi n\cot\left(\frac\pi n\right)-i\frac\pi n
$$
The residue of $\frac1{1-u^n}$ at $u=1$ is $-\frac1n$. Therefore, the integral along the clockwise red semicircle is
$$
i\frac\pi n
$$
Since there are no singularities inside the contour, the total integral over the contour is $0$. Thus, the integral over the perforated green line must be
$$
\mathrm{PV}\int_0^\infty\frac{\mathrm{d}u}{1-u^n}=\frac\pi n\cot\left(\frac\pi n\right)
$$

Self-Contained Argument
Using the contour above and separating real and imaginary parts, we get that
$$
\begin{align}
\color{#00A000}{\mathrm{PV}\int_0^\infty\frac{\mathrm{d}u}{1-u^n}}+\color{#C00000}{i\frac\pi n}
&=\color{#0000FF}{e^{i\pi/n}\int_0^\infty\frac{\mathrm{d}u}{1+u^n}}\\
&=\left(\cos\left(\frac\pi n\right)+i\sin\left(\frac\pi n\right)\right)\int_0^\infty\frac{\mathrm{d}u}{1+u^n}
\end{align}
$$
Looking at the imaginary part, we get
$$
\int_0^\infty\frac{\mathrm{d}u}{1+u^n}=\frac\pi n\csc\left(\frac\pi n\right)
$$
Then looking at the real part, we get
$$
\mathrm{PV}\int_0^\infty\frac{\mathrm{d}u}{1-u^n}=\frac\pi n\cot\left(\frac\pi n\right)
$$

A: I can at least give your integral a name.  Suppose $0 \leq x<1$ so that the integral converges.
Letting $u = v^{1/n}$, the integral becomes
$$
\frac{1}{n} \int_0^{x^n} v^{\frac{1}{n}-1}(1-v)^{-1}\,dv = \frac{1}{n}B\left(x^n;\,\frac{1}{n},\,0\right),
$$
where $B(z;p,q)$ is the incomplete beta function.  According to MathWorld, we can also write this as a hypergeometric function:
$$
x\cdot{}_2F_1\left(\frac{1}{n},\,1;\,\frac{1}{n}+1;\,x^n\right).
$$

It appears (based on numerical evidence) that the principal value of the integrand is given by
$$
\text{PV} \int_0^x \frac{du}{1-u^n} = \operatorname{Re}\left[x\cdot{}_2F_1\left(\frac{1}{n},\,1;\,\frac{1}{n}+1;\,x^n\right)\right].
$$

This is in regards to the table posted in the question.  They are not using the principal value of the integral; they are using a related quantity which differs from the principal value by a function depending only on $n$.
Let $0 < \epsilon < \min\{1,x-1\}$ and split the integral up into two parts,
$$
\begin{align*}
&\int_0^{1-\epsilon} \frac{du}{1-u^n} + \int_{1+\epsilon}^{x} \frac{du}{1-u^n} \\
&\qquad = (1-\epsilon)\cdot{}_2F_1\left(\frac{1}{n},\,1;\,\frac{1}{n}+1;\,(1-\epsilon)^n\right) + \int_{1+\epsilon}^{x} \frac{du}{1-u^n}.
\end{align*}
$$
Making the substitution $u=1/v$ in the remaining integral gives
$$
\begin{align*}
\int_{1+\epsilon}^{x} \frac{du}{1-u^n} &= -\int_{1/x}^{1/(1+\epsilon)}\frac{v^{n-2}}{1-v^n}\,dv \\
&= \int_0^{1/x}\frac{v^{n-2}}{1-v^n}\,dv - \int_0^{1/(1+\epsilon)}\frac{v^{n-2}}{1-v^n}\,dv.
\end{align*}
$$
Both of these integrals are treated the same way.  We proceed as before, letting $v=w^{1/n}$.  This gives
$$
\begin{align*}
\int_0^a \frac{v^{n-2}}{1-v^n}\,dv &= \frac{1}{n} \int_0^{a^n} w^{\frac{n-1}{n}-1} (1-w)^{-1}\,dw \\
&= \frac{a^{n-1}}{n-1}\, {}_2F_1\left(1-\frac{1}{n},\,1;\,2-\frac{1}{n};\,a^n\right),
\end{align*}
$$
so that
$$
\begin{align*}
\int_{1+\epsilon}^{x} \frac{du}{1-u^n} &= \frac{x^{1-n}}{n-1}\, {}_2F_1\left(1-\frac{1}{n},\,1;\,2-\frac{1}{n};\,x^{-n}\right) \\
&\qquad - \frac{(1+\epsilon)^{1-n}}{n-1}\, {}_2F_1\left(1-\frac{1}{n},\,1;\,2-\frac{1}{n};\,(1+\epsilon)^{-n}\right).
\end{align*}
$$
Thus
$$
\text{PV} \int_0^x \frac{du}{1-u^n} = \frac{x^{1-n}}{n-1}\, {}_2F_1\left(1-\frac{1}{n},\,1;\,2-\frac{1}{n};\,x^{-n}\right) + f(n),
\tag{1}
$$
where
$$
\begin{align*}
f(n) &= \lim_{\epsilon \to 0} \left\{(1-\epsilon)\cdot{}_2F_1\left(\frac{1}{n},\,1;\,\frac{1}{n}+1;\,(1-\epsilon)^n\right) \right. \\
&\qquad\qquad\qquad \left. - \frac{(1+\epsilon)^{1-n}}{n-1}\, {}_2F_1\left(1-\frac{1}{n},\,1;\,2-\frac{1}{n};\,(1+\epsilon)^{-n}\right)\right\} \\
&= \frac{\pi}{n} \cot\left(\frac{\pi}{n}\right)
\tag{2}
\end{align*}
$$
if $n>1$.  The last equality $(2)$ follows directly from robjohn's work by letting $x \to \infty$ in $(1)$.  So, in summary,

For $x<1$,
  $$
\int_0^x \frac{du}{1-u^n} = x\cdot{}_2F_1\left(\frac{1}{n},\,1;\,\frac{1}{n}+1;\,x^n\right),
$$
  and for $x>1$ and $n>1$,
  $$
\text{PV} \int_0^x \frac{du}{1-u^n} = \frac{x^{1-n}}{n-1}\, {}_2F_1\left(1-\frac{1}{n},\,1;\,2-\frac{1}{n};\,x^{-n}\right) + \frac{\pi}{n} \cot\left(\frac{\pi}{n}\right).
$$

In computing their table, they seem to have assumed that $f(n) = 0$.  Indeed, their table is exactly equal to the one generated by
$$
g(n,x) = \text{PV} \int_0^x \frac{du}{1-u^n} - \frac{\pi}{n} \cot\left(\frac{\pi}{n}\right).
$$
For example,
$$
\begin{align*}
g(2.6,1.01) &\approx 1.75625, \\
g(2.6,1.02) &\approx 1.4927, \\
g(2.6,1.03) &\approx 1.33979, \\
g(2.6,1.04) &\approx 1.23215, \\
g(2.6,1.05) &\approx 1.14932.
\end{align*}
$$


text:
Q: How does Python assign and retrieve a DLL's global variable? DLL written in C
extern int32_T myinput;
extern int32_T myoutput;

extern void initialize(void);
extern void run(void);
extern void terminate(void);

void run(void)
{
    myoutput = myinput * 2;
}

Python script
from ctypes import*
mydll = cdll.LoadLibrary("C:\\myDLL.dll")
mydll.myinput = 10    # Question1
mydll.initialize()
mydll.run()
print(mydll.myoutput) # Question2
mydll.terminate()

My expectation
20

The actual output
<_FuncPtr object at 0x00000000023646C8>

My Question

*

*How to assign global variable in the DLL?

*How to retrieve global variable in the DLL?

In short, could you modify my script to make the output be 20?


text:
Q: Nested attribute term Query I have a documents something like bellow
{
        "_index": "lines",
        "_type": "lineitems",
        "_id": "4002_11",
        "_score": 2.6288738,
        "_source": {
          "data": {
            "type": "Shirt"
          }
        }
      }
I want to get a count based on type attribute value. Any suggestion on this?
I tried term query but no lick with that.

A: You should use the terms aggregation, this will return the number of documents aggregated for each "type" field values.
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html


text:
Q: Grouped data back to list using lambda c# When i have grouped my data, how do i get it back to my _data variable? I cant seem to declare the query variable outside the If statement, i guess because its anonymous?
How do i achieve this?
Thanks!
public IActionResult Get(string area, string hobby)
    {
        var _data = _myContext.getData();

        _data = _data.Where(x => x.hobby == hobby).ToList();

        if (area == "All")
        {
            var query = _data
            .GroupBy(a => new
            {
                a.area
            })
            .Select(b => new
            {
                myDate = b.First().myDate,
                totalAmount = b.Sum(c => c.totalAmount)
            });
        }

        return Ok(_data);
    }

A: You cannot assign the grouped result to _data as you are using a anonymous type. If you want to just return the result to caller you can directly return within the if statement
 if (area == "All")
        {
            var query = _data
            .GroupBy(a => new
            {
                a.area
            })
            .Select(b => new
            {
                myDate = b.First().myDate,
                totalAmount = b.Sum(c => c.totalAmount)
            });

          return Ok(query);
        }


text:
Q: Avoiding trivial all-zero prediction with multi-label regression I have dataset with 64 features that I'm using to model 6 labels bounded on the interval [0,1]. These labels are highly related and it therefore seems reasonable to model them all at once rather than individually.
To model these labels I use a weight matrix with a parameter for each feature + label combination and a bias for each label (i.e. 1 neural network layer). To bound the regression I use a sigmoid activation for each label. I optimize using a variant of SGD with a MSE loss function.
I have 200 observations in my training set, 50 in my validation set and 1000 in my test set. I'm unable to change the number of observations in any set. Regularization (dropout) is applied to deal with the low number of observations. I do not care about inference, only prediction performance.
My issue is that for many observations 3-4 of the labels are 0.0 and that in general, the labels are close to zero. The labels each have a mean of ~0.15. This causes my model to favor a solution, where it simply predicts close to 0.0 for all labels for all observations. The final evaluation of performance is the Pearson correlation between the predictions and the true labels, which makes the all-zero solution worthless.
What are some ways in which I can force my model to avoid the all-zero solution? Perhaps another loss function?


text:
Q: How can I validate the database schema against my JPA in Wildfly 11/Hibernate I'm using JPA persistence in a Java web project, which runs on Wildfly 11. It's using Hibernate 5.1. Sometimes the database schema changes and I try to be very careful to change the production databases in the same way as I change my Java code for the entities.
However, I need to be able to run update scripts before the application boots up. After those ran, the database should be in the right state.
So I added a bean with @Singleton and @Startup. That bean takes care of updating the schema nicely. It detects the current database version and selects the right update scripts.
Since I'm modifying the Java code of the entities by hand and doing the update scripts by hand, I'd like to have a way to validate my work. I know I can activate hibernate.hbm2ddl.auto and set it to validate. But then my update scripts wouldn't work, since in that case, validation takes place before the schema is updated. So ideally I'd like to run validation manually inside that class, after all updates are through.
I tried to use org.hibernate.tool.hbm2ddl.SchemaValidator, but I need an instance of org.hibernate.boot.Metadata and I failed to get it out of my EntityManager. So if someone could tell me how to get that, that would possibly solve this problem. I was able to get a org.hibernate.service.ServiceRegistry.
I also tried to add another persistence unit, one without validation and one with hibernate.hbm2ddl.auto set to validate, but it turned out, that this setting is global and either all units will have validation enabled or none. Maybe I was doing it wrong, but I see it as an undesirable solution anyway. But still, better than nothing.
Maybe there is also some library I can use to validate the database schema. I had a look at Liquibase, but it seemed to take control of everything and not validate the JPA against the database.
Maybe my whole approach to developing this kind of application is not ideal, but I figured, that I really need control over my database and also over the entities.
Any hints are welcome! Thanks in advance.


text:
Q: pdfkit on rails hangs I have a weird problem after I moved my rails application from shared hosting to VPS on DreamHost.
pdfkit hangs.
Page A is called and it generates a pdf from HTML(Page B).
But when Page A calls Page B, as Page A is not finished, Page B is waiting.
So this is basically circular problem.
This didn't happen before.
How do I solve this problem?


text:
Q: Uploading pdf files to Mysql server I am unable to upload the pdf documents that are created using Photoshop and PDFTK. Other pdf documents are getting uploaded without any problem.
I am getting the following warning:

fread(): supplied argument is not a
  valid stream resource in
Warning: fclose(): supplied argument
  is not a valid stream resource

A: I wouldn't suggest uploading the PDFs to MySQL - you would have to save it as a BLOB, and then read the BLOB. This will bloat your database quickly and cause speed issues.
Instead, upload the PDF to the file system, and save the PATH to the PDF in MySQL. Then you can read that path from MySQL.
However, if you absolutely need to save the file as a BLOB - here is a good tutorial for doing so:
http://bytes.com/topic/php/insights/740327-uploading-files-into-mysql-database-using-php


text:
Q: Wine won't follow Symbolic links I can't get Wine to follow some symbolic links I have in my home folder or in applications. Is there a way to enable this? This is on Wine-1.5.18.
Edit: Just in case it helps, I'm trying to use a symbolic link to share the save data from my Fallout 1, between my netbook and my Desktop via Dropbox.
Edit 2: Apparently, there was a option in the wine config file in the past, but I can't find it in the new registry. Anyone have any idea?

A: Don't move and link the whole ~/.wine directory, but the subdirectories c_drive and dosdevices, then try again. At least that worked for us for one program (heidisql).

A: When symbolic linking to something you wish to run, you need to use the full path instead of path shortcut notation. Wine will not expand the notation and tries to follow as a relative path. i.e. use /home/user instead of ~/.
See this answer for more details: https://ubuntuforums.org/showthread.php?t=2001697

A: I'd establish both directories as drives inside wine using winecfg (do it for this program specifically not globally) Then you can just copy from E: to F: (your letters may be different)


text:
Q: Programmatically scroll a ScrollView to focus on a Button or a view - Android I have an Activity that has a ScrollView of 125 buttons.  The 125 buttons are Levels in my game that slowly get unlocked (think of Candy Crush Saga).  Right now if the user is on the level, let's say, 88 of 125 then the user has to manually scroll all the way down to button 88.
My question is, how would I make it so that when the Activity loads, it automatically scrolls down and centers the ScrollView on a certain button?
Below is my code of how the buttons are created and populated programmatically.
ScrollView scrollView;

@Override
public void onCreate(Bundle savedInstanceState) {

    LinearLayout lay = (LinearLayout)findViewById(R.id.linearlayout);

    for(int i = 0; i < 125; i++) {

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
        params.weight = 1;
        params.gravity = Gravity.CENTER;

        if(i == 0) {
            TextView textview = new TextView(this);
            textview.setLayoutParams(params);
            textview.setTextSize(15);
            textview.setText(c.getResources().getString(R.string.l1to5));

            TextView textview2 = new TextView(this);
            textview2.setLayoutParams(params);
            textview.setTextSize(15);
            textview2.setText(c.getResources().getString(R.string.goal100));

            TextView textview3 = new TextView(this);
            textview3.setLayoutParams(params);
            textview.setTextSize(15);
            textview3.setText(c.getResources().getString(R.string.catRandom));

            if((getResources().getConfiguration().screenLayout &
                Configuration.SCREENLAYOUT_SIZE_MASK) ==
                Configuration.SCREENLAYOUT_SIZE_LARGE) {
                    textview.setTextSize(22);
                    textview2.setTextSize(22);
                    textview3.setTextSize(22);
            } else if((getResources().getConfiguration().screenLayout &
                Configuration.SCREENLAYOUT_SIZE_MASK) ==
                Configuration.SCREENLAYOUT_SIZE_XLARGE) {
                    textview.setTextSize(22);
                    textview2.setTextSize(22);
                    textview3.setTextSize(22);
            }

            lay.addView(textview);
            lay.addView(textview2);
            lay.addView(textview3);

            View ruler = new View(this);
            ruler.setBackgroundColor(0xFFC2BEBF);
            lay.addView(ruler, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
        }

        if(i == 5) {

 //  ....

}

        Button button = new Button(this);
        int _id = getResources().getIdentifier("b" + (i + 1), "id", this.getPackageName());
        button.setTag(_id);
        button.setLayoutParams(params);

        if((getResources().getConfiguration().screenLayout &
            Configuration.SCREENLAYOUT_SIZE_MASK) ==
            Configuration.SCREENLAYOUT_SIZE_LARGE) {
                button.setTextSize(22);
        } else if((getResources().getConfiguration().screenLayout &
            Configuration.SCREENLAYOUT_SIZE_MASK) ==
            Configuration.SCREENLAYOUT_SIZE_XLARGE) {
                button.setTextSize(22);
        }

        button.setText("Level " + (i + 1));
        final int x = i + 1;
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                singleton.setLevelJustPlayed(x);
                // ...
                } else {
                 // ...
                    Intent intent = new Intent(Levels.this, Categories.class);
                    startActivity(intent);
                }
            }
        });

        lay.addView(button);

        if(singleton.getLevel() >= (i + 1)) {
            button.setEnabled(true);
        } else {
            button.setEnabled(false);
        }
    }
// end the onCreate() method

A: try
yourScrollView.scrollTo(0, (int) button.getY());

A: For Kotlin user

your_scrollview.post( { your_scrollview.scrollTo(0, your_view_inside_SV.getY().toInt()) })


text:
Q: Having Issue to Use Received Message From Popup in Current Page In Chrome Extension Using Chrome Extension Manifest 3, I am trying to send and use a message from popup to current active tab/page
in my manifest I have
{

    "manifest_version": 3,
    "name": "My Ext",
    "version": "1",
    "description": "Testing",
    "background": {
        "service_worker": "background.js"
    },
    "permissions": ["storage"],
    "action": {
        "default_popup": "popup.html"
    },
    "icons": {
        "16": "icon.png"
    },
    "content_scripts": [
        {
            "matches": ["http://*/*", "https://*/*"],
            "js": ["content-script.js"]
   }
 ]

}

In my popup.html JS script I have which will trigger when user clicks on .send-message button in popup
  $(document).on("click", ".send-message", function () {
   chrome.tabs.query({
                active: true,
                currentWindow: true
            }, function (tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {
                    code: "Hello Input"
                });
            });
          });

In content-script.js I have
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        console.log(request.code);
        $('#input').val(request.code);
        $('#input').text(request.code);
    }
);

I have added the jQuery on top of my content_scripts to inject the jQuery there too (Not sure this is a correct and smart way to do it!)
I am able to send the request.code message to page as the console.log(request.code); is logging out the message in current page console but the  $('#input').val(request.code);  $('#input').text(request.code); is not working!
Can you please let me know what I am doing wrong here and how I can fix this?


text:
Q: incorrect number of dimensions error when I did the loop with matrices list I got the error message when I tried to pass a list of matrices to a newly defined list.
t<-list()
for(i in 1:N){t[[i]]<-Z[[i]][,2]}

here Z is a list of matrices with different sizes(the number of columns in each matrix is same but the rows of matrix is different. And I attempted to create a new matrices list t and each matrix in t has the second column of corresponding matrix in original list Z. But it always didn't work.
The most strange thing is N is 300 but this loop stopped when N approached to 81 every time and gave the error message. Thank you in advance!


text:
Q: How can I identify the calling platform from a .NET Standard library at runtime? Specifically, what I need to identify is the calling development platform (i.e. .NET Core vs. .NET Framework vs. Other) rather than the operating system information I can get through System.Environment.OperatingSystem.Platform. Is there a way to do this?
(To give more detail on my specific use case, I am referencing a library - log4net - which is configured by passing it an XML resource. Some of its configurable features which I want to use if available are supported under .NET Framework but not under .NET Core, and I want to be able therefore to pass it a different version of the resource depending on which I'm being used by.)

A: Solving from the runtime environment could prove to be uncertain as runtime change. I would force the issue up front before the application runs. As previously stated you could pass in the runtime or configure it.
Another option would be something similar to SL4J provides. Runtime determination dependent upon how you deploy the application.
You could create your own interface for exposing platform information. Then, at deploy time, just add the appropriate assembly to the installation. Load the assembly and call the methods you require.
Alternatively you see how Microsoft handled similar situations here: https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/

A: I had to do this once. There was a method I needed to call that varied across implementations. I just used reflection to try one name after another.
Trying to detect the runtime library is silly. Detect the differences directly. It's less likely to break.


text:
Q: Expression mysql NOW() in Doctrine QueryBuilder How to use the expression mysql NOW() in doctrine querybuilder?

A: Using query builder it would look like this:
$qb
    ->select('B')
    ->from('RandomBundle:Banana', 'B')
    ->where(
        $qb->expr()->gt('B.expiresAt', ':now')
    )
    ->setParameter('now', '\'CURRENT_TIMESTAMP()\'');

Note: extra quotes on parameter set is required to get CURRENT_TIMESTAMP() function working.
Or simply
$qb
    ->select('B')
    ->from('RandomBundle:Banana', 'B')
    ->where(
        $qb->expr()->gt('B.expiresAt', 'CURRENT_TIMESTAMP()')
    );

A: In Doctrine2 you have to use one of the following instead of NOW().
This:
CURRENT_TIMESTAMP()

Or:
...
createQuery(...'WHERE x.date = :now')
->setParameter('now', new \DateTime('now'))
...

If you want only time or only date use one of those:
CURRENT_TIME() and CURRENT_DATE()
Documentation can be found here.


text:
Q: Difference in AspNetCore identity 2.0 and 2.1
*

*What is the difference in AddIdentity and AddDefaultIdentity

ConfigureServices Method in Startup from AspNetCore identity 2.0
 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();
    }

ConfigureServices Method in Startup from AspNetCore identity 2.1
 public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

A: AddDefaultIdentity was introduced in ASP.NET Core 2.1. Calling AddDefaultIdentity is similar to calling the following:

*

*AddIdentity

*AddDefaultUI

*AddDefaultTokenProviders
Refer to https://github.com/aspnet/Docs/issues/8434


text:
Q: setting up cluster on GCP with Cloudera Director I'm following along with the instructions on Cloudera's website to set up a cluster using Cloudera Director.  However, when I get to the step where I'm supposed to "Add an Environment," I'm presented with two issues.   First, the region I selected (us-east1-b) when configuring my Google Compute instance is not available for selection on the Cloudera Director software.  Second, there is no option for me to upload Client ID JSON Keys, as the documentation says we should be able to do.  I've attached a screenshot of what I'm looking at.  Any clues?
My Cloudera director software is reporting itself as version 2.1.1, and the docs I'm looking at are for version 2.1.x.  Am I somehow working with an older version of the software?  Or are the Cloudera docs not in line with the current version?  Can anyone else running Cloudera 2.1.1 confirm that they're seeing something similar or different?

A: There is a field to load the Client ID JSON keys in the "Advanced Options" section under General Information. Click the > to expand the Advanced Options.
You should be able to type in the region you want even if it isn't provided as a value in the drop-down.


text:
Q: Different EOF behavior with read versus ignore I was recently just tripped up by a subtle distinction between the behavior of std::istream::read versus std::istream::ignore.  Basically, read extracts N bytes from the input stream, and stores them in a buffer.  The ignore function extracts N bytes from the input stream, but simply discards them rather than storing them in a buffer.  So, my understanding was that read and ignore are basically the same in every way, except for the fact that read saves the extracted bytes whereas ignore just discards them.
But there is another subtle difference between read and ignore which managed to trip me up.  If you read to the end of a stream, the EOF condition is not triggered.  You have to read past the end of a stream in order for the EOF condition to be triggered.  But with ignore it is different: you only need to read to the end of a stream.
Consider:
#include <sstream>
#include <iostream>
using namespace std;

int main()
{
    {
        std::stringstream ss;
        ss << "abcd";
        char buf[1024];
        ss.read(buf, 4);
        std::cout << "EOF: " << std::boolalpha << ss.eof() << std::endl;
    }

    {
        std::stringstream ss;
        ss << "abcd";
        ss.ignore(4);
        std::cout << "EOF: " << std::boolalpha << ss.eof() << std::endl;
    }
}

On GCC 4.4.5, this prints out:
EOF: false
EOF: true

So, why is the behavior different here?  This subtle difference managed to confuse me enough to wonder why there is a difference.  Is there some compelling reason that EOF is triggered "early" with a call to ignore?

A: eof() should only return true if you have already attempted to read past the end. In neither case should it be true. This may be a bug in your implementation.

A: I'm going to go out on a limb here and answer my own question:  it really looks like this is a bug in GCC.
The standard reads in 27.6.1.3 paragraph 23:

[istream::ignore] behaves as an
  unformatted input function (as
  described in 27.6.1.3, paragraph 1).
  After constructing a sentry object,
  extracts characters and discards them.
  Characters are extracted until any of
  the following occurs:

*

*if n != numeric_limits::max()
  (18.2.1), n characters are extracted

*end-of-file occurs on the input sequence (in which case the function
  calls setstate(eofbit), which may
  throw ios_base::failure(27.4.4.3));

*c == delim for the next available input character c (in which case c is
  extracted). Note: The last condition
  will never occur if delim ==
  traits::eof()

My (somewhat tentative) interpretation is that GCC is wrong here, because of the bold parts above.  Ignore should behave as an unformatted input function, (like read()), which means that end-of-file should only occur on the input sequence if there is an attempt to extract additional bytes after the last byte in the stream has been extracted.
I'll submit a bug report if I find that enough people agree with this answer.

A: The consensus seemed to be that this was a legitimate bug in gcc.  Since I saw no indication a bug report had been filed, I'm doing so now.  The report can be viewed at:
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51651


text:
Q: SQLite ef edmx designer in Visual Studio 2013 update 4 for database first targetting .net framework 4 I have been trying to get the SQLite install package to work with my setup.I need to target the .Net Framework 4 but it seems like to get design support for Studio 2013 I had to install the SQLite 4.5.1 package.
I spent much time just getting the edmx wizard to display the SQLite connection and it involved a few hacks with the app.config just to get it working in a 4.5.1 targeted project.
I have a edmx model built now and I want to know if I can use this model created in the 4.5.1 class library in a project targeting .net 4. I just copied to entire edmx into a .net 4 console project to test and I keep getting provider related error messages.
I downloaded the pre-compiled package for targeting .net 4 from the System.Data.SQLite site and copied those dll's into my project then referenced those rather than the dll's installed to the GAC from the 2013 4.5.1 install package, so the dll's should be good.
If need be I can post my error messages and a copy of my app.config file, but I am really wanting to know if I can even use a model created in a 4.5.1 targeted project in a .net 4 targeted project. And I would love some help with how to achieve this if it is possible.


text:
Q: regex: Searching for specific values in a specific location of a string Im fairly new to regex and im looking how to search for a specific value at a specific locaiton within a string.
i work closely with a telegram system and i am looking to search for a specific value within the standardized telegram.
for example:
locations: 01234567890123456789
telegram:  @.?55_50-*8S7/#8H708
im looking for a regex expression that would return all strings with value 5 at location 6 and value #8 at locations 15/16.
thank you for all of your help!!!

A: If in this string telegram: @.?55_50-*8S7/#8H708 the 5 marked as bold is the 6th position, I think this would be a possibility:
^.{5}5.{7}#8.*$

*

*From the beginning of the string ^

*Any character 5 times .{5}

*Match a 5

*Any character 7 times .{7}

*Match #8

*Any character zero or more times till the end of the line .*$
If the @ sign is part of it, you could use ^@.{5}5.{7}#8.*$
If you would like to match telegram: @.?55_50-*8S7/#8H708 you could do it like this:
telegram:\s@.{5}5.{7}#8.*$


text:
Q: Using a function as the second argument of a 'for' loop Let's assume I have the following code:
for(std::vector<int>::iterator i = vect.begin(); i != vect.end(); ++i)
{
    //do smth here
}

Is vect.end() going to be re-called each iteration? If yes, how should I iterate a vector then?
Having a function called inside the logical expression (second argument of the for loop) is generally bad practice?

A: Yes, it will. However, if the compiler can determine that the value returned by vect.end() will never change, it could of course optimize it out. However, if you want to avoid doing it for sure, just change your code to:
for(std::vector<int>::iterator i = vect.begin(), end = vect.end();
    i != end; ++i)
{
    //do smth here
}

You should, of course, make sure your code doesn't rely on end() being checked on every iteration. For example, if you were doing vect.erase(i) on elements in your vector, you would need to make sure you got the new end() iterator every time (and also make sure you assign the result of erase to i).

A: What you have seems perfectly fine. vect.end() should be an O(1) operation, so that's not a huge performance hit.
But if your looking for a alternative:
typedef std::vector<int>::iterator iter;
iter end = vect.end();
for(iter it = vect.begin(); it != end; ++it) {

}

A: Nothing wrong with that.
or:
std::vector<int>::iterator it = vect.begin();
std::vector<int>::iterator end = vect.end();

for(it; it != end; it++) ...

or, if your compiler supports C++11 range-based for loops you can iterate the vector like this:
for(auto x : vect)
{
    //x is the actual int, not an iterator.
}


text:
Q: SVG  code keeps breaking when rendered in any browser I've scoured all corners of the web looking for a solution to this but it seems no one else has had this issue.
Here is my current code:

<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <linearGradient id="mygradient">
            <stop offset="0%" stop-color="red"/>
            <stop offset="100%" stop-color="yellow"/>
        </linearGradient>
    </defs>
    <path id="myID" d="M 0 78.37136556477951 C 207.875 51.32892778872315 207.875 51.32892778872315 415.75 64.85014667675132 C 623.625 78.37136556477951 623.625 78.37136556477951 831.5 60.035876993171016 C 1039.375 41.70038842156255 1039.375 41.70038842156255 1247.25 64.68862384088634 C 1455.125 87.67685926021014 1455.125 87.67685926021014 1663 60.035876993171016 L 1663 3756 L 0 3756 Z" fill="url(#mygradient)"/>
</svg>

Whenever any browser tries to render this, the <linearGradient> breaks completely. This is how it renders in browsers:
<lineargradient id="mygradient"><stop offset="0%" stop-color="red"></stop offset="0%" stop-color="red"><stop offset="100%" stop-color="yellow"></stop offset="100%"></lineargradient id="mygradient">

As you can see, all spaces in the <linearGradient> become   and <linearGradient> becomes <lineargradient>.
Any help with this will be appreciated.

A: Sorted this one out, pasted my <linearGradient> code snippet into a minifier which seemed to fix the issue. Don't know why but it just did.


text:
Q: XML parsing in IOS Shows NULL value in label? i m doing XML parsing using NSXMLParserDelegate..I m getting null value when i print the value in label...I m using simple xml file got in an internet.You can check what is in that file too.anyone pls help..Here is my code
#import "xmlViewController.h"

@implementation xmlViewController
@synthesize label;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"http://www.bonifacedesigns.com/tuts/xmltest.xml"]];
    receivedData=[[NSMutableData alloc]initWithContentsOfURL:url];
    dataParser=[[NSXMLParser alloc]initWithData:receivedData];
    dataParser.delegate=self;
    [dataParser parse];
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//    if(!xmlString){
//
//    }else
//    {
//        [xmlString setString:@""];
//    }
  if([elementName isEqualToString:@"elements"])
  {
      xmlString=[NSMutableString alloc];
      [xmlString setString:@""];
  }

}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    xmlString= (NSMutableString *)[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{

        if([elementName isEqualToString:@"element"]){

            NSString *string=xmlString;
            [xmlArray addObject:string];
            label.text=[NSString stringWithFormat:@"%@",xmlArray];

       }

}

@end

This is my XML file....I want to print XML Data Parsed! in my label.Help me with that.I have edited the code and check now
<elements>
<element myData="XML Data Parsed!"/>
</elements>

check this:
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//    if(!xmlString){
//
//    }else
//    {
//        [xmlString setString:@""];
//    }

  if([elementName isEqualToString:@"elements"])
  {

      xmlString=[[NSMutableString alloc]initWithCapacity:5];
  }

}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    xmlString= (NSMutableString *)[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{

        if([elementName isEqualToString:@"element"]){
            [attributeDict objectForKey:@"myData"];
            [xmlString setString:@""];
            NSString *string=xmlString;
            [xmlArray addObject:string];
            label.text=[NSString stringWithFormat:@"%@",xmlArray];

       }

I m getting error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with setString:'
*** First throw call stack:
(0x13ba052 0x154bd0a 0x1362a78 0x13629e9 0x1387970 0x2a26 0x9e1a35 0x5171532 0x9e002d 0x26b8 0xd764e 0x37a73 0x37ce2 0x37ea8 0x3ed9a 0xfbe6 0x108a6 0x1f743 0x201f8 0x13aa9 0x12a4fa9 0x138e1c5 0x12f3022 0x12f190a 0x12f0db4 0x12f0ccb 0x102a7 0x11a9b 0x2238 0x2195 0x1)
terminate called throwing an exception

A: I guess that the problem is in this line:
xmlString== (NSMutableString *)[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Change == to =
Hope that explanation isn't needed.

A: It seems you have several errors in your code.
The mutable string xmlString isn't properly initialized, on the line :
xmlString = [NSMutableString alloc]; // wrong

This should look like : xmlString = [[NSMutableString alloc] initWithCapacity:X];.
Also, when the parser finds characters, you replace the entire existing mutable string, instead of appending them to the existing content, or try to because according to the code, you simply make a memory address compare and waste the result (==).
// wrong
xmlString == (NSMutableString *)[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

This should look like :
[xmlString appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];

Finally in didEndElement, I'm not sure what you are trying to achieve, but you add the string object reference to an array, and then set the label text to display the content of the array... as long as the mutable array is well allocated and initialized (what I'm really not sure), the label should display at least the array content.  But you might consider to "flush" the mutable string ([xmlString setString:@""];) and not allocate it on every element.
EDIT :
The attributeDict maps attribute names as the keys with their values. I guess your attribute value can be accessed via [attributeDict objectForKey:@"myData"];.


text:
Q: Minimum value of $y=\sin( 2x) - x$, where $x\in [-\frac{\pi}2,\frac{\pi}2]$ I tried applying the concept that at minima, derivative of $y$ with respect to $x$ should be zero, but realised that it fails as the domain is restricted.
Rightly, upon plotting the graph, we can see that we cannot equate $\frac{\mathrm dy}{\mathrm dx}$ to be zero.
Can you help me arrive at the solution in a way that doesn't require graph plotting?

A: The derivative test claims that local extrema in the interior of the domain are to be found among the zeros of the derivative; as noted above, in this case $\pm{\frac{\pi}{6}}$ are the zeros of the derivative and it is easy to see that the plus one is a local maximum and the minus one is a local minimum.
However, the boundary points need also to be checked as there the function may have an extremum without the derivative being zero, and in this case it is trivial to see that $-\frac{\pi}{2}$ is the global minimum attained at $\frac{\pi}{2}$ since $\sin({2x}) \ge 0, x \in [0,\frac{\pi}{2}]$, hence $\sin({2x})-x \ge -x \ge -\frac{\pi}{2}$ there while the function is odd and for negative $x$ obviously at least $-1$ (actually the local minimum for negative $x$ is at $-\frac{\pi}{6}$ and hence it is $-\frac{\sqrt{3}}{2}+\frac{\pi}{6}=-0.34...$

A: $$\frac{dy}{dx}=2\cos(2x)-1=0$$ has the solutions
$$x=\pm\frac\pi3$$ in the specified interval.
Now compare the values of the function at the stationary points and interval endpoints.

A: Why can't you equate its derivative to 0??
$$\frac{dy}{dx}=2\cos(2x)-1=0$$ gives:
$$cos(2x)= \frac12$$
Hence, we obtain
$$x=\pm\frac\pi6$$ which are in the specified interval.
Note that these are the points of local maxima and minima. The max and min over the entire given domain will obviously be at $-\frac\pi2$ and $\frac\pi2$ respectively.

A: Choice of the domain is restricted to the domain interval you stated as bounded between two limits. But everything else remains same.
Derivative $ \dfrac{dy}{dx}=2\cos(2x)-1  $ vanishes at an infinite number of points when domain is not restricted to $ x= \pm \dfrac{\pi}{3}.$ When  you selected a truncated interval $|x|<\dfrac{\pi}{2}  $ the derivative underwent sign change only twice.


text:
Q: Am i missing something in this code? I want to install google tag manager with provided code by google tag manager site. But it return error after i implement it in the first .
This is the code :

The error return is "Unexpected start tag token (iframe) in the frameset phase" and "Unexpected end tag (noscript)"
Any idea guys?

A: How is your page file saved in your editor? ASCII, UTF-8, anything else?
When you change the file encoding, does the error go away?
Another helpful info might be reading the official quick start guide by Google https://developers.google.com/tag-manager/quickstart
Something else that I though of, is your tag manager code within an open PHP code tag? If yes, is it properly called within your code?
Something like...
<?php
.....php code here

Can you post your full code?
The information that @Frayne Konok gave you is not correct! The code must be right after the opening  tag, NOT before the closing tag!


text:
Q: How do I run a function once session storage is != undefined I am in a situation wherein I have a an external JavaScript file that makes an ajax call and saves certain data to session storage. The JavaScript file loads from an external site and therefore, I cannot edit it.
I need to run a function to consume the saved data as soon as it loads into session storage. How can I trigger a function once this data loads?

A: Maybe this can help you:
window.onstorage = function(e) {
  console.log('The ' + e.key + ' key has been changed from ' + e.oldValue + ' to ' + e.newValue + '.');
};

More info here and here
So you could subscribe to your session key changes with (not tested):
window.onstorage = function(e) {
    if (
        e.storageArea === sessionStorage &&
        e.key === "<your_key>" &&
        e.oldValue === undefined &&
        e.newValue !== undefined
    ) {
        console.log("my key is not undefined anymore")
    }
};

UPDATE: So it seems that it is not working for you. Then you can try something like this (using interval to check if sessionStorage changes):
var INTERVAL = 2000;
// Then, in your code you can check every `INTERVAL` milleconds
// if the sessionKey you need is not null
console.log("Program starts");
// You can limit your intents too
var limit = 5;
var intervalId = setInterval(function() {
  console.log("Checking sessionStorage");
  var test = sessionStorage.getItem("test");
  if (test !== null) {
    console.log("'test' is now defined: " + test);
    clearInterval(intervalId);
  }

  if (--limit <= 0) {
    console.log("'test' has not changed");
    clearInterval(intervalId);
  }
}, INTERVAL);

Test here: https://jsbin.com/tukubutoje/edit?js,console

A: See StorageEvent:

A StorageEvent is sent to a window when a storage area it has access to is changed within the context of another document.

For example:

window.addEventListener('storage', function(e) {
  document.querySelector('.my-key').textContent = e.key;
  document.querySelector('.my-old').textContent = e.oldValue;
  document.querySelector('.my-new').textContent = e.newValue;
  document.querySelector('.my-url').textContent = e.url;
  document.querySelector('.my-storage').textContent = e.storageArea;
});

Here we add an event listener to the window object that fires when the Storage object associated with the current origin is changed. As you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the URL of the document that changed the storage, and the storage object itself.


text:
Q: Starting a specific app in Android I know how to load a PDF file in Android. But if more than one PDF viewers are installed, Android shows a list to choose from. I want to load my PDF file with a specific PDF viewer (say DroidReader). How to do this?

A: I would strongly recommend not specifying an explicit class name in the Intent as the accepted answer recommends, since that is an implementation detail of the app that can change at any time on you.
Instead, build your Intent like normal, but use Intent.setPackage() to specify the system should only look in the desired app's package name for matching activities.  That is:
Intent intent = new Intent(Intent.ACTION_VIEW, uriToView);
intent.setPackage("com.package.name.of.droidreader");
startActivity(intent)

A: Then specify the complete name of the activity:
    Intent intent = new Intent();
    ComponentName comp = new ComponentName("com.package.name.of.droidreader", "com.package.name.of.droidreader.DroidReader");
    intent.setComponent(comp);
    startActivity(intent);

To know what the package name and activity are, you could take a look at the adb logcat output: when you open an activity it gets logged there. And, of course, configure the intent correctly so that the DroidReader know what file to open.
Lastly, but important, you should surround the startActivity method with a try-catch block catching the ActivityNotFoundException (I'm sure that most of the handsets won't have that specific app).


text:
Q: getting "java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver" I have try many things but still getting same error. I am using jdK7 and Microsoft sql 2008 and eclipse,jar file is sqlijdc41.jar(4.1)
I have added the jar file using build path configure build path.
below is my code.
package com.daccess.captureimg;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class CaptureImage
 */
@WebServlet("/CaptureImage")
public class CaptureImage extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public CaptureImage() {
        super(); }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String url = "jdbc:sqlserver://localhost:60700;databaseName=sampleprojectdb;user=sa;password=dsspl@123";

        try {
            System.out.println("connecting to the db");
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            System.out.println("driver get register");
            Connection con=DriverManager.getConnection(url);
            System.out.println("connected to the db");
            Statement stm=con.createStatement();
            stm.executeUpdate("insert into GPSLoaction1 values('123477.7','3467.7','gfasdgfghfsd')");

            System.out.println("Value insearted");
        } catch (Exception e) { e.printStackTrace(); }

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}

Below is the error in console:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at com.daccess.captureimg.CaptureImage.doGet(CaptureImage.java:40)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Please Help me where I am wrong.


text:
Q: Create and set styles in Excel cells using C#? How to create and set styles in Excel cells using C#?
I want to write something like "April 1st" with st as a superscript.
I would be using a string format not a date format.
I have tried http://msdn.microsoft.com/en-us/library/f1hh9fza.aspx but getting an The name 'Globals' does not exist in the current context error. I have added assembly Microsoft.Office.Interlop.Excel. Am I missing any other assembly?
Excel.Style style = Globals.ThisWorkbook.Styles.Add("NewStyle");

A: You actually don't want to change the font of the whole cell but you to change a portion of the text in the cell I take it.
You'll still need to retrieve the cell range and then adjust the characters within that range. here is an example where it's just adjusting the first cell. A1.
If you wanted to change the whole cell range to be superscript it would be done like this
    currentRange.Font.Superscript  = true;
void Main()
{
         var app = new Application();
        app.Visible = true;
        var workbook = app.Workbooks.Add(1);

        Sheets excelSheets = workbook.Worksheets;
        string currentSheet = "Sheet1";
        Worksheet worksheet1 = (Worksheet)excelSheets.get_Item(currentSheet);

        worksheet1.Cells[1, 1] = "April 1st";
        worksheet1.Cells[1, 2] = "April 2nd";
        worksheet1.Cells[1, 3] = "April 3rd";
        worksheet1.Cells[1, 4] = "April 4th";

        // fill in the starting and ending range programmatically this is just an example.
        string startRange = "A1";
        string endRange = "A1";
        Range currentRange = worksheet1.get_Range(startRange , endRange );

        var text = currentRange.Text.ToString();
        int length = text.Length;
        int index = 0;
        if(text.Contains("st"))
        {
            index =text.IndexOf("st");
        }
        //The other checks for "nd", "rd", "th" obviously check to see a # precedes these.

        if(index > 0)
        {
            currentRange.get_Characters( index+1, 2).Font.Superscript  = true;
        }
}

A: As the MSDN article you've linked to states:

Applies to: The information in this topic applies to document-level
  projects and application-level projects for Office 2013 and Office
  2010. See Features Available by Office Application and Project Type.

To use Globals class you have to create Office project. For another reference you can check this question about creating Office add-in:

Globals.ThisAddin.Application can be only used in VSTO Add-In


text:
Q: Passing function in React-Native audio player I am trying to play sounds dynamically based on a function called meditationList. The return of the function gives me the right path which it works in the player.
However, if I call the function on the URL is not working giving me the following error: Rejection, Can't find variable meditationList. I also tried with JSON.stringify to return adress.meditation.meditationPlayerAdress but no luck

export default class Player extends React.Component<Props> {
  meditationList = () => {
    const adress = this.props.route.params;

    return adress.meditation.meditationPlayerAdress; //console.log returns ../../assets/track1.mp3
  };

  audio = () => {
    TrackPlayer.setupPlayer().then(async () => {
      // Adds a track to the queue

      await TrackPlayer.add({
        id: 'trackId',
        url: require('../../assets/track1.mp3'), // this.require(meditationList())- warning that variable meditationList cannot be found
        title: 'Track Title',
        artist: 'Track Artist',
      });

      let trackId = await TrackPlayer.getCurrentTrack();

      // Starts playing it
      TrackPlayer.play();
    });
  };

  pause = () => {
    TrackPlayer.pause();
  };

  stop = () => {
    TrackPlayer.stop();
  };

  render() {
    return (
      <SafeAreaView style={styles.container}>
        <View style={{alignItems: 'center'}}>
          <View style={{alignItems: 'center', marginTop: 24}}>
            <Text style={[styles.textLight, {fontSize: 12}]} />

            <Text
              style={[
                styles.text,
                {fontSize: 15, fontWeight: '500', marginTop: 8},
              ]}>
              {this.meditationList()}
            </Text>
          </View>

          <View style={styles.coverContainer}>
            <Image
              source={require('../../../assets/coverArt.jpg')}
              style={styles.cover}
            />
          </View>

          <View style={{alignItems: 'center', marginTop: 32}}>
            <Text style={[styles.textDark, {fontSize: 20, fontWeight: '500'}]}>
              Exhale
            </Text>
            <Text style={[styles.text, {fontSize: 16, marginTop: 8}]}>sal</Text>
          </View>
        </View>

        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'center',
            alignItems: 'center',
            marginTop: 16,
          }}>
          <TouchableOpacity onPress={this.stop}>
            <FontAwesomeIcon icon={faStop} size={32} color="#93A8B3" />
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.playButtonContainer}
            onPress={this.audio}>
            <FontAwesomeIcon
              name="play"
              icon={faPlay}
              size={32}
              color="#3D425C"
            />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.pause}>
            <FontAwesomeIcon icon={faPause} size={32} color="#93A8B3" />
          </TouchableOpacity>
        </View>
      </SafeAreaView>
    );
  }
}

A: meditationList cannot be found solution :
As you are using class based component, anything defined within that, you can access that via this.ANYTHING_DEFINED, but not directly, so here we need this.meditationList()
You can use meditationList() within function based component without error.

require(var) will not take dynamic varibale
You cannot use variables in require. All requires must be statically analyzable. That means you always have to write require('/path/to/file'). SOURCE

But, you can do something like this, SOURCE
const IMAGES = {
  image1: require('../image1'), // statically analyzed
  image2: require('../image2'), // statically analyzed
}

getImage(num: number) { // dynamically invoked
  return IMAGES['image' + num];
}

A: For everybody who got this problem. I couldn't find an easy solution for it, but I found one quite convenient walk around.
Considering that is not good for an app to store all the audio files in local storage(especially in cases of big apps ), I decided to set the path of my URL to an audio link, hence solving the problem with "required"
Now my code looks like this and works perfectly
meditationList = () => {
    const adress = this.props.route.params;

    return adress.meditation.meditationPlayerAdress; //returns a URL link now
  };
audio = () => {

    TrackPlayer.setupPlayer().then(async () => {
      // Adds a track to the queue

      await TrackPlayer.add({
        id: 'trackId',
        url: this.meditationList(),
        title: 'Track Title',
        artist: 'Track Artist',
      });