text:
Q: Loop over each file in folder directory and check date Azure Data Factory V2 -wrong code I want to loop over each file in a stfp folder and check whether it is new or not and then copy the new files on a Data Lake
Right now I have the below code but I don't think it is correct. There is no usage of @item() in the second GetLastModifyfromFile activity to refer to the items last date  in the loop but rather to a completely different data set called SrcLocalFile.
{
"name": "IncrementalloadfromSingleFolder",
"properties": {
    "activities": [
        {
            "name": "GetFileList",
            "type": "GetMetadata",
            "policy": {
                "timeout": "7.00:00:00",
                "retry": 0,
                "retryIntervalInSeconds": 30,
                "secureOutput": false
            },
            "typeProperties": {
                "dataset": {
                    "referenceName": "SrcLocalDir",
                    "type": "DatasetReference"
                },
                "fieldList": [
                    "childItems"
                ]
            }
        },
        {
            "name": "ForEachFile",
            "type": "ForEach",
            "dependsOn": [
                {
                    "activity": "GetFileList",
                    "dependencyConditions": [
                        "Succeeded"
                    ]
                }
            ],
            "typeProperties": {
                "items": {
                    "value": "@activity('GetFileList').output.childItems",
                    "type": "Expression"
                },
                "activities": [
                    {
                        "name": "GetLastModifyfromFile",
                        "type": "GetMetadata",
                        "policy": {
                            "timeout": "7.00:00:00",
                            "retry": 0,
                            "retryIntervalInSeconds": 30,
                            "secureOutput": false
                        },
                        "typeProperties": {
                            "dataset": {
                                "referenceName": "SrcLocalFile",
                                "type": "DatasetReference"
                            },
                            "fieldList": [
                                "lastModified"
                            ]
                        }
                    },
                    {
                        "name": "IfNewFile",
                        "type": "IfCondition",
                        "dependsOn": [
                            {
                                "activity": "GetLastModifyfromFile",
                                "dependencyConditions": [
                                    "Succeeded"
                                ]
                            }
                        ],
                        "typeProperties": {
                            "expression": {
                                "value": "@and(less(activity('GetLastModifyfromFile').output.lastModified, pipeline().parameters.current_time), greaterOrEquals(activity('GetLastModifyfromFile').output.lastModified, pipeline().parameters.last_time))",
                                "type": "Expression"
                            },
                            "ifTrueActivities": [
                                {
                                    "name": "CopyNewFiles",
                                    "type": "Copy",
                                    "policy": {
                                        "timeout": "7.00:00:00",
                                        "retry": 0,
                                        "retryIntervalInSeconds": 30,
                                        "secureOutput": false
                                    },
                                    "typeProperties": {
                                        "source": {
                                            "type": "FileSystemSource",
                                            "recursive": false
                                        },
                                        "sink": {
                                            "type": "BlobSink"
                                        },
                                        "enableStaging": false,
                                        "dataIntegrationUnits": 0
                                    },
                                    "inputs": [
                                        {
                                            "referenceName": "SrcLocalFile",
                                            "type": "DatasetReference"
                                        }
                                    ],
                                    "outputs": [
                                        {
                                            "referenceName": "TgtBooksBlob",
                                            "type": "DatasetReference"
                                        }
                                    ]
                                }
                            ]
                        }
                    }
                ]
            }
        }
    ],
    "parameters": {
        "current_time": {
            "type": "String",
            "defaultValue": "2018-04-01T00:00:00Z"
        },
        "last_time": {
            "type": "String",
            "defaultValue": "2018-03-01T00:00:00Z"
        }
    },
    "folder": {
        "name": "IncrementalLoadSingleFolder"
    }
},
"type": "Microsoft.DataFactory/factories/pipelines"

}

A: Just a thought - I don't see your dataset definition but...
Should you pass in path and file name to the dataset as parameters?
i.e. add 2 parameters to the dataset definition for path and file (say pathparam and fileparam).  Use those parameters in the dataset's fileName and folderName settings as @dataset().pathparam and @dataset().fileparam.
In the code above, pass in parameters a new "parameters" section of the dataset input with pathparam and fileparam equal to the folder and child item you retrieved from earlier activity.
note - there was a bug that the dataset name could not have spaces in it.


text:
Q: inverter to rectifier I'm putting together an experimental geo resistivity measuring device following vague instructions found on the internet. I was wondering if it is safe to connect a Mastervolt AC MASTER 12/500 inverter to a MDQ 100A 1600V rectifier. Also I would like to know what approximate DC voltage would I obtain?
http://www.mastervolt.com/products/ac-master-12v/ac-master-12-500/
http://goldelectric.ca/download/MDQ.pdf
Thanks!

A: You will get about 320 volts DC from the rectifier.  A 30 Amp rectifier would be more than adequate, as the inverter can only deliver about 2 Amps.
Whether this is safe or not depends on how you wire things, and what you are doing with the 320 volts DC.
230 Volts AC and 320 volts DC ARE DANGEROUS if you don't know what you're doing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jxbrowser 6.2 proxy authentication The dialog that displays when using this code does not have a username and password textboxes. Is this a bug or am I doing something wrong?
browser.getContext().getNetworkService().setNetworkDelegate(new DefaultNetworkDelegate() {
        @Override
        public boolean onAuthRequired(AuthRequiredParams params) {
            if (params.isProxy()) {
                params.setUsername("proxy-username");
                params.setPassword("proxy-password");
                return false;
            }
            return true;
        }
    });

A: This code doesn't display a dialog. This code just sets username and password values and return. If you need to display login dialog, then you don't need to register NetworkDelegate.


text:
Q: Spreading array over Ramda's pipe function gives type error "Expected 1-6 but got 0 or more" I'm at a loss as to how I can make this work.  I'm defining a function in typescript that essentially wraps Ramda's pipe function.  I want to accept values that may or may not be functions, wrap the non-function values in constant functions, and then pass it all to pipe.
Here's the original function I tried writing:
const convertToPipeable = (values: any[]) => {
  const valueFunctions = map(valueAsFunction, values);

  return pipe(...valueFunctions);
}

At the point where I spread valueFunctions over pipe, typescript complains saying "Expected 1-6 arguments, but got 0 or more".  I realise it's because pipe is typed with overloads for each argument length case (from 1 until 6), but I'm having a hard time believing that it's not possible to spread this array over it.  I've tried several things, from defining the values argument as a big tuple, to using Ramda's apply method in place of the spread operator, and none of these have worked properly.
If there is no good way to type this, what might be the alternative?
Cheers!

A: If the type declaration for pipe only accepts up to 6 arguments, but you have an array that (as far as the compiler knows) can be arbitrarily long, then the best you can do with pipe is:
return (<any>pipe)(...valueFunctions);

I'm not familiar with Ramda to know if there are other Ramda functions you may be able to use instead.


text:
Q: Acessing directory in bucket S3 and getting the itens I am having some issues understanding the documentation, I have something like this in my bucket:
—- videos
      —-carvideos
         Tesla.video
         Chevrolet.video
      Car.png
      Bike.png

—-Files

And I want to access  the video directory and get the car.png file, And to enter  the carvideos directory and get all the videos in it.How do I do that?
My code:
import boto3
s3 =boto3.resource('s3', access_key, secret_acess_key)

bucket = s3.Bucket('name of my bucket')

A: You can access the car.png file like this:
import boto3

s3_resource = boto3.resource('s3')

s3.Object('mybucket', 'videos/Car.png').download_file('/tmp/Car.png')

Note that the filename (Key) of the object includes the full path to the object.
To obtain a listing of all objects in the carvideos directory, you can use:
bucket = s3_resource.Bucket('mybucket')

objects = bucket.objects.filter(Prefix='videos/carvideos/')

for object in objects:
  print(object.Key)


text:
Q: Prove/Disprove: a function is uniformly continuous
Prove/Disprove: $f(x)$ is defined and second derivative is bounded in $I$, so $f(x)$ is uniformly continuous.

I have started with simple functions like $x^2$ but on a closed interval it is uniformly continuous, moreover, I can not find a connection between derivatives and uniformly continuous

A: It is FALSE if $I$ is not bounded. Take for example $I=\mathbb{R}$ and $f(x)=x^2$. Then $f$ is not uniformly continuous in $I$ but its second derivative is bounded.
It is TRUE if $I$ is a bounded interval.  If the second derivative is bounded in $I$ then also the first derivative is bounded: let $x_0\in I$ then for any $x\in I$, there is $t$ between $x$ and $x_0$ such that
$$f'(x)-f'(x_0)=f''(t)(x-x_0)\Rightarrow |f'(x)|\le |f'(x_0)|+M|I|$$
where $\sup_{x\in I}|f''(x)|=M$ and $|I|$ is the size of $I$.
Hence $f$ is Lipschitz which implies that $f$ is uniformly continuous in $I$.

A: If just the first derivative is bounded then it is uniformly continuous (think Lipschitz continuity). But the statement is not true (viz. $x^2$ on real line)


text:
Q: Proof that RLC networks are linear? I've been learning about RLC networks, superposition, two-port circuits etc. and a lot of derivations and equations implicitly assume the fact that the circuits in question are linear, no matter the weird and wonderful arrangements of the resistors, inductors and capacitors.
This sort of makes sense to me intuitively, but is there any proof (or any way to prove) that all RLC passive networks (except exceptions such as with non-ideal components) behave linearly?

A:

there any proof (or any way to prove) that all RLC passive networks (except exceptions such as with non-ideal components) behave linearly?

Yes , Let's say a complex circuit of N- meshes having R,L,C elements(with no initial conditions), then you can always write mesh equation for each mesh and you'll get N  integro -differential equation which on differentiation gives you a linear constant cofficient   differential equation , so now you have N variables and N differential equation , and by substitution method,  you can always get a unique linear constant cofficient differential equation with desired input output variables .
And hence, we can say that no matter how complex R,L,C circuit is you'll always get a LCCDE between input and  output ,which is certainly a linear relation .

A: For a resistor, inductor and capacitor there is a linear relationship between voltage and current.
For a resistor: \$ V_R=RI\$
For an inductor: \$V_L=Z_LI=j\omega L\cdot I \$
For a capacitor: \$V_C=Z_CI= \frac{1}{j\omega C}\cdot I \$
As you can see, the voltage across the various components is proportional to the current flowing through it, with the proportional constant being either \$R, \: j\omega L \$ or \$\frac{1}{j\omega C} \$.
Hence, any combination of a resistor, inductor and capacitor will also result in a linear relationship between voltage and current. So the entire system is linear.


text:
Q: How to set a select query to a column of another select query in SQL? I have a query that I do not have a problem with.you can see its result
SELECT
    FICHENO AS [Sifariş Nömrəsi],
    SHPAGNCOD AS [Maşın Nömrəsi],
    DATE_ AS Tarix,
    ISNULL(CAST(T1.txtGirishSaati AS VARCHAR), '-') AS [Giriş Tarixi],
    CASE
       WHEN T1.txtGirishSaati IS NOT NULL
          THEN N'İcazə verilib'
          ELSE ' - '
    END [Giriş Statusu],
    ISNULL(CAST(T2.ChixishTarixi AS VARCHAR), '-') as [Çıxış Tarixi],
    CASE
       WHEN T2.ChixishTarixi IS NOT NULL
          THEN N'İcazə verilib'
          ELSE ' - '
    END [Çıxış Statusu]
FROM
    TGR3.dbo.LG_999_01_ORFICHE AS Logo
LEFT JOIN
    EBATEST.dbo.E_GirishFormu_Form as T1 ON Logo.LOGICALREF = T1.SifarisNoCombo
LEFT JOIN
    EBATEST.dbo.E_Chixish_Form as T2 ON Logo.LOGICALREF = T2.Sifarish
WHERE
    Logo.TRCODE IN (1, 2)
ORDER BY
    T1.txtTarix DESC

But I want to make a column which is coming from this select:
SELECT
    o.FIRSTNAME + o.LASTNAME as 'Girişi Təsdiq Edən'
FROM
    FLOWREQUESTS f
JOIN
    OSUSERS o ON f.USERID =o.ID
WHERE
    PROCESS = 'GirishFormu' AND FOLLOWSTATUS = 5
ORDER BY
    PROCESSID DESC

So I want a column named 'Girisi Tesdiq eden' in the first query which is coming from the second query
Thanks in advance

A: A good tip for new users is to never post images as a result set, people in this community hate it.
We prefer beautifully formatted text instead.
Also, we love good verifiable datasets, queries, and examples like the below.
create table TableA(Id int not null, ValueA varchar(50) not null)
create table TableB(Id int not null, IdA int not null, ValueB varchar(50) not null)
create table TableC(Id int not null, IdB int not null, ValueC varchar(50) not null)

create table TableX(Id int not null, ValueX varchar(50) not null)
create table TableY(Id int not null, IdX int not null, ValueY varchar(50) not null)
GO

insert into TableA values
(1,'value of A1')
insert into TableB values
(1,1,'value of B1'),(2,1,'value of B2')
insert into TableC values
(1,1,'value of C1B1'),(2,2,'value of C2B2'),(3,2,'value of C3B2')

insert into TableX values
(1,'value of ')
insert into TableY values
(1,1,'A1'),(2,1,'C3B2')
GO

select a.ValueA, b.ValueB, c.ValueC, subquery.[join Field]
from dbo.TableA a
left join dbo.TableB b on b.IdA = a.Id
left join dbo.TableC c on c.IdB = b.Id
left join
(
  select x.ValueX+y.ValueY as [join Field]
  from dbo.TableX x
  join dbo.TableY y on y.IdX = x.Id
) as subquery on subquery.[join Field] = c.ValueC
GO

ValueA      ValueB      ValueC        join Field
----------- ----------- ------------- -------------
value of A1 value of B1 value of C1B1 NULL
value of A1 value of B2 value of C2B2 NULL
value of A1 value of B2 value of C3B2 value of C3B2

(3 linhas afetadas)

Finally, this is an English language Q&A site, and while I find the British language, not the prettiest one I stick to it in my examples because most people here can understand only it.
I hope this was a useful answer.


text:
Q: Chronological numbers order - PHP I need to find the chronological next number.
For example , I have an array :
$numbers = array(1,2,4);

I want function give me the missing chronological number : 3
more example :
$numbers = array(6,7,8,11);

need to give me : 9
Thanks

A: The only way I see doing this is to use sort on your array, then looping through the entire array.
To insert the number at the specified position in the array, look at this.
Use nickb's answer though - much better!

A: The solution is simple once you make the assumption that the array is sorted with:
sort( $numbers);

Then, you can get the complete range of numbers, do a difference on the complete set and the input array, and take the first element (which will be the first element that differs):
Since the array is sorted, we can grab the min and max elements like this (we could also call min() and max()):
$min = current( $numbers);
$max = end( $numbers);

Now, we use range() to get the complete set of numbers, then call array_diff() to find the difference:
$complete = range( $min, $max);
$diff = array_diff( $complete, $numbers);

The first consecutive missing number is in the first element in the difference:
$first_missing = array_shift( $diff);

The benefit here is that $diff will contain all of the missing numbers between the range of $min and $max.

A: This should do the trick:
<?php
function chrono_trigger($array) {
    sort($array, SORT_NUMERIC);
    $prev = False;
    foreach($array as $num) {
        if($prev === False) {
            $prev = $num;
            continue;
        }
        if($prev != ($num-1)) {
            return $prev+1;
        }
        $prev = $num;
    }
    return False;
}

$numbers1 = array(1,2,4); // Should return 3
$numbers2 = array(6,7,8,11); // Should return 9
$numbers3 = array(1,2,3,4); // Shouldn't return anything

// Returns 3
$missing1 = chrono_trigger($numbers1);
var_export($missing1);

// Returns 9
$missing2 = chrono_trigger($numbers2);
var_export($missing2);

// Returns False
$missing3 = chrono_trigger($numbers3);
var_export($missing3);


text:
Q: How can I start an activity before application's oncreate I am making an app that has an application class. I want the application to remain till the point the app is killed. But I also want that whatever is done in the application's oncreate() to be done after taking input from the user. So I have an activity which takes the data from the user. So, is there a way I can launch that activity's oncreate first before the application's oncreate because by default the first thing that is executed is application's oncreate().

A: onCreate() is the first step in the app lifecycle and, as such, there is nothing before onCreate(). You can't do something in something that doesn't exist yet.
What you might want to do is have two different activities, one where you get the data you need from the user, and another one that you call once you have received the data you need.


text:
Q: React bootstrap modal animation property changes doesnt apply as expected I'm trying to create custom ModalManager class and i have problem with showing/hiding animations.I would like to have control how modal will display/hide all the time,for example modal will show up with animation and hide without it.Is there any way to achive such a thing?
Here is some slim example of ModalManager

class App extends React.Component {

 constructor(props){
   super(props)

 this.displayModal = this.displayModal.bind(this)
  }

  render(){

   return (

     <ModalManager ref={(c)=>{this.modalManager = c}} />
      <button onClick={this.displayModal}>display modal</button>

    )

  }

  displayModal(){

   this.modalManager.display('LoadingModal')
    //fake ajax request
    setTimeout(()=>{

      this.modalManager.hide('LoadingModal',false) //hide without animation
     this.modalManager.display('NotificationModal',false) //display without animation

    },2500)

  }

}

class ModalManager extends React.Component {

 constructor(props){
   super(props)
    this.hide = this.hide.bind(this)
    this.display = this.display.bind(this)

   this.state = {

     modals:{
       'LoadingModal':{
         constructor:LoadingModal,
          props:{
           animation:true,
           show:false,
           hide:this.hide
          }
         },
         'NotificationModal':{
         constructor:NotificationModal,
          props:{
           animation:true,
           show:false,
           hide:this.hide
          }
         }
       }

    }

  }

  render(){

   return(

    {Object.keys(this.state.modals).map((key) =>{

       var Modal = this.state.modals[key].constructor,
      props = this.state.modals[key].props;

     return (

       <Modal key={key} modalKey={key} {...props}/>

      )

    })}

    )

  }

  updateAnimation(key,value){

   this.setState((prevState)=>{
      prevState.modals[key].props.animation = value

     return {

       modals:prevState.modals,

      }

    })

  }

  display(key, animation = true){

   this.setState((prevState)=>{

      prevState.modals[key].props.animation = animation
     prevState.modals[key].props.show = true

     return {

       modals:prevState.modals,

      }

    })

  }

  hide(key,animation = true){
   this.setState((prevState)=>{
      prevState.modals[key].props.show = false
      prevState.modals[key].props.animation = animation

     return {

       modals:prevState.modals,

      }
    })

    setTimeout(()=>{
     this.setState((prevState)=>{
     prevState.modals[key].props.show = false
     return {

       modals:prevState.modals,

      }

    })
    },0)

  }

}

class LoadingModal extends React.Component {

 constructor(props){
   super(props)

    this.hide = this.props.hide.bind(null,'LoadingModal',true)
  }

  render(){

   return(

       <ReactBootstrap.Modal {...this.props}>
          <ReactBootstrap.Modal.Header >
            Loading Modal
          </ReactBootstrap.Modal.Header>

           <ReactBootstrap.Modal.Body >
            Loading...
          </ReactBootstrap.Modal.Body>

          <ReactBootstrap.Modal.Footer >
            I will self close in a moment without animation
          </ReactBootstrap.Modal.Footer>

        </ReactBootstrap.Modal>

    )

  }

}

class NotificationModal extends React.Component {

 constructor(props){
   super(props)

    this.hide = this.props.hide.bind(null,'NotificationModal',true)
  }

  render(){

   return(

       <ReactBootstrap.Modal {...this.props}>
          <ReactBootstrap.Modal.Header >
            Notification Modal
          </ReactBootstrap.Modal.Header>

           <ReactBootstrap.Modal.Body >
            Change modal without animation
          </ReactBootstrap.Modal.Body>

          <ReactBootstrap.Modal.Footer >
          <button onClick={this.hide}>Hide me</button>

            I should close with animation
          </ReactBootstrap.Modal.Footer>

        </ReactBootstrap.Modal>

    )

  }

}

ReactDOM.render(<App></App>, document.getElementById('app'))

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

Its weird because my code work on first transition but when you press hide button it doesn't overwrite default animation property.I have also noticed that div with modal drop doesn't disappear after last modal hide.


text:
Q: Select rows as columns for wordpress post meta WordPress's wp_postmeta table has all the additional fields for a post but they are in rows so it's easy to add more.
However, now I want to query for all the fields of all the posts lets say, I obviously want those fields in a column and not a row.
This is my query that I am running
SELECT p.post_title,
       m.meta_value,
       m.meta_key
FROM   wp_posts p
       JOIN wp_postmeta m
         ON p.id = m.post_id
WHERE  p.id = 72697;

This will give me all the meta_values and their respective meta keys as columns. But I need the meta keys values as columns and meta values as rows
For example a meta_key could be additional_description and it's value could be What's up
So I need something like this
SELECT p.post_title, additional_description
FROM   wp_posts p
       JOIN wp_postmeta m
         ON p.id = m.post_id
WHERE  p.id = 72697;

I need it as a column. I also need all of the posts and not a specific one, but whenever I remove the where it just doesn't query (I have lots of posts, that could be an issue).
Here is some sample data and how I want the results to show up
wp_postmeta table
meta_key    post_id     meta_key    meta_value
1       5       total_related   5
2       5       updated     0
3       5       cricket     1
4       8       total_related   8
5       8       updated     1
6       8       cricket     0

wp_post table

id  post_title      other things I dont care about
5   This is awesome
8   This is more awesome

wp_post id is related to post_id on wp_postmeta table
Result wanted
post_title      total_related   updated     cricket
This is awesome     5       0       1
This is more awesome    8       1       0

A: Try that:
select post_title ,
 MAX(CASE WHEN `meta_key`='total_related' THEN meta_value END)as 'total_related',
 MAX(CASE WHEN `meta_key` = 'updated' THEN meta_value END) as 'updated' ,
 MAX(CASE WHEN `meta_key` = 'cricket' THEN meta_value END) as 'cricket'
FROM   wp_posts p
JOIN wp_postmeta m ON p.id = m.post_id
GROUP BY p.id

A: There are several approaches.
Here's an example of one way to get the specified result, using correlated subqueries in the SELECT list:
SELECT p.post_title
     , ( SELECT m1.meta_value
           FROM wp_post_metadata m1
          WHERE m1.meta_key = 'total_related'
            AND m1.post_id = p.id
          ORDER BY m1.meta_key LIMIT 1
       ) AS `total_related`
     , ( SELECT m2.meta_value
           FROM wp_post_metadata m2
          WHERE m2.meta_key = 'updated'
            AND m2.post_id = p.id
          ORDER BY m2.meta_key LIMIT 1
       ) AS `updated`
     , ( SELECT m3.meta_value
           FROM wp_post_metadata m3
          WHERE m3.meta_key = 'cricket'
            AND m3.post_id = p.id
          ORDER BY m3.meta_key LIMIT 1
       ) AS `cricket`
  FROM wp_posts p
 WHERE p.id IN (5,8)

There are several other approaches, each with its own advantages and drawbacks.
There's a somewhat related question I referenced in a comment on the question. That question illustrates several approaches, but omits a correlated subquery approach.)

A: What about something like this?
SELECT p.post_title, m1.meta_value as 'total_related', m2.meta_value as 'updated', m3.meta_value as 'cricket'
FROM wp_posts p
LEFT JOIN wp_postmeta m1
    ON p.id = m1.post_id AND m1.meta_key = 'total_related'
LEFT JOIN wp_postmeta m2
    ON p.id = m2.post_id AND m2.meta_key = 'updated'
LEFT JOIN wp_postmeta m3
    ON p.id = m3.post_id AND m3.meta_key = 'cricket'

And since you aren't looking for a specific post you should be able to do this.
If you want to query specific post_types you can try something like this
SELECT p.post_title, m1.meta_value as 'total_related', m2.meta_value as 'updated', m3.meta_value as 'cricket'
FROM wp_posts p
LEFT JOIN wp_postmeta m1
    ON p.id = m1.post_id AND m1.meta_key = 'total_related'
LEFT JOIN wp_postmeta m2
    ON p.id = m2.post_id AND m2.meta_key = 'updated'
LEFT JOIN wp_postmeta m3
    ON p.id = m3.post_id AND m3.meta_key = 'cricket'
WHERE p.post_type = 'my_custom_post_type';

A: Here's how I did this dynamically - this procedure builds a SQL statement for every postmeta key for a given post type and then runs the "pivot" query for you:
This isn't the fastest query, and we use it only for migration and deep dives into data, but it does the job.
Note that this temporarily resets the max length of the concat function so you can build a large SQL statement:
CREATE PROCEDURE `wp_posts_pivot`(IN post_type_filter varchar(50))
BEGIN

/* allow longer concat */
declare max_len_original INT default 0;
set max_len_original = @@group_concat_max_len;
set @@group_concat_max_len=100000;

SET @sql = NULL;
SELECT
    GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(pm.meta_key = ''',
                meta_key,
                ''', pm.meta_value, NULL)) AS `',
                meta_key,
                '`'))
INTO @sql FROM
    wp_posts p
        INNER JOIN
    wp_postmeta AS pm ON p.id = pm.post_id
WHERE
    p.post_type = post_type_filter;

SET @sql = CONCAT('SELECT p.id
                    , p.post_title
                    , ', @sql, '
                   FROM wp_posts p
                   LEFT JOIN wp_postmeta AS pm
                    ON p.id = pm.post_id
                    where p.post_type=\'',post_type_filter,'\'
                   GROUP BY p.id, p.post_title');

/* reset the default concat */
set @@group_concat_max_len= max_len_original;

/*
select @sql;
*/

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END

You can then call this with a simple call such as this one, which will select a single row for each 'page' post type along with all meta values:
call wp_posts_pivot('page');


text:
Q: Populate Angular formGroup from many observables I have a postcode$ observable and want to populate the postalCode form input with its value when I create the form group using this.customerForm = this.formBuilder.group({}).
This SO post answer suggests initialising the form in a subscribe of the observable:
ngOnInit() {
    // ...
    // .take(2) to ensure that it will run only for the first value:
    contactsObservable.take(1).subscribe(contacts => {
        this.form = this.fb.group({contact: [this.contacts[0], Validators.required]];
    });
    // ...
}

However, my form has a lot of different fields which need populating from various observables...
  initForm = () => {
    this.myForm = this.form.group({
      postCode: ['', Validators.required],
      // ...many other fields...
    });
  };

Is it possible to populate the '' directly from the observable? If so, I can simply pass in the numerous observable values into the one form group builder.

A: One way to solve this is by using forkJoin to combine all your observables.
Basically, this function takes an array of observables, when all are completed, then the emitted values are combined and returned in an array in the same order as your array of observables, more details here.
import { forkJoin } from 'rxjs';

const observables: Array<Observable<TA | TB | TC>> = [observableA$, observableB$, observableC$]; // N quantity of observables

forkJoin(observables).subscribe((responseData: Array<TA | TB | TC>) => {
  this.myForm = this.form.group({
    firstField: [responseData[0] as TA, [Validators.required]],
    secondField: [responseData[1] as TB, [Validators.required]],
    thirdField: [responseData[2] as TC, [Validators.required]],
  });
});


text:
Q: Simple classification in scikit-learn I am trying to develop a simple classification program using scikit-learn. I want to pull in my set of tsv values, save them in an array. Then, save a csv containing the first value of my tsv from above and simply a random 1 or 0. So it will be output to the csv as follows:
tsvValue1, random1or0 eg
string123, 0
foo234, 1

I have all the code (nearly) separately, my problem is fitting it all together.
import numpy as np
from sklearn import metrics,preprocessing,cross_validation
import pandas as p

loadData = lambda f: np.genfromtxt(open(f,'r'), delimiter=' ')

def main():
    traindata = list(np.array(p.read_table('../data/train.tsv'))[:,2])
    testdata = list(np.array(p.read_table('../data/test.tsv'))[:,2])
    y = np.array(p.read_table('../data/train.tsv'))[:,-1]

    X_all = traindata + testdata

    # What can I do below? What can I use to export to csv
    # properly with an appended 1 or 0 value below ?

    from random import randint
    randomInt = randint(0,1) #Inclusive
    testfile = p.read_csv(
        '../data/test.tsv', sep="\t", na_values=['?'], index_col=1)
    pred_df = p.DataFrame(testdata, index=testfile.index, columns=['label'])
    pred_df.to_csv('test.csv')
    print ("your random file has been created..")

if __name__=="__main__":
    main()

UPDATE :
Standard format of input tsv file:
foo1                       foo2   foo3   foo4   fooN
RelevantString123123123
RelevantString456456456
RelevantString789789789

Format of desired resulting csv:
RelevantString123123123,1
RelevantString456456456,0
RelevantString789789789,1

The second 1 or 0 in the csv file being ranzomly generated.

A: Having the file input.tsv with the content (separated by tabs):
foo1                       foo2   foo3   foo4   fooN
RelevantString123123123
RelevantString456456456
RelevantString789789789

This shows how to get the output you want:
>>> import numpy as np
>>> import pandas
>>> df = pandas.read_csv('input.tsv', sep='\t')
>>> df['value'] = pandas.Series(np.random.randint(2, size=len(df)), index=df.index)
>>> df.to_csv('output.csv', cols=['foo1', 'value'], index=False)

The output.csv content is:
foo1,value
RelevantString123123123,1
RelevantString456456456,0
RelevantString789789789,0


text:
Q: Server/Client not communicating correctly (CocoaAsyncSocket) I've got a simple client & server application semi working with CocoaAsyncSocket. I can use the client to connect to the server, and can pass data back and forth between them and the delegate methods seem to fire correctly. My problem is that I can only send data back to a (AsyncSocket *) object that is passed to one of delegate methods. When accepting a connection I add the socket to an NSMutableArray, but later if I try to use the socket writing fails. So
[connectedSockets addObject:newSocket];
//then later
[[connectedSockets objectAtIndex:i] writeData:someData withTimeout:-1 tag:0];

doesn't work. Code is below for server and client. The initial communication does work, but when my notification gets called no data is sent, even though the NSLog statement tests the socket in the array and gets the proper IP Address & port #:
Server:
- (id)init
{
    self = [super init];
    if (self) {
        listenSocket = [[AsyncSocket alloc] initWithDelegate:self];
        [listenSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
        [listenSocket acceptOnPort:42381 error:nil];

        connectedSockets = [[NSMutableArray alloc] init];
        newNotificationDictArray = [[NSMutableArray alloc] init];
        updateNotificationDictArray = [[NSMutableArray alloc] init];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(newJobNotification:)
                                                     name:@"NewJob"
                                                   object:nil];
    }

    return self;

}

-(void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    [connectedSockets removeObject:sock];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    [connectedSockets removeObject:sock];
}

- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
    [connectedSockets addObject:newSocket];
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
if ([newNotificationDictArray count] > 0) {
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:newNotificationDictArray forKey:@"DictArray"];
    [archiver finishEncoding];
    [archiver release];
    [sock writeData:data withTimeout:-1 tag:0];
    [data release];
}

[sock readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    [sock readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
[sock readDataWithTimeout:-1 tag:0];
}

-(void) newJobNotification: (NSNotification *) notification
{
NSDictionary *dict = [notification userInfo];
[newNotificationDictArray addObject:dict];
[updateNotificationDictArray addObject:dict];
NSMutableData *updateData = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:updateData];
[archiver encodeObject:updateNotificationDictArray forKey:@"DictArray"];
[archiver finishEncoding]
[updateNotificationDictArray removeAllObjects];
[archiver release];
NSLog(@"Attempting to write to %@:%i", [[connectedSockets objectAtIndex:0] connectedHost], [[connectedSockets objectAtIndex:0] connectedPort])
[[connectedSockets objectAtIndex:0] writeData:updateData withTimeout:-1 tag:0];
}

and then the client:
- (id)init
{
self = [super init];
if (self) {
    socket = [[AsyncSocket alloc] initWithDelegate:self];
}
return self;
}

-(void) connectToHost: (NSString *) address
{

}

-(BOOL)onSocketWillConnect:(AsyncSocket *)sock
{
[sock retain];
[socket readDataWithTimeout:-1 tag:0];
return YES;
}

-(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"Did Connect on port %i", [sock connectedPort]);
}

-(void) disconnectFromRemoteHost
{
[socket disconnect];
}

-(void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSLog(@"Did Disconnect");
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"Disconnect Error: %@", [err localizedDescription]);
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
[socket readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSArray *dictArray = [[unarchiver decodeObjectForKey:@"DictArray"] retain];
    [unarchiver finishDecoding];
    [unarchiver release];
    for (NSDictionary *dict in dictArray) {
        if ([[dict objectForKey:@"Kind"] isEqualTo:@"New"])
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NewJob" object:self userInfo:dict];
        else if ([[dict objectForKey:@"Kind"] isEqualTo:@"Update"])
            [[NSNotificationCenter defaultCenter] postNotificationName:@"JobUpdate" object:self userInfo:dict];
    }
[socket readDataWithTimeout:-1 tag:0];
}

Help me stackoverflow, you're my only hope!

A: I see 2 potential problems with your posted code. The first seems unlikely to be causing your problems, but I'll post it anyway. In your client code you have:
-(BOOL)onSocketWillConnect:(AsyncSocket *)sock
{
    [sock retain];
    [socket readDataWithTimeout:-1 tag:0];
    return YES;
}

I'm not sure why you would be retaining "sock" here. You already have a retained copy of the socket you created and this seems likely to result in a leak.
As for the second problem, which is more likely to be the cause of your failures, here is what I think is happening. Looking at the documentation for AsyncSocket I see this:

However, AsyncSocket is not thread-safe. You must only invoke methods on AsyncSocket from
  the thread/runloop on which the socket is configured. If you find yourself on a thread which
  is different from the thread on which AsyncSocket is running, and you need to invoke a
  method on AsyncSocket, then you must use a method like performSelector:onThread: to ensure
  the method is invoked on AsyncSocket's thread (and thereby maintaining thread-safety).

Your code that receives notifications and triggers a "later" write is likely in another thread, so even through the thread is valid the write fails to do what you expect. The AsyncSocket documentation goes on to suggest you use GCDAsyncSocket if you want thread safety.


text:
Q: Nexus 7 2013 with Android L camera issue: onPreviewFrame not called I have very basic camera initialization code that gets me preview on Acer A500 (Android 3.1) and Ainol Novo 9 (Android 4.1.1). I've just bought a Nexus 7 2013, installed Android L preview onto it, and found out my camera-related code no longer works. The camera is initialized successfully, no exceptions being thrown, including the startPReview() call. However, onPreviewFrame is not being called at all. What could be the reason?
Could it be because I only have a dummy SurfaceView that's not displayed anywhere?
private SurfaceView   m_surfaceView = new SurfaceView(CameraTestApplication.instance().getApplicationContext());
private SurfaceHolder m_surfaceHolder = m_surfaceView.getHolder();

void initCamera()
{
   m_openedCamera = Camera.open(0);
   ...
   m_openedCamera.setPreviewDisplay(m_surfaceHolder);
   m_openedCamera.setPreviewCallback(this);
   openedCamera.startPreview();
   ...
}

A: Fixed the problem. It was, in fact, related to my artificial SurfaceView - what I did was not good enough. However, this works:
private SurfaceTexture m_previewTexture = new SurfaceTexture(8743);

void initCamera()
{
   m_openedCamera = Camera.open(0);
   ...
   m_openedCamera.setPreviewTexture(m_previewTexture);
   m_openedCamera.setPreviewCallback(this);
   openedCamera.startPreview();
   ...
}


text:
Q: Integral Equations where the Unknown Function depends on the Integration Dummy Consider the following the integral equation:
$$ f(s) = \int_a^b K(s,t) g(s,t) dt, $$
where $f$ and $K$ are known functions, and $g$ is the unknown function we want to solve for.

For example, $K(s,t)$ is the conditional density of a random variable $T$ given $S$. So $K \geq 0$ and $\int K(s,t)dt = 1$. Then the question becomes: if we know the conditional expectation
$$ \mathbb{E}[g(S,T) \mid S] = f(S), $$
then can we back out the original function $g$?

Is there any way to solve this kind of problem? All the books I find talking about integral equations do not allow $g$ to be a function of $s$. I'm really curious about this more general situation where $g$ is a function of both $t$ and $s$ but couldn't find any reference to go to.
Thanks in advance for any help and consideration!


text:
Q: Auto complete commands with "windows like" options (starting with slash) I'm trying to write a custom auto-complete script for zsh (or bash) for a command that has options starting with a slash.
For instance: MyCommand /foo=bar.txt /yolo=test /final=4
I've been trying to use the zsh helper _arguments but it did not work:
#compdef MyCommand

_MyCommand()
{
  local curcontext="$curcontext" state line
  typeset -A opt_args

  _arguments \
    '/foo=:foo:_files'
}

_MyCommand "$@"

But when I replace the / with -- it works well.
How can I achieve this?

A: You can do that using _regex_arguments like this:
matchany=/$'[^\0]##\0'/
_regex_arguments _mycommand "$matchany" \( /$'/foo='/ ':option:option:(/foo=)' "$matchany" ':file:filename:_files' \| /$'/yolo='/ ':option:option:(/yolo=)' "$matchany" ':optarg:optarg:(test this)' \| /$'/final='/ ':option:option:(/final=)' /$'[0-9]##\0'/ ':number:number:' \) \#
_mycommand "$@"

You can read more about _regex_arguments here
http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-Functions
or here: https://github.com/vapniks/zsh-completions/blob/master/zsh-completions-howto.org
The important thing to note here is that there is no null char (\0) at the end of the pattern matches for the option names.


text:
Q: jQueryUI inline DatePicker doesn't work until after I change month I'm using an inline Datepicker with jquery 1.7.2 and jqueryui 1.8.20. the problem I have is that the following doesn't work until I change the month in the datepicker, then it works fine. Any help would be appreciated.
$( "#datepicker" ).datepicker({
       dateFormat: 'D, dd M yy',
       minDate:0,
       onSelect: function(dateText, inst){
            //$('.field_pickDate').html(dateText);
            alert('boo');
            //console.log(dateText);
        }
    });

dateFormat and minDate are both working but the onSelect event isn't firing from the get-go.

A: This is the default functionality of that event.
Its fired when the user "selects" something in the date picker.
To call an event on click (before you show the date Picker) you can use "beforeShow".
$( "#datepicker" ).datepicker({
       dateFormat: 'D, dd M yy',
       minDate:0,
       beforeShow: function(input, inst) {
             alert("Fired on click, before the picker is shown");
       },
       onSelect: function(dateText, inst){
            //$('.field_pickDate').html(dateText);
            alert('boo');
            //console.log(dateText);
        }
    });

Here's a JSFiddle example of it working with your code.
http://jsfiddle.net/applehat/jukJa/1/
You could always just add another event onto the text box, such as $('#datepicker').select(function(){ /* do something */ });
as well, if you want to detect them selecting the field.
================= EDIT ===============
Since you are using it as an Inline element, Im not sure what your problem is. I have updated my JSFiddle here: http://jsfiddle.net/applehat/jukJa/2/
Everything works as expected here, so maybe you have other code causing issues?


text:
Q: settimeout & cleartimeout to start time with a click I'm pretty new with Javascript and jQuery and can't quite figure out settimeout.
What I'm trying to do it start a timer with a click. It will slide a page to where there is an input to enter an email. If, in 20 seconds, there is nothing typed, I want it to do something. But if they do enter something, I'd like the 20 second timer reset to 20 seconds onkeyup. And finally, if the form is submitted, I want the timeout cancelled.
$('#button').click(function(){
  $('#pane').scrollTo( '1000px', 500);
  setTimeout(goback, 20000);
  function goback() {
  $('#pane').scrollTo ('0px', 500);
  $('#input').keyup(function(){
    clearTimeout(goback);
    setTimeout(goback, 20000);
};
$('#submitemail').click(function(){
  //form submit stuff
  clearTimeout(goback);
});

Could you please point me in the right direction?
var timer;
$('#button').click(function(){
     $('#pane').scrollTo( '768px', 0 );
     $('#emailinput').delay(1000).focus();
     $('#slide2fadeout').css("display", "block").fadeOut();
     timer = setTimeout(goback, 20000);              //in 20 seconds start goback function
     function goback(){
         $('#like').scrollTo( '0px', 0 );            //scroll back to top
         $('#emailinput').val('');                   //clear any partial entry
     };
     $('#emailinput').keyup(function(){
         clearTimeout(timer);
         timer = setTimeout(goback, 20000);
     };
});

Here's my actual code... can't seem to get it working right. Any help appreciated.

A: You need to save the return value of setTimeout somewhere in order to cancel it later:
var timer;
$('#button').click(function () {
    ...
    timer = setTimeout(goback, 20000);
    ...
    clearTimeout(timer);
}


text:
Q: Ios - Facebook login - Facebook browser in app connexion not working I'm using Meteor 1.6.1 and using Facebook Login.
Facebook Login is working perfectly on Chrome, Firefox, Facebook browser Android, Mac but it's not working on Facebook in app browser ios.
The popup message never disappears:
Login completed. click here to close this window
This behavior only happens on the Facebook browser on ios.
How reproduce the error:
1- Share the url https://app.lovlyapp.com/ on your timeline
2 - Open the link on your ios facebook app
3 - Connect to the plateform (and you will see the error message).
Could you please help us solve this issue?
Thanks,
Olivier


text:
Q: Android saves session cookies between application launches -- Is this expected? I have an application in a web view that uses session cookies. (Cookies that get deleted when browser is closed). If I login to my web application, and then kill my Android app and then load the url again, the session cookie still persists. This is NOT what I expected. Is this known behavior?
here is my code:
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    String storeUrl = intent.getStringExtra("storeUrl");
    this.webView = (WebView)findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient()
    {
        public void onPageFinished(WebView view, String url)
        {

        }
    });
    webView.loadUrl(storeUrl);
}

A: Afaik, Android store the cookies in the RAM

The CookieSyncManager is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM

You can clear session cookies pro-grammatically, put this onBackPressed method so that when you leave from your application then it will clear the session cookies.
CookieManager cm = CookieManager.getInstance(this);
cm.removeSessionCookie();

http://developer.android.com/reference/android/webkit/CookieManager.html#removeSessionCookie()


text:
Q: Is it possible to have different constraints for different phone sizes in Xcode? I'm not very experienced with xcode and constraints and I was wondering if it were possible to create different constraints depending on screen size.  I'm currently creating a form and ideally, I would want it to look like this:
iPhone 4 vs iPhone 6

A: Yes, it's very much possible! The best is if you refer to the official Apple documentation : Building for Multiple Screen Sizes
It's a guide about size classes, which you can already see when you click on "w Any, h Any" on the bottom bar of Interface Builder in Xcode. You'll see that you can choose which size class, i.e. which iPhone, the constraints you're currently setting up refer to. Of course, in "w Any, h Any" are the constraints for all sizes and then you'd specify other constraints for others size classes, i.e. phone sizes.
I hope this helps!


text:
Q: Passing selected radio button value to groovy controller Unable to obtain value of selected radio button, to the controller class.
I have a radio-group, to display two radio buttons on a page, as well as an input text field, and a button that validates the input, and takes them to the desired page.
The idea is that the user can select the radio button, which will in turn determine the action performed on what is inputed into the text field.
However, I am finding it difficult to pass the value of radio button to the controller, based on which radio button has been selected, this will determine how the user input is validated.
Have looked through the grails documentation, as well as through stack-overflow posts, to try and understand how to pass the value of selected to the groovy controller, from my index.gsp class.
index.gsp:

        <g:radioGroup name="Radio" values="['value1', 'value2']" value="value1" onchange="setRadio(this)">
           ${it.radio} ${it.label}

        </g:radioGroup>

    <g:form>

            <g:textArea class="smallTextArea" name="radioVal" value="Paste your input for value1" />

            <g:actionSubmit value="validate" action="validate" />

</g:form>

controller:
class AesController {

    def index() {

    }
    def validate() {

    }

}

onchange="setRadio(this">
Changes the text shown in the input field with a JS function. By default it shows "Paste your input for value1". Currently if the user changes between the two radio button it changes between "Paste your input for value1" and "Paste your input for value2". The idea is that if they have value1 or value2 selected this will have a different value and different action occurs to the inputted text
I expect the user to be able to select a radio button and this value is passed to the controller so it is know what radio button the user pressed.

A: I would also suggest you to add the radio-button group in the form. However, if this does not work, add a hidden field to your form:
<g:hiddenField name="selectedRadioButton" value="value1" />

And update it in your setRadio(x) javascript function based on the selection.

A: You need to include your radio group into . So it will be:
<g:form>
...
<g:radioGroup name="Radio" values="['value1', 'value2']" value="value1" onchange="setRadio(this)">
...
<g:textArea class="smallTextArea" name="radioVal" value="Paste your input for value1" />
...
<g:actionSubmit value="validate" action="validate" />
</g:form>

Then you can easily access to radio button value by params.Radio


text:
Q: Optimize the creation of sub arrays based on string prefix In my last question, was created a way to divide a array based in the string pattern Father_son, but now i need a way to split too a new pattern: Father_N_son
Original (generated by http://ideone.com/pmHHR code) :
array
  'Pagamento' =>
    array
      'data' => string '' (length=0)
      '0_pessoaId' => string '85' (length=2)
      '0_valorBruto' => string '890.00' (length=6)
      '1_pessoaId' => string '83' (length=2)
      '1_valorBruto' => string '20.00' (length=5)

Now i need:
array
  'Pagamento' =>
    array
      'data' => string '' (length=0)
      0 =>
        array
          'pessoaId' => string '85' (length=2)
          'valorBruto' => string '890.00' (length=6)
      1 =>
        array
          'pessoaId' => string '83' (length=2)
          'valorBruto' => string '20.00' (length=5)

Thanks,
Celso

A: my solution with regex:
static function parserRequest($array = null) {

        if (empty($array)) {
            $array = $_REQUEST;
        }

        foreach ($array as $k => $v) {

            $name = explode('_', $k);
            $newkey = array_shift($name);
            $newname = implode('_', $name);

            //para o padrão Entidade.n.atributo
            if(preg_match("/[0-9]_[a-z]/", strtolower($newname))){

                $nameValued    = explode('_',$newname);
                $newkeyValued  = array_shift($name);
                $newnameValue  = implode('_', $name);

                $result[$newkey][$newkeyValued][$newnameValue] = $v;

            }else{

                //para o padrão Entidade.atributo
                $result[$newkey][$newname] = $v;

            }

        }

        return $result;
    }


text:
Q: Getting out of While(hasNextInt()) Hi I have a problem getting out of the loop. My input (it can input any number of integer) supposed to be
Add 10 5 //input then after I press enter it supposed to show the output
Items added: [5, 10] //output

But instead I get
Add 10 5 //enter
Add 2 //I need to enter another input to get the output
Items added: [5, 10] //output

Here is my code. I think the problem is after the while loop I need to remove the remainder of the input line but I don't know how to fix it. Please help, thank you
public static void main(String [] args) throws NoSuchElementException {

      StackLL <Integer> stack = new StackLL <Integer> ();
      Scanner sc = new Scanner(System.in);
      String op;

      while (sc.hasNext()) {
          op = sc.next();

          if (op.equals("Add")) {
              // Fill in the code
              while (sc.hasNextInt()){
                  stack.push(sc.nextInt());
              }
              System.out.print("Items added: ");
              System.out.print(stack.toString() + "\n");
          }

          else if (op.equals("Query")) {
              // Fill in the code
              while (sc.hasNextInt()) {
                  int query = sc.nextInt();
                  int pop = query - 1;
                  while (query!=pop)
                      pop = stack.pop();
              }
              sc.nextLine();
              System.out.println("Query met: " + stack.toString());
          }
      }
  }

A: From http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.

A: replace
   while (sc.hasNextInt()){
     stack.push(sc.nextInt());
   }

with
stack.push(sc.nextInt());
stack.push(sc.nextInt());

also you don't need  sc.nextLine(); at end
see hasNext() - when does it block and why?


text:
Q: r-value references and normal variables I am reading the following tutorial: Learn Cpp and there they put an example of use of a r-value reference.
#include <iostream>

class Fraction
{
private:
    int m_numerator;
    int m_denominator;

public:
    Fraction(int numerator = 0, int denominator = 1) :
        m_numerator{ numerator }, m_denominator{ denominator }
    {
    }

    friend std::ostream& operator<<(std::ostream& out, const Fraction &f1)
    {
        out << f1.m_numerator << '/' << f1.m_denominator;
        return out;
    }
};

int main()
{
    auto &&rref{ Fraction{ 3, 5 } }; // r-value reference to temporary Fraction

//    auto notref=Fraction(4,8);
    auto notref{Fraction(4,8)};  //<---MY adding
    // f1 of operator<< binds to the temporary, no copies are created.
    std::cout << rref << '\n';
    std::cout<< notref<<"\n";  //<-- MY adding

    return 0;
} // rref (and the temporary Fraction) goes out of scope here

The parts mark "MY adding" are parts added by me for this question.
and they write

As an anonymous object, Fraction(3, 5) would normally go out of scope
  at the end of the expression in which it is defined. However, since
  we're initializing an r-value reference with it, its duration is
  extended until the end of the block. We can then use that r-value
  reference to print the Fraction's value.

However as you can see I have added a normal variable for comparison and it does exactly the same. The Fraction does not go out of scope and it can be normally used in the printing part.
What is the difference and why would someone use the r-value reference?

A: In this example, rref only goes out of scope after return 0. It has the same lifetime as notref. So there is no difference.


text:
Q: Stop SonataAdmin / Symfony2 from creating empty objects with sonata_type_admin embedded admins First of all, I'm not sure if this is a Sonata issue or a Symfony2 one, this is the first time I'm working with Sf2 forms to edit a relationship.
Here's the problem:
I have two classes, let's call them the old favourites: Car and Wheel. Car has an optional one-to-one relationship with Wheel (it's for the example, just go with it...). I have set up SonataAdmin with a CarAdmin class which embeds a WheelAdmin using sonata_type_admin and try to create a Car without entering any data for Wheel.
However, on submit (somewhere in $form->bind()/$form->submit() as far as I can trace) Symfony and/or Sonata is instantiating a Wheel and trying to persist it (with all its values as null). Since the Wheel has some non-null constraints this throws a DBALException complaining that you cannot INSERT a Wheel with null vlaues.
This is naughty and I'd like to stop it happening. If I don't enter any details for Wheel I don't want a phantom Wheel menacing my code and database. What I expect is that if I enter no data there is nothing to insert/persist so it's left alone. But this is not what's happening... any ideas how to tame this into something sensible?

Here's the long version, with code blocks and everything:
The ORM definitions first:
# MyNS\MyBundle\Resources\Config\Doctrine\Car.orm.yml
MyNS\MyBundle\Entity\Car:
  type: entity
  repositoryClass: MyNS\MyBundle\Entity\Repositories\CarRepository
  table: test_cars
  id:
    id:
      type:                     integer
      generator:                { strategy: AUTO }
  fields:
    color:
      type:                     string
      length:                   50
    owner:
      type:                     string
      length:                   50
      nullable:                 true
  oneToOne:
    leftFrontWheel:
      targetEntity:             Wheel
      cascade:                  [ persist ]
      joinColumn:
        name:                   leftFrontWheelId
        referencedColumnName:   id

# MyNS\MyBundle\Resources\Config\Doctrine\Wheel.orm.yml
MyNS\MyBundle\Entity\Wheel:
  type: entity
  repositoryClass: MyNS\MyBundle\Entity\Repositories\WheelRepository
  table: test_wheels
  id:
    id:
      type:                     integer
      generator:                { strategy: AUTO }
  fields:
    diameter:
      type:                     integer
      length:                   5

Then the SonataAdmin classes:
namespace MyNS\MyBundle\Admin

use ...

class CarAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('color',              null, array('required' => true))
            ->add('owner',              null, array('required' => false))
            ->add('leftFrontWheel',     'sonata_type_admin', array('delete' => false))
        ;
    }

    protected function configureListFields(ListMapper $listMapper) { ... }
}

and
namespace MyNS\MyBundle\Admin;

use ...

class WheelAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('diameter',   null,   array('required' => false))
        ;
    }

    protected function configureListFields(ListMapper $listMapper) { ... }
}

and finally the admin.yml entries:
services:
    sonata.admin.car:
        class: MyNS\MyBundle\Admin\CarAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, label: "Car" }
        arguments:
            - ~
            - MyNS\MyBundle\Entity\Car
            - 'SonataAdminBundle:CRUD'
        calls:
            - [ setTranslationDomain, [MyNS\MyBundle]]
    sonata.admin.wheel:
        class: MyNS\MyBundle\Admin\WheelAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, label: "Wheel" }
        arguments:
            - ~
            - MyNS\MyBundle\Entity\Wheel
            - 'SonataAdminBundle:CRUD'
        calls:
            - [ setTranslationDomain, [MyNS\MyBundle]]

Expected/required behaviour:

*

*Display a form with three fields:

*

*car.color (required)

*car.owner (optional)

*car.wheel.diameter (optional)

*if car.wheel.diameter is left blank then no Wheel should be created and test_cars.leftFrontWheelId should remain null in the database

*if car.wheel.diameter is entered then a Wheel should be created and linked to the Car (this seems to work fine with the existing config)
The question: How do I get this system to behave as above?

A: It might be caused by a missing 'required' => false, no ?
protected function configureFormFields(FormMapper $formMapper) {
    $formMapper
        ->add('color',              null, array('required' => true))
        ->add('owner',              null, array('required' => false))
        ->add('leftFrontWheel',     'sonata_type_admin', array('required' => false, 'delete' => false))
    ;
}

A: Change your Wheel form field for something like :
$formMapper
    // ...
    ->add('leftFrontWheel', 'sonata_type_admin', array(
        'delete' => false,
        'by_reference => true,
        'required' => false,
    ))
    // ...

See by_reference documentation
If it's not sufficient, use a prePersist hook in your parent admin class and manage which field you store. i.e. :
// Fire on submit, before the object persisting
public function prePersist($object)
    if ($wheel = $object->getLeftFrontWheel()) {
        if (!$wheel->getYourNonNullableField()) {
            $object->setLefTFrontWheel(null);
        }
    }
}


text:
Q: Using selfwritten .sh file in another .sh file I am writing a small .sh program in bash.
The problem is extremely simple, i.e, to dind the primefactors of a number.
What I've done is written a .sh file to check if a number is prime or not.
Here is the code for that :
if [ $# -ne 1 ]; then
    exit
fi
number=$1
half=$(($number / 2))
for (( i=2;i<$half;i++ ))
do
    rem=$(($number % $i))
    if [ $rem -eq 0 ]; then
        echo "0"
        exit
    fi
done
echo "1"

And the second .sh file to generate prime factors :
clear

echo "Enter number : "
read number
half=$(($number / 2))
for(( i=1;i<=$half;i++ ))
do
    rem=$(($number % $i))
    if [ $rem -eq 0 ]; then
        ok=`prime.sh $rem`
        if [ "$ok" == "1" ]; then
            echi $i
        fi
    fi
done

This line ,
ok=`prime.sh $rem`

gives the following error :
primefactor.sh: line 10: prime.sh: command not found

So, is it not possible to divide a program into smaller modules and use it in the other modules like other programming languages ?
Some help on how to achieve this will be helpful.

A: primefactor.sh: line 10: prime.sh: command not found

...means that prime.sh is not in your PATH, or is not executable. There are a few ways you can remedy this:

*

*First, ensure that the +x bit is set:

chmod +x prime.sh

*...then, add it to your PATH:

PATH=.:$PWD

*...or invoke it directly:

ok=$(./prime.sh)

By the way, names ending in .sh are appropriate for POSIX sh libraries, not bash scripts (which typically aren't valid POSIX sh scripts anyhow). You don't run ls.elf; you should run prime, not prime.sh, for the same reasons.

That said, if your goal is just to split your code amongst multiple files, a library might be the right thing. Using subshells (which fork an existing shell instance) is much more efficient than spawning subprocesses (which involve both a fork and an exec).
For instance, you could write prime.bash:
check() {
  local number half i rem
  number=$1
  half=$((number / 2))
  for (( i=2; i<half; i++ )); do
    rem=$((number % i))
    if (( rem == 0 )); then
      echo "0"
      return
    fi
  done
  echo "1"
}

...and then, in your primefactor script, read in that library and use the function it defined:
source prime.bash # read in the library
clear

echo "Enter number : "
read number
half=$((number / 2))
for(( i=1;i<=half;i++ ))
do
    rem=$((number % i))
    if (( rem == 0 )); then
        ok=$(check "$rem")
        if [[ $ok = 1 ]]; then
            echo "$i"
        fi
    fi
done

A: Call your script like this:
ok=`./prime.sh $rem`


text:
Q: How do I figure out what fields to mark as transient when tryhing to use Gson's toJson method? I'm using Gson 2.8.1.  I have this code
        Object o = session.getSecurityContext();
        Gson gson = new Gson();
        String serialized = gson.toJson(o);

It results in this stack overflow error.
15:45:47,784 ERROR [io.undertow.request] (default task-58) UT005023: Exception handling request to /ebook/WEB-INF/views/registration/studentConfirm.jsp: java.lang.StackOverflowError
    at sun.util.locale.provider.DateFormatSymbolsProviderImpl.getInstance(DateFormatSymbolsProviderImpl.java:85)
    at java.text.DateFormatSymbols.getProviderInstance(DateFormatSymbols.java:359)
    at java.text.DateFormatSymbols.getInstance(DateFormatSymbols.java:335)
    at java.util.Calendar.getDisplayName(Calendar.java:2110)
    at java.text.SimpleDateFormat.subFormat(SimpleDateFormat.java:1125)
    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:966)
    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:936)
    at java.text.DateFormat.format(DateFormat.java:345)
    at com.google.gson.internal.bind.DateTypeAdapter.write(DateTypeAdapter.java:83)
    at com.google.gson.internal.bind.DateTypeAdapter.write(DateTypeAdapter.java:41)
    at com.google.gson.internal.bind.TypeAdapters$26$1.write(TypeAdapters.java:586)
    at com.google.gson.internal.bind.TypeAdapters$26$1.write(TypeAdapters.java:579)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:125)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:243)
    at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:976)

Per other answers, if I mark the circular reference that is causing this as "transient," this will supposedly go away, but how do I figure that out programmatically?  I have looked at the object in question and it is not obvious to me through code checking what the circular reference is.

A: Based on the GSON User Guide (https://sites.google.com/site/gson/gson-user-guide), you mark a field as transient when it shouldn't be serialized.
Ideally, you would know beforehand which references are circular, and simply avoid serializing them. On the other hand, you might not know this information, so having some way of constructing a complex object from less complex parts is sometimes beneficial.
For example, if I am trying to serialize a complicated Date object, it might be better to simply add a constructor like the following:
public Date(double ms) {
  // create new Date from milliseconds from the epoch
}

then, where you would serialize a Date object, convert it to milliseconds and serialize the double instead. You can use type interceptors to perform this kind of conditional serialization based on type.
Serialization has been a problem since the dawn of the Java language. You can't simply stick any object into a serialization mechanism and expect that it's magically going to work, unfortunately. That said, many objects will work with GSON, provided you break them down a bit.
When all else fails, trial and error (like you've just seen) works, too. When I was working with GSON serialization/deserialization and I encountered an object I hadn't serialized before, I would first write a unit test for it, to make sure that serialization and deserialization works the way I expect, before putting it in production code.


text:
Q: GPUReport shows no data with Metal in a UIView I am creating a metal app where the primary renderer is a custom UIView that has a CAMetalLayer as a sublayer of it. This works just fine for rendering but nothing is showing up in the FPS debugger and I would really like to have that information.
This debugger I speak of is found by going to the monitors section of the left panel and it is at the bottom below the CPU monitor etc.
I am using a CADisplayLink to trigger my rendering updates and I suppose I could work in something there but it would sure be nice to get back to the easy to access GPU and CPU ms times and usage.
Is there anyway to attach my UIView so that this debugger appears?


text:
Q: Makefile não funciona em MINGW64. Alguém pode me ajudar? Estou programando em python em Django com o Sublime Text 3, usando o Git Bash MINGW64.
Criei o makefile mas quando executo recebo "bash: make: command not found"

A: O bash não está encontrando o make, ele pode não estar instalado ou pode não estar no seu path.
Certifique-se que ele está instalado, e caso esteja crie uma variável de ambiente e adicione-a ao path do sistema.


text:
Q: Redirect non-members to about/intro page I´m making a small wordpress/buddypress community site where I want all content except an about page to be for members only.
I need to do a redirect to the about-page for all non-logged in users. When users log in (from the sidebar) they should end up on the blog/frontpage.
How can I achive this? I tried some different members-plugins for buddypress and wordpress but none of them did exactly what I wanted, or didn´t work with other important plugins (like WP-FB-autoconnect).
I´m guessing this is pretty easy to do with custom code in the header or functions file. But I´m not really a coder so I would like som help!

A: Open your theme's headr.php file and add at the top
<?php
if( !is_user_logged_in() ) {
    wp_redirect(get_permalink(123));
    exit;
}
?>

just change 123 to the id of your about page, or replace get_permalink(123) with the about page URL example:
<?php
if( !is_user_logged_in() ) {
    wp_redirect('http://mydomain.com/about');
    exit;
}
?>


text:
Q: Two-way binding faulty when used with a popup directive i am trying angularjs modal popup directive. in that popup i have used tabs and panes directive. i
have a two
textbox(both having same ng-model=myName), one in my main page and one in my popup. if i change the
value in main page it is getting updated in popup textbox, but when i change the popup textbox the main page textbox is not getting updated. how to fix it.
// html page
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>modal popup</title>

<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/style.css">

 <input type="text" ng-model="myName" />
<button ng-click="primaryAction()">click to load default text</button>

<button modal-open="myModal"> click me</button>

<popup modal-id="myModal" modal-type="tabs" show-header="false" header-title="Modal Header">

<tabs>
<pane title="first">
    <input type="text" name="myName" ng-model="myName">
        <button class="btn btn-primary" ng-click="primaryAction()">save</button>
</pane>
<pane title="second">

content2

</pane>
<pane title="Third">

content3

</pane>

</tabs>

i have posted my code in my fiddle. fiddle here

A: That's because there are two different scopes where one is the parent of the other. When no myName property exists on the child scope, the child scope gets myName from the parent scope. That is, when you change the value in the outer input (which is connected to the parent scope), the input inside the tabs directive gets updated. But when you edit the value of the input field inside the tabs, the value gets written to the new myName property on the child scope, and myName is no longer connected between the parent and child scope.
If you want to share ng-models like that, make sure that your model contains a dot. Something like myModel.myName instead of just myName. That will cause JavaScript to first look for myModel on the child scope, but since the child scope doesn't have a myModel, it looks for it in the parent scope and sets myName on that object.
Here's a working example: http://jsfiddle.net/Zd7ax/30/


text:
Q: Flutter Local routes issue I have a small problem with a flutter local app. I am trying to have 2 routes depending on device  languageCode. When I build the app, that second option are launched. If I save the app, the right route are picked. I think the
final lang = locale.languageCode;

Do not have a value when this is called:
"/newsfeed": lang == "da"
              ? (BuildContext context) => News()
              : (BuildContext context) => NewsEN(),

The print statement I have in the code have the right value, so are a bit lost Here are the code:
class MyApp3 extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        // List all of the app's supported locales here
        supportedLocales: [
          Locale('en', 'US'),
          Locale('da', 'DK'),
        ],
        // These delegates make sure that the localization data for the proper language is loaded
        localizationsDelegates: [
          // A class which loads the translations from JSON files
          AppLocalizations.delegate,
          // Built-in localization of basic text for Material widgets
          GlobalMaterialLocalizations.delegate,
          // Built-in localization for text direction LTR/RTL
          GlobalWidgetsLocalizations.delegate,
        ],
        // Returns a locale which will be used by the app
        localeResolutionCallback: (locale, supportedLocales) {
          // Check if the current device locale is supported
          for (var supportedLocale in supportedLocales) {
            //print(locale.languageCode);

            final lang = locale.languageCode;
            print(lang);
            if (supportedLocale.languageCode == locale.languageCode &&
                supportedLocale.countryCode == locale.countryCode) {

              return supportedLocale;
            }
          }
          // If the locale of the device is not supported, use the first one
          // from the list (English, in this case).
          return supportedLocales.first;
        },
        home: MyHomePage(),
        routes: <String, WidgetBuilder> {
          //"/Knowledge_pick": (BuildContext context) => SplashScreen(),
          "/calculator_pick": (BuildContext context) => Pickcalculator(),
          //"/receipe_pick": (BuildContext context) => Receipemenu(),
            "/receipe_pick": (BuildContext context) => Wrapper(),
          "/newsfeed": lang == "da"
              ? (BuildContext context) => News()
              : (BuildContext context) => NewsEN(),

Hope someone can help me with this problem.

A: Honestly I don't see why this wouldn't work but what you should try to do is setup two different routes, one from 'da' and one for 'en'
"/newsfeedDA": (BuildContext context) => News(),
"/newsfeedEN": (BuildContext context) => NewsEN(),

and have your logic for selecting them in the initState or constructor of MyHomePage().


text:
Q: stop dispatch_time_t when a button is clicked i am implementing a simple dispatch timer to execute a few lines of code after two minutes of invocation of the timer. the code is as follows,
dispatch_time_t poptime = dispatch_time (DISPATCH_TIME_NOW, delayInSeconds *NSEC_PER_SEC);
dispatch_after(poptime,dispatch_get_main_queue(), ^(void){

              //some code here
});

what i am looking for is to either kill or stop or modify the timer to infinity when a button is clicked. i have the button click function and this dispatch timer is written in viewdidload function of class.
Is this possible? please help
thanks.

A: Once a GCD block has been dispatched, you can't cancel it. You should use something like NSTimer instead.

A: AFAIK I know you can't do it with GCD.
Use: NSOperationQueue instead and use cancelAllOperations for cancelling the operations.


text:
Q: set selected value in Select2 dropdown I want to set the selected value of Select2 dropdown. I am displaying two types of address which contains Address and invoice address. Each will have the following fields:

*

*Address 1 - textbox

*Address 2 - textbox

*Town - textbox

*country - dropdown

Invoice address also has these same fields. Also, I am displaying one checkbox, if it is clicked, we should copy the address fields values to invoice address fields.
I can able to copy the textbox values and set to another textboxes. But I'm unable to copy the dropdown values and set to another dropdown. I used the following code:
$('#invoiceAddress').on('ifChecked', function (event) {
    $('input[data-cg-address]').each(function (index, element) {
        var fieldname = $(this).data('cg-address');
        var fieldvalue = $(this).val();
        $('#invoice-address').find('input[data-invoice-address="' + fieldname +   '"]').val(fieldvalue);
    });

    $('select[data-cg-address]').each(function (index, element) {
        var fieldname = $(this).data('cg-address');
        var selectedValue = $(this).val();
        $('#invoice-address').find('select[data-invoice-address="' + fieldname + '"]').val(selectedValue);
    });
});

This code was working if it is normal dropdown. It is not working on a Select2 dropdown.
I used this code on few more pages. So I can;t use the id of those dropdowns.
I need to write common code. below are the form fields.

 Address Details

                                                    @Html.DisplayNameFor(x => x.CompanyGroupAddress.Address1)
                                                    @Html.TextBoxFor(x => x.CompanyGroupAddress.Address1, new { @class = "form-control", data_cg_address = "address1" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupAddress.Address1)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupAddress.Address2)
                                                    @Html.TextBoxFor(x => x.CompanyGroupAddress.Address2, new { @class = "form-control", data_cg_address = "address2" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupAddress.Address2)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupAddress.Town)
                                                    @Html.TextBoxFor(x => x.CompanyGroupAddress.Town, new { @class = "form-control", data_cg_address = "town" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupAddress.Town)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupAddress.Address4)
                                                    @Html.TextBoxFor(x => x.CompanyGroupAddress.Address4, new { @class = "form-control", data_cg_address = "address4" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupAddress.Address4)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupAddress.Postcode)
                                                    @Html.TextBoxFor(x => x.CompanyGroupAddress.Postcode, new { @class = "form-control", data_cg_address = "postcode" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupAddress.Postcode)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupAddress.CountyId)
                                                    @Html.DropDownListFor(x => x.CompanyGroupAddress.CountyId, new SelectList(Model.Counties, "Key", "Value"), "Select Company County", new { @class = "form-control", data_cg_address = "countyid" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupAddress.CountyId)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupAddress.CountryId)
                                                    @Html.DropDownListFor(x => x.CompanyGroupAddress.CountryId, new SelectList(Model.Countries, "Key", "Value"), "Select Company Country", new { @class = "form-control", data_cg_address = "countryid" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupAddress.CountryId)

Invoice Address Details

                                                        @Html.CheckBoxFor(x => x.InvoiceAddress, new { @id = "invoiceAddress", @for = "invoiceAddress", @class = "m-t-10" })
                                                        Same as Company Address

                                                    @Html.DisplayNameFor(x => x.CompanyGroupInvoiceAddress.Address1)
                                                    @Html.TextBoxFor(x => x.CompanyGroupInvoiceAddress.Address1, new { @class = "form-control", data_invoice_address = "address1" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupInvoiceAddress.Address1)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupInvoiceAddress.Address2)
                                                    @Html.TextBoxFor(x => x.CompanyGroupInvoiceAddress.Address2, new { @class = "form-control", data_invoice_address = "address2" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupInvoiceAddress.Address2)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupInvoiceAddress.Town)
                                                    @Html.TextBoxFor(x => x.CompanyGroupInvoiceAddress.Town, new { @class = "form-control", data_invoice_address = "town" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupInvoiceAddress.Town)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupInvoiceAddress.Address4)
                                                    @Html.TextBoxFor(x => x.CompanyGroupInvoiceAddress.Address4, new { @class = "form-control", data_invoice_address = "address4" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupInvoiceAddress.Address4)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupInvoiceAddress.Postcode)
                                                    @Html.TextBoxFor(x => x.CompanyGroupInvoiceAddress.Postcode, new { @class = "form-control", data_invoice_address = "postcode" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupInvoiceAddress.Postcode)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupInvoiceAddress.CountyId)
                                                    @Html.DropDownListFor(x => x.CompanyGroupInvoiceAddress.CountyId, new SelectList(Model.Counties, "Key", "Value"), "Select Company County", new { @class = "form-control", data_invoice_address = "countyid" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupInvoiceAddress.CountyId)

                                                    @Html.DisplayNameFor(x => x.CompanyGroupInvoiceAddress.CountryId)
                                                    @Html.DropDownListFor(x => x.CompanyGroupInvoiceAddress.CountryId, new SelectList(Model.Countries, "Key", "Value"), "Select Company Country", new { @class = "form-control", data_invoice_address = "countryid" })

                                                        @Html.ValidationMessageFor(x => x.CompanyGroupInvoiceAddress.CountryId)

Thanks in advance

A: try this:
$('#checkbox').click(function(){
    var dropdown1 = $('#dropdown1').val();

    $('#dropdown2').val(dropdown1);
});

A:

 $("#chkbox").click(function () {
         var options = $('#ddl1 option').clone();
        $('#ddl2').append(options);
        });

<input type="checkbox" id="chkbox" />
<select id="ddl1">
<option value="1">One</option>
<option value="2">Two</option>
</select>

<select id="ddl2">

A: I just added the code in trigger('change') in dropdownlist set value as below.
 $('#invoice-address').find('select[data-invoice-address="' + fieldname + '"]').val(selectedValue).trigger("change");

Now it is working fine.


text:
Q: Entity Framework MetadataWorkspace error Using a Code-First approach with Entity Framework 5 for a Silverlight to WCF RIA Services project. During solution build, I receive the following error and warning:
Warning
No persistent classes found. Is the metadata information missing?
Error
Failed to get the MetadataWorkspace for the DbContext type
I'm running off a local Database, and placed the custom connection string information in the constructor for the DbContext.


text:
Q: boost::program_options custom validate and default value I am using boost::program_options to parse arguments. Because I cannot break compatibility I need to allow specifying some arguments multiple times. I need to do it for example for strings (last one wins) or for booleans (every occurence switches the value).
Let's show what I have on bool (for strings it should be easier because it does not matter what the default is when parameter is used, because it is overwritten with new value). I have my own class BoolValue and custom validate function which switches the value with every occurence. So if you have variable with value false and call program like this
./program -t -t -t

it switches it to true, false, and true again.
I can achieve it with following code and it works ok if default value is false. But sometimes I need the default value to be true (so the example above would switch it to false, true and finally false again).
I can make two classes like TrueValue and FalseValue of course but it does not look nicely. So - can I somehow read the specified default_value inside validate function for initial assignement when still empty?
// my custom class
class BoolOption {
public:
    BoolOption(bool initialState = false) : state(initialState) {}
    bool getState() const {return state;}
    void switchState() {state = !state;}
private:
    bool state;
};

// two test variables
BoolOption test1;
BoolOption test2;

// validate
void validate(boost::any &v, std::vector<std::string> const &xs, BoolOption*, long)
{
    if (v.empty()) {
        v = BoolOption(true); // here is the problem
        // it works when default false only (of course)
        // I don't know how to read the default_value here
    } else {
        boost::any_cast<BoolOption&>(v).switchState();
    }
}

optionsDescription->add_options()
        ("test1,t", po::value<BoolOption>(&test1)->default_value(BoolOption(true), "true")->zero_tokens(), "")
        ("test2,T", po::value<BoolOption>(&test2)->default_value(BoolOption(false), "false")->zero_tokens(), "")
;

// output result
cout << test1.getState() << endl;
cout << test2.getState() << endl;

As stated above very awkward solution would be to have two classes for that purpose, can be done also with template, something like
template <bool B> class SwitchOption {
public:
    SwitchOption() : value(B) {}
    bool getValue() const {return value;}
    void setValue(bool value) {this->value = value;}
    void switchState() {value = !value;}
    string toStr() {return value ? "true" : "false";}
private:
    bool value;
};

// so validate as
template <bool B> void validate(boost::any &v, vector<string> const &xs __unused, SwitchOption<B>*, long)
{
    if (v.empty()) {
        v = SwitchOption<B>();
    }
    boost::any_cast<SwitchOption<B>&>(v).switchState();
}

// and add_options like this:
("switch,s", boost::program_options::value<SwitchOption<true> >(&variableName)->default_value(SwitchOption<true>(), "true")->zero_tokens(), "")
// can be done with macro, but still I have to specify "true" here in add_options and also when defying the variable itself as
// SwitchOption<true> variableName;
// which is bad duplication

Lost in too complicated solutions :-)

A: Used as in original without default value (always false) and switched after options parsing done for those variables where default should be true.


text:
Q: Fixed effects regression with a loop is not workling I do following fixed effects regression with a loop. I always get an error "option if is not allowed"!
levelsof Sic, local(Sic)

xtset Year
foreach i of local Sic {

 xtreg y mq r d, fe if Sic == `i'
    eststo
}

if i do the same regression with a normal OLS regression, its working without any problems. why?

A: The if qualifier should come before the comma, options afterwards.
levelsof Sic, local(Sic)

foreach i of local Sic {
    eststo: xtreg y mq r d  if Sic == `i', fe
}

I assume it worked with OLS because you did not have to specify any options.


text:
Q: ActionController::ParameterMissing in CotizacionsController#create param is missing or the value is empty: cotizacion El contexto de la pregunta es el siguiente:

*

*Generé la entidad Cotizacions, a través de scaffold. Se creó la vista, modelo y controlador correspondiente: cotizacions_controller.rb, cotizacion.rb y vistas (_cotizacion.json.jbuilder, _form.html.erb, edit.html.erb, index.html.erb, new.html.erb).

*Se instala template, creative de Bootstrap. Se crea controlador y vistas correspondientes: creatives_controller.rb y vistas (index.html.erb, _header.html.erb, etc.).
Lo primero que se realizó fue ocupar el formulario generado en la vista de cotizacions _form.html.erb. Desde la vista se creatives archivo _header.html.erb, utilizando el siguiente codigo:

Negocia tu Auto

Somos una empresa especialista......

      <%= render :partial =>'cotizacions/form' , locals: { cotizacion:@cotizacion } %>

El problema es que al gatillar el evento desde la vista cotizacions, recibo el siguiente mensaje:

ActionController::ParameterMissing in CotizacionsController#create
  param is missing or the value is empty: cotizacion

El controlador de cotizacions es el siguiente:
class CotizacionsController < ApplicationController
  before_action :set_cotizacion, only: [:show, :edit, :update, :destroy]

  def index
    @cotizacions = Cotizacion.all
  end

  def show
  end

  def new
    @cotizacion = Cotizacion.new
  end

  def edit
  end

  def create
    @cotizacion = Cotizacion.new(cotizacion_params)

    respond_to do |format|
      if @cotizacion.save
        format.html { redirect_to @cotizacion, notice: 'Cotizacion was successfully created.' }
        format.json { render :show, status: :created, location: @cotizacion }
      else
        format.html { render :new }
        format.json { render json: @cotizacion.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @cotizacion.update(cotizacion_params)
        format.html { redirect_to @cotizacion, notice: 'Cotizacion was successfully updated.' }
        format.json { render :show, status: :ok, location: @cotizacion }
      else
        format.html { render :edit }
        format.json { render json: @cotizacion.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @cotizacion.destroy

    respond_to do |format|
      format.html { redirect_to cotizacions_url, notice: 'Cotizacion was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
  def set_cotizacion
    @cotizacion = Cotizacion.find(params[:id])
  end

  def cotizacion_params
    params.require(:cotizacion).permit(
      :patente, :marca, :modelo, :kilometraje, :correo, :telefono, :comentarios,
      :abs, :aire_acondicionado, :airbag, :cant, :velocidad_crucero, :aux, :aux1
    )
  end
end

He intentado corregir el problema agregando el siguiente código el controlador de creatives;
class CreativesController < ApplicationController
  layout "creative"
  match "/cotizacions" => "cotizacions#create", :via => [:post]
end

Pero ahora recibo el siguiente error:

undefined method `match' for CreativesController:Class Did you mean?
  catch

_form.html.erb:
<%= form_with(model: cotizacion) do |form| %>

          <%= form.text_field :patente,
                              placeholder: "Patente",
                              id: :car_patente,
                              class: "form-control" %>

          <%= form.select :marca,
                          options_for_select([["SUBARU", "t"], ["KIA", "s"]], id: :car_marca),
                          prompt: "Marca",
                          class: "combobox form-control",
                          name: "inline"%>

          <%= form.text_field :modelo,
                              id: :car_modelo,
                              placeholder: "Modelo Ej: Yaris, i10",
                              class: "form-control" %>

          <%= form.select :kilometraje,
                          options_for_select([["0 - 10.0000", "t"], ["10.0001 - 20.0000", "s"]], id: :car_kilometraje),
                          prompt: "Kilometraje",
                          class: "combobox form-control",
                          name: "inline" %>

          <%= form.email_field :correo,
                               id: :car_correo,
                               placeholder: "ejemplo@mail.com",
                               class: "form-control" %>

          <%= form.telephone_field :telefono,
                                   id: :car_telefono,
                                   placeholder: "Télefono",
                                   class: "form-control" %>

Seleccione Equipamiento

              <%= form.check_box :abs, id: :car_abs %>

            <input type="text" class="form-control" aria-label="...", placeholder="ABS">

              <%= form.check_box :aire_acondicionado, id: :car_aire_acondicionado %>

            <input type="text" class="form-control" aria-label="...", placeholder="Aire Acondicionado">

              <%= form.check_box :airbag, id: :car_airbag %>

            <input type="text" class="form-control" aria-label="...", placeholder="Airbag">

              <%= form.check_box :velocidad_crucero, id: :car_velocidad_crucero %>

            <input type="text" class="form-control" aria-label="...", placeholder="Velocidad Crucero">

          <%= form.submit  class: 'btn btn-success btn-lg', value: 'Tasar su Vehículo' %>

<% end %>

routes.rb:
Rails.application.routes.draw do
  get 'creatives/index'
  resources :cotizacions
  post 'creatives/index', to: 'cotizacions#create
end

log:
ActionController::ParameterMissing (param is missing or the value is empty: cotizacion):

app/controllers/cotizacions_controller.rb:74:in `cotizacion_params'
app/controllers/cotizacions_controller.rb:29:in `create'
Started POST "/creatives/index" for 127.0.0.1 at 2017-07-29 15:01:27 -0400
Processing by CotizacionsController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"vu6ARii6s6IjRMeN7TWM1vmh/KKNja5l37EFnlfN7B0YtwvVq/bzIb9qbYTRuJDh8FwuZCgu1u2dvD4B0BPlog==", "patente"=>"", "marca"=>"", "modelo"=>"", "kilometraje"=>"", "correo"=>"", "telefono"=>"", "abs"=>"0", "aire_acondicionado"=>"0", "airbag"=>"0", "velocidad_crucero"=>"0", "commit"=>"Tasar su Vehículo"}
Completed 400 Bad Request in 1ms

ActionController::ParameterMissing (param is missing or the value is empty: cotizacion):

app/controllers/cotizacions_controller.rb:74:in `cotizacion_params'
app/controllers/cotizacions_controller.rb:29:in `create'
Started POST "/creatives/index" for 127.0.0.1 at 2017-07-29 15:01:28 -0400
Processing by CotizacionsController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"vu6ARii6s6IjRMeN7TWM1vmh/KKNja5l37EFnlfN7B0YtwvVq/bzIb9qbYTRuJDh8FwuZCgu1u2dvD4B0BPlog==", "patente"=>"", "marca"=>"", "modelo"=>"", "kilometraje"=>"", "correo"=>"", "telefono"=>"", "abs"=>"0", "aire_acondicionado"=>"0", "airbag"=>"0", "velocidad_crucero"=>"0", "commit"=>"Tasar su Vehículo"}
Completed 400 Bad Request in 1ms

A: Al parecer estás generando la forma en index (i.e. index.html.erb) en lugar de hacerlo en new (i.e. new.html.erb), lo que ocasiona que @cotizacion sea nil; como resultado form_with no reconoce el modelo y, por ende, no agrupa correctamente.
Puedes solucionarlo de varias formas, pero la más sencilla (en mi opinion) es agregar el atributo scope en form_width para especificar que la forma siempre agrupe con cotizacion; por ejemplo:
<%= form_with(model: cotizacion, scope: :cotizacion ) do |form| %>

Ahora, al enviarse la forma, se enviarán los parámetros agrupados en cotizacion; algo similar a:
Parameters: {
  "utf8"=>"✓",
  "authenticity_token"=>"...==",
  "cotizacion"=>{
    "patente"=>"",
    "marca"=>"",
    "modelo"=>"",
    "kilometraje"=>"",
    "correo"=>"",
    "telefono"=>"",
    "abs"=>"0",
    "aire_acondicionado"=>"0",
    "airbag"=>"0",
    "velocidad_crucero"=>"0"
  },
  "commit"=>"Tasar su Vehículo"
}

De esta forma el parámetro cotizacion estará siempre presente y, por lo tanto, el método cotizacion_params ya no arrojará el error.