text:
Q: Id compuesto en migración de Laravel Tengo una tabla con un id compuesto:
CREATE TABLE `profiles` (
  `id` varchar(100) NOT NULL,
  `id_user` int(11) NOT NULL,
  `id_language` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    ALTER TABLE `profiles`
      ADD PRIMARY KEY (`id`),
      ADD UNIQUE KEY `id` (`id_user`,`id_language`),
      ADD KEY `id_language` (`id_language`),
      ADD KEY `id_user` (`id_user`);

ALTER TABLE `profiles`
  ADD CONSTRAINT `profiles_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `users` (`id`),
  ADD CONSTRAINT `profiles_ibfk_2` FOREIGN KEY (`id_language`) REFERENCES `languages` (`id`);

INSERT INTO `profiles` (`id`, `id_user`, `id_language`) VALUES
('1-co', 1, 'co');

pero no se como hacer lo mismo en laravel
voy aqui:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProfilesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->string('id')->unsigned();

            //aqui deberia deicr que id es compuesta por id_user y id_langauge
            $table->integer('id_user')->unsigned();
            $table->foreign('id_user')->references('id')->on('users');
            $table->integer('id_language')->unsigned();
            $table->foreign('id_language')->references('id')->on('languages');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('profiles');
    }
}

Pero no se que mas hacer.

A: Por defecto Eloquent no permite utilizar dos llaves primarias, hay varias formas que han planteado para que funciona, haciendo override de ciertos métodos, pero Eloquent como tal no fue diseñado para trabajar con llaves primarias compuestas.
Puedes ver la discusión en GitHub (desde 2014) en el siguiente enlace: https://github.com/laravel/framework/issues/5355
Si buscas un poco en Google, podrás encontrar algunas soluciones alternativas, incluso creo que hay algunos paquetes para Eloquent.


text:
Q: PDO: defining parameters using foreach and $_POST I'm trying to create a page that allows users change their info in a sql database using PDO. I'm new to this and I'm running into an error. I'm using this as a source: http://forums.devshed.com/php-faqs-stickies-167/program-basic-secure-login-system-using-php-mysql-891201.html
I'm not sure if I included too much code. I'm hoping someone could point out where I made a mistake.
<?php
require("common.php");

Common runs this code:
<?php
$username = "";
$password = "";
$host = "";
$dbname = "";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
    die("Failed to connect to the database: " . $ex->getMessage());
}

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

header('Content-Type: text/html; charset=utf-8');
session_start();

Now I create the initial query and params:
//initial query and params
    $query = "
        UPDATE users
        SET
        ";
    $query_params = array();
    $query_params[':user_id'] = $_SESSION['user']['id'];

Now I want to define the parameters using an array of parameters (the fields)
      $params = array(info1,info2,info3);
      foreach($params as $param):
        if(!empty($_POST[$param])){
          $query_params[':$param'] = $_POST[$param];
          $query .= "$param = :$param,";
        }
      endforeach;

Then I finish the query and run it:
    //trim last comma
    $query = rtrim($query, ',');
    $query .= "
        WHERE
            id = :user_id
    ";

    try
    {
        // Execute the query
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch(PDOException $ex)
    {
        die("Failed to run main query: " . $ex->getMessage() . "\n" . $query );
    }

This is the HTML (with jquery) I used:
<form method="post" action="edit_account.php" data-ajax="false">

Gebruikersnaam: <?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?>

    E-mail:
    <input autocomplete="off" type="text" name="email" id="email" value="<?php echo htmlentities($_SESSION['user']['email'], ENT_QUOTES, 'UTF-8'); ?>">
    Wachtwoord:
    <input autocomplete="off" type="password" name="password" id="password" placeholder="(alleen als je deze wijzigt)">

    info1:
    <input type="text" name="info1" id="info1" placeholder="<?php echo htmlentities($_SESSION['user']['info1'], ENT_QUOTES, 'UTF-8'); ?>">

    info2:
    <textarea type="text" name="info2" id="info2" placeholder="<?php echo htmlentities($_SESSION['user']['info2'], ENT_QUOTES, 'UTF-8'); ?>"></textarea>
    info3:
    <input type="text" name="info3" id="info3" placeholder="<?php echo htmlentities($_SESSION['user']['info3'], ENT_QUOTES, 'UTF-8'); ?>">
    info4:
    <input type="text" name="info4" id="info4" placeholder="<?php echo htmlentities($_SESSION['user']['info4'], ENT_QUOTES, 'UTF-8'); ?>">

</form>

I get this error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined.

A: I have simplified the code to illustrate how to create dynamic UPDATE query. This uses "lazy" binding and regular placeholders ?.
The text inputs are set as a regular array (ie. not associative) of values.
<?php
if(isset($_POST['submit'])){
    if (isset($_POST["info"]) && !empty($_POST["user_id"])) {
        $query = "UPDATE `users` SET ";
        $query_params = array();
        $i =1;
        foreach ($_POST['info'] as $value) {
            // push array with each valid info entry ...
            if ($value) {
                $query .= "`info".$i. "` = ?,";
                array_push($query_params,$value);
            }
            $i++;
        }
        $query = rtrim($query, ',');//remove trailing ,
        //
        $query .= " WHERE `id` = ?";
        array_push($query_params,$_POST['user_id']);
        //Show query and parameter array Remove after testing
        echo $query;
        echo "
";
        print_r($query_params);
        // Execute the query
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
}
?>
<form method="POST" action="#">
<input type="text" name="info[]" id="info" value="">
<input type="text" name="info[]" id="info"  value="">
<input type="text" name="info[]" id="info"  value="">
<input type="text" name="info[]" id="info" value="">
<input type="text" name="user_id" id="user_id" value="">
<input type="submit" name="submit" value="Submit">

Typical result
UPDATE `users` SET `info1` = ?,`info2` = ? WHERE `id` = ?
Array ( [0] => john [1] => smith [2] => johnsmith )

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to debug "Gallery system error, please try again later"? Trying to upload this file: https://github.com/ripper234/explainxkcd/blob/master/releases/0.2.zip to the store, and I keep getting this error:
Gallery system error, please try again later.
Meanwhile, updating another extension worked well for me.
I already posted to the Chromium Apps Google Group. Anything more I can try in the meantime to debug this?

A: I had had the same problem, than I found the solution.
This is all about compressing method.
You should select compressing method as "Store".
I tried on your files, yes It worked, it was uploaded successfully.
Here what I means for Winrar,


text:
Q: SLD parsing fail on GeoServer
I created a custom style on QGis and saved as SLD file. When I added to GeoServer, after validation it, I got an errors about parsing.
Here is the error message below:
Parsing failed for Filter: java.lang.RuntimeException: Unable to find function Literal
line 26: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ogc:Filter'. One of '{"http://www.opengis.net/ogc":expression}' is expected.
line 27: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ogc:Literal'. One of '{"http://www.opengis.net/ogc":spatialOps, "http://www.opengis.net/ogc":comparisonOps, "http://www.opengis.net/ogc":logicOps, "http://www.opengis.net/ogc":_Id}' is expected.

<?xml version="1.0" encoding="UTF-8"?>
<StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd" xmlns:se="http://www.opengis.net/se">
  <NamedLayer>
    <se:Name>Some_Name</se:Name>
    <UserStyle>
      <se:Name>Some_Name</se:Name>
      <se:FeatureTypeStyle>
        <se:Rule>
          <se:Name>Single symbol</se:Name>
          <se:LineSymbolizer>
            <se:Stroke>
              <se:GraphicStroke>
                <se:Graphic>
                  <se:Mark>
                    <se:WellKnownName>line</se:WellKnownName>
                    <se:Fill>
                      <se:SvgParameter name="fill">#ff0000</se:SvgParameter>
                    </se:Fill>
                    <se:Stroke>
                      <se:SvgParameter name="stroke">#ff0000</se:SvgParameter>
                    </se:Stroke>
                  </se:Mark>
                  <se:Size>3</se:Size>
                </se:Graphic>
                <se:Gap>
                  <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
                    <ogc:Literal>1.2</ogc:Literal>
                  </ogc:Filter>
                </se:Gap>
              </se:GraphicStroke>
            </se:Stroke>
          </se:LineSymbolizer>
          <se:LineSymbolizer>
            <se:Stroke>
              <se:SvgParameter name="stroke">#ff0000</se:SvgParameter>
              <se:SvgParameter name="stroke-width">0.26</se:SvgParameter>
              <se:SvgParameter name="stroke-linejoin">bevel</se:SvgParameter>
              <se:SvgParameter name="stroke-linecap">square</se:SvgParameter>
            </se:Stroke>
            <se:PerpendicularOffset>1</se:PerpendicularOffset>
          </se:LineSymbolizer>
          <se:LineSymbolizer>
            <se:Stroke>
              <se:SvgParameter name="stroke">#ff0000</se:SvgParameter>
              <se:SvgParameter name="stroke-width">0.26</se:SvgParameter>
              <se:SvgParameter name="stroke-linejoin">bevel</se:SvgParameter>
              <se:SvgParameter name="stroke-linecap">square</se:SvgParameter>
            </se:Stroke>
            <se:PerpendicularOffset>-0.6</se:PerpendicularOffset>
          </se:LineSymbolizer>
        </se:Rule>
      </se:FeatureTypeStyle>
    </UserStyle>
  </NamedLayer>
</StyledLayerDescriptor>

How can I resolve the parsing issue?

A: if you change the StyleLayerDescriptor to this...it does validate
<StyledLayerDescriptor version="1.0.0"
xsi:schemaLocation="http://www.opengis.net/sld StyledLayerDescriptor.xsd"
xmlns="http://www.opengis.net/sld"
xmlns:ogc="http://www.opengis.net/ogc"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:se="http://www.opengis.net/se">

It might look similar but geoserver is a bit odd when it comes to SLDs

A: QGIS puts the filter tags but leaves out some essential parts that are needed by the validator in geoserver. So here's what you need to do:
in your filter tag add a PropertyIsEqualTo tag and within that add the PropertyName tag and the Literal tag.
So this:
  <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
    <ogc:Literal>1.2</ogc:Literal>
  </ogc:Filter>

Becomes this:
  <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
    <ogc:PropertyIsEqualTo>
      <ogc:PropertyName>FIELDNAME</ogc:PropertyName>
      <ogc:Literal>1.2</ogc:Literal>
    </ogc:PropertyIsEqualTo>
  </ogc:Filter>

Where FIELDNAME is the name of the field on which the filter is based. Then it should validate correctly.

A: The parser is expecting an Expression at line 26 where you have a filter. So try removing the filter and just using the Literal (which is an expression).
I don't know if the GeoServer SLD parser will like it anyway as the Symbology Encoding support is patchy.


text:
Q: Some access 2007 programming questions on forms I am designing a small Access 2007 UI with SQL Server tables.
I have a subform on my page, which is a datasheet. For every parent record selected (say table A, and table B has a foreign key of table A) in the form view, I want to write out every related record in the datasheet.
There are 5 customers. Each has several orders. You can browse through the customers in the form. But for every next button clicked, I want to display all relevant orders in the datasheet (the datasheet will allow me to write new records too).
Also, in the datasheet (imagine it is orders),  can I set the PK ID value to automatically be the same ID as in the customer record currently displayed?
Thanks

A: If I'm reading this correctly, you're saying you have the main parent table as the main part of the form, and you want the child records display in a sub form as you navigate around. Access works this way by default and you'll not have to write any code at all.
And furthermore if you add child records to the sub form, the foreign key value will be set correctly for you. Again no code is needed.
So, build a standard form based on the main parent table. Then you can build a continuous form Based on the child table and drop that into the above main form.
You then open up the main form in desing mode and setup the sub form property sheet. In that property sheet simply set the link master and link child fields. The link master will be set to the primary key in the main form, and the link child is to be set = the foreign key field from the table in the sub-form.
Once the above is done, then the whole thing should work without any coding and all.

As for the child adding error message:
Assuming you have a main customer form, then the user can't add a order until they navigate to a new customer record. If they don't navigate to a new customer record then they will be editing an existing customer in this main form. So in all cases a main customer record will always be added before they can even enter a customer order.
I suppose a user could navigate to a blank customer record, then jump the cursor (focus) into the sub form where the orders are and start typing. Even in this scenario a blank customer record will be added when the focus moves from the main costumer form to the orders sub form.  ( So the access UI handles the adding of the parent record when you're using a classic main form + a sub form setup)
So from a user interface point of view, it's not really going to be possible for the user to enter orders without a main customer record existing already. Because of this, you're not going to get an error message about the parent customer record not existing. You're only going to get this kind the error if the person opens up the orders form as a non sub form, and then tries to add a new order record. In this case you will get an get an error message. Therefore I really don't see the need to trap this error message. I would not allow the user to open up the sub-form as stand alone. If for some strange reason you do allow the sub-form to be opened up separate from the main form, then open the form with allows additons = false (and again your prevent the need for the error message).
I suppose if for some The reasons users are allowed to open that's sub form or the orders form separately and you've not turned off the allow additions, then they would be able to navigate to a new blank record, and that means the FK to the customer record would not be set correctly.  If there's provisions in this orders form to select a customer, then you could most certainly put the following code in the before update event of this orders form:
If isnull( foreign key field name goes here) = true then
    Msgbox " you must select a customer before you can enter an order"
    Cancel = true
End if

Once again in a sense were not really trapping the error message that a child record is about to be added without the parent record existing. We are simply using the UI interface to tell the user to do some action that will prevent that error message from ever occurring in the first place.


text:
Q: If $g$ is onto and $f$ is one-to-one then $f \circ g$ is onto and one-to-one? If $g$ is one-to-one and $f$ is onto, then we can't say anything about $f \circ  g$, correct?
and if $f\circ g$ is one-to-one and onto, then $g$ is one-to-one and $f$ is onto?
$$g(x) > f(g(x)) = f \circ g$$
$A > Z$ and $Z > B$
we need to look at set $A$ (all elements of $A$ have to map to one unique element of $Z$ to see whether a function $g$ is one-to-one and set $B$ to see if $f$ is onto (there's an arrow to every elements).
Just wanted to make sure I understood correctly.

A: First, if $f\circ g$ is one-to-one, then $g$ is one-to-one. And if $f\circ g$ is onto, then $f$ is onto. So the assertion "if $g$ is onto and $f$ is one-to-one then $f\circ g$ is onto and one-to-one" has to be false.
For example, let $A=\{1,2\}$, $B=\{1\}$, $C=\{1,2\}$. Let $g:A\to B$ be $g(1)=g(2)=1$, $f:B\to C$ be $f(1)=1$. Then $g$ is onto, $f$ is one-to-one, but $f\circ g$ is neither.
In the other way, as you say, you cannot say anything either. Let $A=\{1,2\}$, $B=\{1,2,3\}$, $C=\{1,2\}$. Let $g:A\to B$ be $g(1)=1$, $g(2)=2$, so it is one-to-one. Let $f:B\to C$ be $f(1)=f(2)=1$, $f(3)=2$. Then $f$ is onto. And $f\circ g:A\to C$ is $f\circ g(1)=f\circ g(2)=1$, so it is neither one-to-one nor onto.
I have to admit I struggle to understand the rest of your post.


text:
Q: Android autoLink cause render error I've got some problems with autoLink="phone" option of TextView.
My UI:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/TableLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <TextView
            android:id="@+id/personPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:autoLink="phone"
            android:text="test" />
</TableLayout>

When i switching to Graphical Layout (in ADT) im getting following error:
    Exception raised during rendering: com/android/i18n/phonenumbers/PhoneNumberUtil
    Exception details are logged in Window > Show View > Error Log
    The following classes could not be found:
    - TextView (Change to android.widget.TextView, Fix Build Path, Edit XML)
Error in log:
java.lang.NoClassDefFoundError: com/android/i18n/phonenumbers/PhoneNumberUtil
    at android.text.util.Linkify.gatherTelLinks(Linkify.java:451)
    at android.text.util.Linkify.addLinks(Linkify.java:230)
    at android.widget.TextView.setText(TextView.java:3700)
    at android.widget.TextView.setText(TextView.java:3622)
    at android.widget.TextView.<init>(TextView.java:1259)
    at android.widget.TextView.<init>(TextView.java:607)
    at sun.reflect.GeneratedConstructorAccessor16.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at android.view.LayoutInflater.createView(LayoutInflater.java:594)
    at android.view.BridgeInflater.onCreateView(BridgeInflater.java:86)
    at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
    at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:131)
    at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:755)
    at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:64)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:727)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:373)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:385)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:332)
    at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:325)
    at com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService.createRenderSession(RenderService.java:440)
    at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.renderWithBridge(GraphicalEditorPart.java:1545)
    at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.recomputeLayout(GraphicalEditorPart.java:1302)
    at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.activated(GraphicalEditorPart.java:1059)
    at com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate.delegatePageChange(LayoutEditorDelegate.java:686)
    at com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor.pageChange(CommonXmlEditor.java:360)
    at org.eclipse.ui.part.MultiPageEditorPart$2.widgetSelected(MultiPageEditorPart.java:292)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1077)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1062)
    at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:774)
    at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3028)
    at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:1749)
    at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:278)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4169)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3758)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1053)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:942)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:86)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:588)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:543)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1414)

If i remove
android:autoLink="phone"

error disappears.
Also if i change "phone" to "email", there wouldn't any errors, but "all" cause the same error.

A: I have the same behavior when i use API level 18 to render the view. It won't affect your program. As a workaround you can change the "API version to use when rendering in Eclipse" to 16 rather than 18 while working with layouts that include autolink. There is a button above the graphical view with a robot icon and a number which you can use to change that.
This bug also occurs in Android Studio and is being tracked in Android's issue tracker at http://code.google.com/p/android/issues/detail?id=59497.

A: I have simple solution. you can use
tools: name space to override android name space for example you can use next code sample
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

          <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:autoLink="all"
                tools:autoLink="none"
                />

You need only that xmlns:tools="http://schemas.android.com/tools" and tools:autoLink="none"
This will be applyed only for preview rendering, you cant found that attributes on runtime
Also you can use that name space for other attributes, for ex.:
tools:text="Some text that visible only on preview"


text:
Q: PHP Validation form submit How do you stop an email being sent to you before the form is fully completed.  Currently when submit is clicked even though there are validation errors present that have been picked up via the PHP checks that I have in place:
Code:
  if (isset($_POST['submitButton'])) {

    $fullName      = $_POST['fullName'];
    $myGender      = isset($_POST['myGender']) ? $_POST['myGender'] : '';
    $email         = $_POST['email'];
    $age           = $_POST['age'];
    $myDate        = isset($_POST['myDate']) ? $_POST['myDate'] : '';
    $streetNum     = $_POST['streetNum'];
    $streetName    = $_POST['streetName'];
    $city          = $_POST['city'];
    $state         = $_POST['state'];
    $postCode      = $_POST['postCode'];
    $movie         = $_POST['movie'];

    //You need to se the $var

    if (empty($fullName))
      {
        $errorfullName .= 'Please Enter Your Name';
      }

      if (!ctype_alpha(str_replace(array(" ", "-"), "",$fullName))) {
            $errorfullName .= 'Your name should contain alpha characters only.';
      }

      if (strlen($fullName) < 3 OR strlen($fullName) > 40) {
            $errorfullName .= 'First name should be within 3-40 characters long.';
        }
/*  Check Gender) */

  if ($myGender != 'male' && $myGender != 'female') {
            $errormyGender .= 'Please select your gender.';

        }

  /* Check Email   */

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
     $erroremail .= 'Enter a valid email address.';
     }

/* Age */

if (intval($age) == '') {
        $errorage .= 'Please enter your current age';
        }
if (intval($age) < 3 OR intval($age) > 200){
        $errorage .= 'Age must be less than 200 years';
        }

if(intval($age) == "/^[0-9]$/" ){
          $errorage .= 'Must be numeric numbers';
          }

/*  check date using explode (breaks a string into an array.)if day is not 1-31, throw error*/

if(empty($myDate))
    {
        $errormyDate.= 'Please enter a current date';
    }

     $date_arr = explode ("-", $myDate);

     $dateSplit = array_slice($date_arr, 0,1);

     $dateYear = current($dateSplit);

    if($dateYear > date('Y'))
    {
        $errormyDate .= 'Sorry your not born in the future';
    }

/*  Check Address House Number if its not numeric, throw error */

if (intval($streetNum) == '') {
    $errorstreetNum .= 'Please add street Number';
    }
/* Street Name */

     if (strlen($streetName) < 3 OR strlen($streetName) > 200) {
        $errorstreetName .= 'Street must be filled out and within 200 characters';
        }
 /*City Name */

     if (strlen($city) < 3 OR strlen($city) > 200) {
        $errorcity .= 'City must be filled out and within 200 characters';
        }
 /*State Name */

     if (strlen($state) < 3 OR strlen($state) > 200) {
        $errorstate .= 'State must be filled out and within 200 characters';
        }
/* Check postCode */

   if(intval($postCode) == "/^[0-9]$/" ){
      $errorpostCode .= 'Post Code must be numeric numbers';
      }
/* Check movie selection */

        if (trim($movie) === "select") {
            $errormovie .= 'Please select a favourite movie';
        }

if ($fullName, $myGender, $email, $age, $myDate, $streetNum, $streetName, $city, $state, $postCode, $movie, == " "){

            echo  '$errorsuccess .= 'Please complete all sections of the form'';
            }
            else {
            $success = "Thank you for submitting your form; We will be in contact soon";
                    //send mail
                    $to = "@yahoo.co.nz";
                    $subject = "Php form data";
                    $message = "
".$fullName."

".$myGender."

".$email."

".$age."

".$myDate."

".$streetNum."

".$streetName."

".$city."

".$state."

".$postCode."

".$movie."
";
                    $from = "@yahoo.co.nz";
                    mail($to,$subject,$message);
                  }
}

A: Set something like $err to false at the beginning of the code.  Set it to true when an error is detected.  (Even if it's already true; just setting it is easier than checking.)
Then, you can condition the final result on $err.

A: The reason being is that you even though you have several validations completed in the above, none of them are later checked to see if they failed/passed, your only sanity check is here:
if ($fullName, $myGender, $email, $age, $myDate, $streetNum, $streetName, $city, $state, $postCode, $movie, == " "){

Which its self is pretty useless all together, by the way.
A simpler way for this would be to first create an array to hold all the errors.
$errors = array();

Then when you do your individual checks, make them a key, for example:
if (empty($fullName))
{
    $errors['fullname'] .= 'Please Enter Your Name';
}

And
if (intval($age) == '') {
    $errors['age'] .= ' Please enter your current age.';
}

if (intval($age) < 3 OR intval($age) > 200){
    $errors['age'] .= ' Age must be less than 200 years.';
}

if(intval($age) == "/^[0-9]$/" ){
    $errors['age'] .= ' Must be numeric numbers.';
}

Then later you can do:
if($errors){
    echo 'There are errors in the form. Please observe each of the errors and try again.'. PHP_EOL;
    foreach($errors as $idx => $error){
        echo ucfirst($idx). ': ' .$error;
    }
}

A: It looks like that in order to send the email, you only need to have a value for each of your input fields (from $fullName to $movie).
Where you are validating the form (for example, when you use if (empty($fullName))..., the error that is produced if the form isn't filled out correctly always differs. Unless you have some kind of reason for this, I would just stick to a generic error variable of $formerror.
Then in the final section of your code, where you use if($fullName...$movie == ''), you could change this to if($fullName...$movie === '' AND !empty($formerror)) so that if any errors were picked up during the validating of the form, you would be able to echo $formerror and if not, the email would send.


text:
Q: Deriving the time-dependent solution of the Schrödinger equation I have the Schrödinger equation:
$$\dfrac{-\hbar^2}{2m} \nabla^2 \Psi + V \Psi = i \hbar \dfrac{\partial{\Psi}}{\partial{t}},$$
where $m$ is the particle's mass, $V$ is the potential energy operator, and $(-\hbar^2/2m) \nabla^2$ is the kinetic energy operator ($p^2/2m$).
The state function can be expressed as the product of space-dependent and time-dependent factors, $\Psi = \psi(r) \psi(t)$. If we substitute these into the above equation and divide by $\psi w$, we obtain a function on the left that depends on $r$ and a function on the right that only depends on $t$:
$$\dfrac{-\hbar^2}{2m} \dfrac{\nabla^2 \psi}{\psi} + V = \dfrac{i \hbar}{w} \dfrac{\partial{w}}{\partial{t}}.$$
Therefore, to be valid for all $r$ and $t$, each side must equal a constant, $E$:
$$\dfrac{-\hbar^2}{2m} \dfrac{\nabla^2 \psi}{\psi} + V = \dfrac{i \hbar}{w} \dfrac{\partial{w}}{\partial{t}} = E.$$
From this, we immediately have
$$w(t) = Ce^{-i(E/\hbar)t},$$
from which we can identify that $E = \hbar \omega$, where $\omega$ is the radian frequency of oscillation.
It's been a while since I've done PDEs, so I'm not sure how we "immediately have" $w(t) = Ce^{-i(E/\hbar)t}$. The form of $\dfrac{-\hbar^2}{2m} \dfrac{\nabla^2 \psi}{\psi} + V = \dfrac{i \hbar}{w} \dfrac{\partial{w}}{\partial{t}} = E$ reminds me of a separation of variables situation, but I'm not entirely sure.
Furthermore, I'm not sure how we identify that $E = \hbar w$ from $w(t) = Ce^{-i(E/\hbar)t}$.
I would greatly appreciate it if people would please take the time to explain this.

A: Note that we have performed a separation of variables and have two separate differential equations
$$\frac{i \hbar}{w} \frac{\partial w}{\partial t} = E \\
\frac{-\hbar^2}{2m \psi} \nabla^2 \psi + V = E$$
The first equation is just a first-order ODE of the form $w'(t) = A w$, whose solution is a scalar multiple of $e^{At}$. Here $A = E/(i \hbar) = -i E / \hbar$, which is why the solution to the differential equation in time is as you have written. Note that the second equation above is referred to as the time-independent Schrodinger equation.
Intuitively, one can note that the solution to the differential equation in time is periodic with some frequency $\omega = E/ \hbar$. So the wave equation of the particle has frequency $\omega$, and rewriting the previous equation gives the relation $E = \hbar \omega$.


text:
Q: create a generic class for the type name there is a class
public class Repository <TKey, TEntity>
{
    public ICollection<TEntity> Get()
    {
        using (var session = NHibernateHelper.OpenSession())
        {
            if (typeof(TEntity).IsAssignableFrom(typeof(IActualizable)))
                return session.CreateCriteria(typeof(TEntity)).Add(Restrictions.Lt("ActiveTo", DBService.GetServerTime())).List<TEntity>();

            return session.CreateCriteria(typeof(TEntity)).List<TEntity>();
        }
    }
}

how to create it, knowing only the name of TEntity?
Example:
class Game
{
}
string nameEntity = "Game";
var repository = new Repository< long, ??? >();

A: There's three parts to this:

*

*getting the Type from the string "Game"

*creating the generic instance

*doing something useful with it

The first is relatively easy, assuming you know a bit more - for example, that Game is in a particular assembly and namespace. If you know some fixed type in that assembly, you could use:
Type type = typeof(SomeKnownType).Assembly
      .GetType("The.Namespace." + nameEntity);

(and check it doesn't return null)
Then we need to create the generic type:
object repo = Activator.CreateInstance(
      typeof(Repository<,>).MakeGenericType(new[] {typeof(long), type}));

however, note that this is object. It would be more convenient if there was a non-generic interface or base-class that you could use for Repository<,> - I would put serious though into adding one!
To use that, the easiest approach here will be dynamic:
dynamic dynamicRepo = repo;
IList entities = dynamicRepo.Get();

and use the non-generic IList API. If dynamic isn't an option, you'd have to use reflection.
Alternatively, adding a non-generic API would make this trivial:
interface IRepository {
    IList Get();
}
public class Repository <TKey, TEntity> : IRepository {
    IList IRepository.Get() {
        return Get();
    }
    // your existing code here
}

then it is just:
var repo = (IRepository)Activator.CreateInstance(
      typeof(Repository<,>).MakeGenericType(new[] {typeof(long), type}));
IList entities = repo.Get();

Note: depending on the data, IList might not work - you might need to drop to the non-generic IEnumerable instead.


text:
Q: Fixed div gets locked during vertical scroll until main content also reaches the end I've tried to look for a response to this, but even when some questions are similar, I couldn't find any answer to my problem.
In my website I use Sidr JQuery plugin for a left side menu. It is a fixed div with bottom:0, overflow-y: scroll.
The main content has a bigger height than the left side menu.
On my mobile (Chrome on Android), when I scroll this menu vertically, it starts scrolling OK but then it gets locked and starts to scroll the main content. Only when main content reaches almost the end, the left side menu also finishes scrolling.
How can I avoid this behavior and have both elements scroll independently from each other?
Thanks!

A: For anyone who ends up in the same situation, it was just because SIDR modifies the body while the left menu was open, setting the position of the main content as "absolute".
I've added something like:
    body.sidr-open { position: fixed !important; }
And it solved the problem!

A: I found if I added 400px of padding to the bottom of the last item in the div.sidr, you can now swipe to the bottom of the menu more easily. Not the best workaround but it seems to have fixed the problem.


text:
Q: установка одинаковой скорости у меня есть java код:
int vx = enemy_pos_x - t_pos_x;
int vy = enemy_pos_y - t_pos_y;
x += vx;
y += vy;

он делает чтобы объект двигался в определённую точку.
x,y-позиция объекта
enemy_pos_x,y-позиция точки б
t_pos_x,y-позиция точки а

Проблема в том, что шарик летит с разной скоростью и прилетает всегда с одним временем полёта, надо установить одинаковую скорость.
этот код находится в таймере

A: Кинематика: <положение> = <время> * <скорость>. Вам нужно задать вектор скорости пули (vx, vy). Я буду считать что величина скорости постоянна и хранится в bullet_speed.
Направление на врага:
dx = enemy_pos_x - t_pos_x;
dy = enemy_pos_y - t_pos_y;

Расстояние до врага:
dist = (dx ** 2 + dy ** 2) ** 0.5;

Скорость по направлению к врагу:
vx = bullet_speed * dx / dist;
vy = bullet_speed * dy / dist;

Стартовая точка пули:
x = t_pos_x
y = t_pos_y

В цикле по таймеру находите промежуток времени, умножаете его на скорость, добавляете к координатам пули:
dt = now_t - prev_t;
x += vx * dt;
y += vy * dt;


text:
Q: How can I extend UiApp with a new function? I would like to extend (prototype) UiApp in Google Apps Script with a wrapping function, but I am getting TypeError when running a simple sample like below...
what am I doing wrong?
Object.prototype.addLabel = function(text) {
  this.createLabel(text);
  return this;
}

function testingxUiApp() {
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var app = UiApp.createApplication().setTitle('playing around UiApp').setHeight("250");
  var panel = app.createFlowPanel().setId('panel');
  app.add(panel);
  panel.add(app.addLabel("adding label for testing"));
  doc.show(app);
}

thanks

A: It is impossible to extend UiApp, Document, Spreadsheet and other high order classes. Google prevented it. If to execute the var isObject = UiApp.createApplication() instanceof Object; line then the isObject is false, although the typeof UiApp.createApplication(); expression returns object.

A: BTW note from 2021: (from https://b.corp.google.com/issues/36753527)
It looks like Reflect used in V8 can do the trick:
  Reflect.set(
    Reflect.getPrototypeOf(SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Some sheet')),
    'myMethod',
    function() {
      return `From sheet '${this.getSheetName()}' with love`;
    }
  );

  let message = SpreadsheetApp.getActiveSheet().myMethod();
  console.log(message); // From sheet 'Sheet1' with love`


text:
Q: Google Oauth for YouTube : Why do I get "Undefined index: oauth_token" ( Jim S.' code ) I got a little problem with the OAuth for Google, I use the Jim Saunder Libraire for CodeIgniter (http://codeigniter.com/wiki/OAuth_for_Google) but when I came to my access_youtube function, which look like that :
public function access_youtube()
{ //STEP 2

// Here is the first call to load the library
    $params['key'] = 's390075769.onlinehome.fr';
    $params['secret'] = 'iHD72YKzWmbm8VTwncht_E-d';

// We  can change the signing algorithm and http method by setting the following in your params array.
    $params['algorithm'] = 'HMAC-SHA1';
    // $params['method'] = "GET";

// We need to reload the library since we left our site beetween Step 1 & 2.
    $this->load->library('google_oauth', $params);

// We are using HMAC signing you need to specify the token_secret you got from the request step as the second parameter of this method. So
    $token_secret = $this->session->userdata('token_secret');
    $oauth = $this->google_oauth->get_access_token(false, $token_secret);

// The access method will return an array with keys of 'oauth_token', and 'oauth_token_secret'
// These values are your access token and your access token secret. We should store these in our database.
    $this->session->set_userdata('oauth_token', $oauth['oauth_token']);
    $this->session->set_userdata('oauth_token_secret', $oauth['oauth_token_secret']);

// Now you have an access token and can make google service requests on your users behalf
    redirect(site_url());
}

I got several error messages :

Undefined index: oauth_token
Undefined index: oauth_token_secret

which refer to the lines $this->session->set_userdata ...
and, after each error message I get :

Message: Cannot modify header information - headers already sent by (output started at /homepages/7/d390075755/htdocs/system/core/Exceptions.php:170)
  Filename: libraries/Session.php
  Line Number: 671

which, I think is linked with the previous error message.
so I tried that in the constructor :
class Example extends CI_Controller
{
private $CI;
public function __construct()
{
     parent::__construct();

    $this->CI =& get_instance();
    $this->CI->load->library('session');

    $oauth = array();
    $oauth['oauth_token_secret']='';
    $oauth['oauth_token']='';

}

just before my function but it doesn't do anything .. and I'm affraid I'm gonna loose my session variables stock by google ... isn't it ? Do I get my tokens from google ?

A: Honestly i am not sure how Session will be managed by PHP code so will be of little help for you.
It seems that this line is the cause
$oauth = $this->google_oauth->get_access_token(false, $token_secret);

you are trying to get access_token from the Google to send request to Google API to get user information who ever authorize your application and i guess Google is not returning what has been expected from them.
this can be due to type mismatch in the request data as what Google Oauth is expecting from you and what actually you are sending
In you case i would have used debugger of my Eclipse to see what exactly is going on but for OAuth i already told you in earlier question

*

*You  need to store that token you getting at your first step.

*Once your user is back from authenticate them-self you need to get access_token using that request token

*Once you have request token you are ready to make final API call and it seems that some how your code is failing to get the data from session


text:
Q: Problems with HTML and CSS: Icon and navigation bar issue I'm following a YouTube video about making websites and his website looks like this:

and mine looks like this:

As you can see, the icon is in the navigation bar and itself has a little of space between the Google web browser bar, and my website doesn't have all of this.
I looked the lowercase letters and to my it's fine everything, look any grammar error and frankly don't see any error
This is my code:
HTML
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">

    <title>pomodone.app</title>

Pomodone

                <input type="text" id="search" placeholder="search here">

CSS
*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: 'poppins', sans-serif;
}
.topbar{
    position: fixed;
    background: #fff;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.08);
    width: 100%;
    height: 60px;
    padding: 0 20px;
    display: grid;
    grid-template-columns: 2fr 10fr 0.4fr 1fr;
    align-items: center;
    z-index: 1;
}

.logo h2{
    color: #df7f27;
}

.search{
    position: relative;
    width: 60%;
    justify-self: center;
}

.search input {
    width: 100%;
    height: 40px;
    padding: 0 40px;
    font-size: 16px;
    outline: none;
    border: none;
    border-radius: 10px;
    background: #f5f5f5;

}
.search i {
    position: absolute;
    right: 15px;
    top: 15px;
    cursor: pointer;
}

.user{
    position: relative;
    width: 50px;
    height: 50px;
}

.user img{
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    object-fit: cover;
}

Thank you in advance

A: @Iomipac, you need to set position to the label.
Please add this style. Hope it is helpful~.
.search >label {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
        }

* {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
            font-family: 'poppins', sans-serif;
        }

        .topbar {
            position: fixed;
            background: #fff;
            box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.08);
            width: 100%;
            height: 60px;
            padding: 0 20px;
            display: grid;
            grid-template-columns: 2fr 10fr 0.4fr 1fr;
            align-items: center;
            z-index: 1;
        }

        .logo h2 {
            color: #df7f27;
        }

        .search {
            position: relative;
            width: 60%;
            justify-self: center;
        }

        .search input {
            width: 100%;
            height: 40px;
            padding: 0 40px;
            font-size: 16px;
            outline: none;
            border: none;
            border-radius: 10px;
            background: #f5f5f5;

        }

        .search >label {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
        }

        .search i {
            position: absolute;
            right: 15px;
            top: 15px;
            cursor: pointer;
        }

        .user {
            position: relative;
            width: 50px;
            height: 50px;
        }

        .user img {
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
            width: 100%;
            object-fit: cover;
        }

Pomodone

                <input type="text" id="search" placeholder="search here">
                icon


text:
Q: Spring Page.getContent giving class cast exception Because of some need, I have manually did like this in spring data jpa:
List<Foo> fooList = repository.findAll();
PageRequest pg = new PageRequest(1, 20);
Page<Foo> pageFoo = new PageImpl<Foo>(fooList, pageRequest, fooList.size());
final List<Foo> iterable = pageFoo.getContent();

for(Foo foo : iterable) {

}

In the line of for loop I am getting class cast exception saying object can't cast to foo.
Why is like that? But when I do iterable.size() its giving the actual count of records in the object.
Please help me to solve this case.

A: It's Pageable not PageRequest for further ref:
https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/PageImpl.html
List<Foo> fooList = repository.findAll();
Pageable pg = new PageRequest(1, 20); //
Page<Foo> pageFoo = new PageImpl<Foo>(fooList, pg, fooList.size());
final List<Foo> iterable = pageFoo.getContent();
for(Foo foo : iterable) {
 .....
}


text:
Q: How would you change or rather optimize this postgres sql query so that the output format remains the same? Original expensive and slow query is this:
select 'INTEGRATED' as "STATUS", coalesce(sum(response_count),0) as "COUNT" from f_wfc_transaction_summary_isocc_ft_sum_no_tid('2015-07-22 00:00:00','2015-08-05 01:00:00', null, 'LINK')
where wfc_result in ('TM_OK', 'TM_NO_CHANGE')
union
select 'WFC_FALLOUT' as "STATUS", coalesce(sum(response_count),0) as "COUNT" from f_wfc_transaction_summary_isocc_ft_sum_no_tid('2015-07-22 00:00:00','2015-08-05 01:00:00', null, 'LINK')
where wfc_result LIKE 'WFC%'
union
select 'TM_FALLOUT' as "STATUS", coalesce(sum(response_count),0) as "COUNT" from f_wfc_transaction_summary_isocc_ft_sum_no_tid('2015-07-22 00:00:00','2015-08-05 01:00:00', null, 'LINK')
where wfc_result = 'TM_FAIL'
union
select 'WFC_PENDING' as "STATUS", coalesce(sum(response_count),0) as "COUNT" from f_wfc_transaction_summary_isocc_ft_sum_no_tid('2015-07-22 00:00:00','2015-08-05 01:00:00', null, 'LINK')
where wfc_result = 'PENDING';

Output:
Status       Count
Integrated     40
TM_FALLOUT      50
WFC_PENDING      60
WFC_FALLOUT      70

The output format above is what I need. But this query takes a lot of time.
The query that I want to use is the following as it takes less time.
select
sum(CASE WHEN wfc_result IN ('TM_OK','TM_NO_CHANGE') THEN response_count ELSE 0 END) as "INTEGRATED",
sum(CASE WHEN wfc_result LIKE 'WFC%' THEN response_count ELSE 0 END) as "WFC_FALLOUT",
sum(CASE WHEN wfc_result = 'TM_FAIL' THEN response_count ELSE 0 END) as "TM_FALLOUT",
sum(CASE WHEN wfc_result = 'PENDING' THEN response_count ELSE 0 END) as "WFC_PENDING"
from f_wfc_transaction_summary_isocc_ft_sum_no_tid('2015-07-22 00:00:00','2015-08-05 01:00:00',null, 'LINK')

However, the output of this query is as follows, I need the same output as I get from the first query.
Integrated   WFC_FALLOUT   TM_FALLOUT   WFC_PENDING
40             50            60              70

I tried several ways but unable to find out how I can edit this?

A: Assuming that 'wfc_result' WFC% is always WFC_% yo can do the following:
SELECT status.lbl AS status, coalesce(sum(response_count), 0) AS count
FROM (VALUES
  ('TM_O', 'INTEGRATED'),
  ('TM_N', 'INTEGRATED'),
  ('WFC_', 'WFC_FALLOUT'),
  ('TM_F', 'TM_FALLOUT'),
  ('PEND', 'WFC_PENDING')) status(cls, lbl)
LEFT JOIN f_wfc_transaction_summary_isocc_ft_sum_no_tid('2015-07-22 00:00:00', '2015-08-05 01:00:00', NULL, 'LINK') wfc
  ON substr(wfc.wfc_result, 1, 4) = status.cls
GROUP BY 1;

If there are only a few 'wfc_result' strings LIKE 'WFC%' you could also spell them out (as well as the other classes) in the VALUES clause and then drop the substr() function in the JOIN clause.
To get the total output, the query is much simpler:
SELECT sum(response_count) AS total_count
FROM f_wfc_transaction_summary_isocc_ft_sum_no_tid('2015-07-22 00:00:00', '2015-08-05 01:00:00', NULL, 'LINK');

This does of course make another call to the expensive function, but there is no way to get around that on the database; in your client application you could simply sum up the "count" values returned from the previous query.


text:
Q: R: Margins too large when grid.arranging plots in two rows in grid.arrange/ggplot2 I am drawing multiple maps based on a list with the following ggplot2 custom function:
plot_list = list()
for (i in 1:length(input_map[[1]])) {
  p = ggplot() +
    geom_polygon(data = df_new, aes_string(x = "long.x", y = "lat.x", fill=input_map[[3]][i],
                                group = "commune"), size=0, colour = "lightgrey") +
    geom_polygon(data = cantons_shp, aes(x = long, y = lat, group = group),
                 size= .1, colour = "lightgrey", fill = NA) +
    coord_fixed() +
    scale_fill_gradient(low = "white", high = input_map[[2]][i], name = input_map[[1]][i], na.value="white", limits=0:1) +
    labs(title = input_map[[1]][i], x = "", y = "") +
    theme_void() +
    theme(plot.title = element_text(size=10, hjust = 0.5),
          legend.position = "bottom", # c(0.85, 0.75)
          legend.text = element_text(size=7),
          legend.title = element_blank(),
          plot.background = element_rect("white"),
          plot.margin=unit(c(0,0,0,0), "cm"))
  plot_list[[i]] = as.grob(p)
}

When arranging 6 maps with grid.arrange in two rows, the maps are getting too small and there is lots of white space between the plots.
# grid.arrange without do.call does not work
do.call("grid.arrange",
          c(plot_list, nrow=2,
          top=title,
          bottom=paste0(n_recordings, " Opnamen aus ", n_communes, " Gemengen", "\nSchnëssen-Projet | (c) Universitéit Lëtzebuerg, 2019")
          )
      )

In the theme options, I already reduced plot.margin to 0, without avail.


text:
Q: Azure web app not working - 500 I really want to use dotnet core and azure. I used the amazing yeoman aspnet generator to scaffold out a basic app. This ran fine locally using Kestrel.
I then added the app to my github account and linked this to a new Azure Web App instance to deploy the thing. But no joy :( I get a 500 error.
Looking at the setting of the webapp it saying using .net framework 4.6 is that right or am I missing something, cannot see an option for .net core 1.0 that I expected to see??
I tried turning on logging in the setting with detailed exceptions etc but have not found anything to give me a clue as to what going on.

A: @Andy, Could you try access into kudu site(yoursite.scm.azurewebsites.net) and start web.cmd file in this folder (/home/site/approot)? I suggest you can try to start this command. Meanwhile, please refer to Shawn's blog 'https://wildermuth.com/2016/04/29/Deploying-ASP-NET-Core-RC1-to-Azure-App-Services '. Any information or update, please let me know.


text:
Q: Import Excel file to SQL Server row-by-row I'm importing an Excel file (about 1000 records only) to a dedicated SQL Server database. As I need to work on the incoming data from Excel (add a GUID per row, some data conversions) I want to do it row by row and don't want to bulk import (I have nothing against transactions, though).
I'm confused on how to do it correctly. I can either use an SQLCommand with parameters like so:
SqlCommand sqlCommand = new SqlCommand("insert into TestTable(GUID,Name,Pricing) values(@GUID,@Name,@Pricing)", sqlConn);
foreach (DataRow dr in ds.Tables[0].Rows) //<-- this is my Excel file to iterate through
{
 sqlCommander.Parameters.Clear();
 String refGUID = Guid.NewGuid().ToString();
 sqlCommander.Parameters.AddWithValue("GUID", refGUID);
 sqlCommander.Parameters.AddWithValue("Name", dr.ItemArray[0]);
 sqlCommander.Parameters.AddWithValue("Pricing", dr.ItemArray[1]);
 sqlCommander.ExecuteNonQuery();
}

Or I can use the "connected" mode like so:
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT GUID, Name, Pricing FROM TestTable", sqlConn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

DataSet myDataSet = new DataSet();
dataAdapter.Fill(myDataSet, "TestTable");
foreach (DataRow dr in ds.Tables[0].Rows) //<-- this is my Excel file to iterate through
{
 DataRow row = myDataSet.Tables[0].NewRow();
 row["GUID"] = refGUID;
 row["Name"] = dr.ItemArray[0];
 row["Pricing"] = dr.ItemArray[1];
 myDataSet.Tables[0].Rows.Add(row);
 dataAdapter.Update(myDataSet);
}

Now my questions are the following:

*

*Is it better to send an INSERT command for each row (that would be the SqlCommand method) or is it better to fill a special DataSet (2nd Method)? I guess it is rather "stupid" to have 1000's of inserts to an SQL server?

*dataAdapter.Update(myDataSet) <-- should I do that AFTER iterating through all Excel rows or for each row (as shown in the example code above), would this magically create a transaction?

*Which method should I use? There also is LINQ to SQL - why not use that (performance maybe, because of another layer)?

*What happens to the DataSet when some error occurs when reading out the Excel file - is the update still pushed to the SQL server or is everything lost?

In short: I want to import an Excel file to an SQL server row-by-row whilst making changes on the data to be imported (and I don't want to use SSIS packages [because besides data conversion I am doing a lot more with the Excel file like importing it to Sharepoint and firing of Workflows] or BizTalk)
»» How to do that beautifully?

In the end I went ahead and bought Aspose Cells. Aspose has a very nice set of tools at their disposal.

A: You mention not wanting to use SSIS - but have you considered SqlBulkCopy? Then there is no need for anything except .NET yet you can still use the fastest/most-direct import.
This will accept a DataTable, so you can prepare your data in a DataTable and then pull the trigger. Transactions are optionally supported IIRC. For larger data you can also implement IDataReader to provide fully streaming upload (while still processing each row in transit).

A: Given your description of your problem: "I want to import an Excel file to an SQL server row-by-row whilst making changes on the data to be imported" - SSIS is the perfect tool for the job.
Importing Excel data with SQL Server Integration Services SSIS with unicode and non-unicode data issues

A: The dataSet will probably ending up sending the INSERT statements to the server, so in my opinion, is better to to just send the INSERT statements without the DataSet. You also can have more control over the process, like checking for individual rows for errors, logging, etc.

A: You could convert your processed data table into XML and pass that to a stored procedure in Sql server (in one query) and have your stored procedure parse the XML to create the records.

A: INSERT INTO [dbo].[TableName]
           ([ColumnName1]
           ,[ColumnName2])
)
SELECT [ColumnName1]
           ,[ColumnName2]

FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0','Data Source= PathToFile.xls;Extended Properties=Excel 8.0')...[Sheet1$]


text:
Q: python call to boto3.client.create_data_source_from_s3 I'm trying to use AWS Machine Learning batch processes from a python project.  I'm using boto3.  I am getting this failure message in the response.

There was an error trying to parse the schema: \'Can not deserialize
  instance of boolean out of START_ARRAY token\n at [Source:
  java.io.StringReader@60618eb4; line: 1, column: 2] (through reference
  chain:
  com.amazon.eml.dp.recordset.SchemaPojo["dataFileContainsHeader"])\

The .csv file I am using works.  I know this because it worked through the console process.
Here is my code; it is a function within a django model which holds the url to the file to be processed (input_file):
    def create_data_source_from_s3(self):
        attributes = []
        attribute = { "fieldName": "Var1", "fieldType": "CATEGORICAL" }
        attributes.append(attribute)
        attribute = { "fieldName": "Var2", "fieldType": "CATEGORICAL" }
        attributes.append(attribute)
        attribute = { "fieldName": "Var3", "fieldType": "NUMERIC" }
        attributes.append(attribute)
        attribute = { "fieldName": "Var4", "fieldType": "CATEGORICAL" }
        attributes.append(attribute)
        attribute = { "fieldName": "Var5", "fieldType": "CATEGORICAL" }
        attributes.append(attribute)
        attribute = { "fieldName": "Var6", "fieldType": "CATEGORICAL" }
        attributes.append(attribute)

        dataSchema = {}
        dataSchema['version'] = '1.0'
        dataSchema['dataFormat'] = 'CSV'
        dataSchema['attributes'] = attributes
        dataSchema["targetFieldName"] = "Var6"
        dataSchema["dataFileContainsHeader"] = True,
        json_data = json.dumps(dataSchema)

        client = boto3.client('machinelearning', region_name=settings.region, aws_access_key_id=settings.aws_access_key_id, aws_secret_access_key=settings.aws_secret_access_key)
        #create a datasource
        return client.create_data_source_from_s3(
            DataSourceId=self.input_file.name,
            DataSourceName=self.input_file.name,
            DataSpec={
                'DataLocationS3': 's3://' + settings.AWS_S3_BUCKET_NAME + '/' + self.input_file.name,
                'DataSchema': json_data,
            },
            ComputeStatistics=True
            )

Any ideas what I'm doing wrong?

A: Remove the comma
  dataSchema["dataFileContainsHeader"] = True,

This is causing Python to think that you are adding a tuple. So your dataSchema actually contains (True, )
and your output looks like this
{"dataFileContainsHeader": [true], "attributes": [{"fieldName": "Var1", "fieldType": "CATEGORICAL"}, {"fieldName": "Var2", "fieldType": "CATEGORICAL"}, {"fieldName": "Var3", "fieldType": "NUMERIC"}, {"fieldName": "Var4", "fieldType": "CATEGORICAL"}, {"fieldName": "Var5", "fieldType": "CATEGORICAL"}, {"fieldName": "Var6", "fieldType": "CATEGORICAL"}], "version": "1.0", "dataFormat": "CSV", "targetFieldName": "Var6"}

AWS is instead expecting something like this
"dataFileContainsHeader": true


text:
Q: R Generate hourly datetime I want to generate datetime hourly as below
Thank you
2017-01-01 0100
2017-01-01 0200
...
2020-01-01 2300
2020-01-31 2400

A: You can also do this with lubridate:
library(lubridate)
seq(ymd_h("2017-01-01-00"), ymd_h("2020-01-31-24"), by = "hours")

A: as.POSIXct('2017-01-01')+3600*1:(24*31)

 [1] "2017-01-01 01:00:00 CET" "2017-01-01 02:00:00 CET" "2017-01-01 03:00:00 CET" "2017-01-01 04:00:00 CET"
 [5] "2017-01-01 05:00:00 CET" "2017-01-01 06:00:00 CET" "2017-01-01 07:00:00 CET" "2017-01-01 08:00:00 CET"
 [9] "2017-01-01 09:00:00 CET" "2017-01-01 10:00:00 CET" "2017-01-01 11:00:00 CET" "2017-01-01 12:00:00 CET"
[13] "2017-01-01 13:00:00 CET" "2017-01-01 14:00:00 CET" "2017-01-01 15:00:00 CET" "2017-01-01 16:00:00 CET"
[17] "2017-01-01 17:00:00 CET" "2017-01-01 18:00:00 CET" "2017-01-01 19:00:00 CET" "2017-01-01 20:00:00 CET"
[21] "2017-01-01 21:00:00 CET" "2017-01-01 22:00:00 CET" "2017-01-01 23:00:00 CET" "2017-01-02 00:00:00 CET"


text:
Q: In search of an algorithm for sorting collection in nodes to satisfy a layout constraint

Firstly, I apologize for the poor title; I cannot think of a good name for this algorithm.
I have an ordered list of stages. Each stage has a cast of characters, unordered. Characters can occur in multiple stages.
A crossing occurs when two consecutive stages cannot have their casts concatenated, with overlap allowed where it would unify the same character on both casts, in a way that leaves a character duplicated in the concatenation. Or, informally, a crossing is when a character would need to be at two different spots at once in a line-up of the combined casts. In code:
uncrossed = [D, F], [N, V, S]
overlap = [D, F, V], [V, N, S]
crossed = [D, V, F], [N, V, S]

In the first example, V isn't with D and F, so there aren't any crossings. In the second example, V is with D and F and then with N and S, but this isn't a problem because the ordering permits (with overlap) a crossing-less concatenation. On the third example, though, the ordering forces a crossing.
For my purposes, crossings can occur on non-consecutive stages as if characters did not actually stray from their previous order in the cast when they are not "on-stage."
I would like to order each stage's cast such that there are as few crossings as possible, understanding that it is definitely possible to have situations where crossings are inevitable. An example series which requires crossings:
required = [A, B], [B, C], [A, C], [A, B]

This all sounds very abstract and silly, so I'll provide a concrete example of a human solving this algorithm for a purpose similar to mine: http://xkcd.com/657/ In this case, the constraint is deliberately ignored for aesthetic purposes, but it's still possible to get a visual idea of what I'm talking about.
I already have some crude ideas for how to solve this, but nothing affordable, and I'm wondering if this is isomorphic to some problem already covered in the literature. It sounds vaguely topological as well.
Since people asked, this algorithm appears to be key to automatically generating pretty timelines for storyboards of characters in stories, and that's what I'm intending to use it for.

A: This isn't an answer, but I think maybe a more precise or even more correct formulation of what you are looking for:
There is a set, call it C, of characters, and there is a finite ordered sequence S_1, ... S_n of scenes, where a scene is a set consisting of some of the characters.  Characters may (and typically do) appear in multiple scenes.
I'd like to phrase your desired outcome in a slightly different way from how you phrased it, because I think it makes it clearer how one may search for a solution (or at least, it makes it totally clear how to brute-force a solution):
The output of our algorithm is a sequence of arrangements of the characters.  An arrangement of the characters is just a permutation of the ordered tuple [c_1, ... c_m], where the c_i are the characters, and there are m of them in total, so C = {c_1, ..., c_m}.  We want n arrangements in total, call them A_1, ..., A_n, one per scene.
What arrangement A_n corresponds to is the top-to-bottom ordering of the characters in your storyboard, during scene n, in the following sense: draw a vertical line through your storyboard passing through scene n.  This line should hit the characters' life-lines in the order specified by A_n.
We require the following property of our arrangements: given scene S_n, the arrangement A_n needs to put the characters contained in S_n into a contiguous chunk, in the following sense: suppose that S_n = {c_2, c_3, c_5}.  Then A_n may yield [c_1, c_4, c_2, c_3, c_5], but may not yield [c_2, c_1, c_3, c_4, c_5].  This is because you don't want an errant character "cutting through" the scene in the storyboard.
We hope to minimize the number of "crossings."  Here, crossings are easy to define: the number of crossings between A_i and A_(i+1) is exactly equal to the number of transpositions of adjacent characters required to go from permutation A_i to permutation A_(i+1).

I haven't given you an answer, but I think that given the above setup, a brute-force approach isn't too hard to code up, and will give you an answer overnight without a problem, if the storyboard isn't too big.
I think that if you posted this problem on MathOverflow, you could possibly get someone interested in it.  Or maybe it has been solved, who knows?


text:
Q: Terraform elastic beanstalk Can any one guide me, how to set alerts(SES) for CPU and others in with in elastic beanstalk using Terraform?
I have already setup an ROR Elastic Beanstalk stack using Terraform, now I need to setup the Cloud Watch with it. Is there any settings which comes with Elastic Beanstalk for Terraform?
Also how to setup two environments(Staging and Production) in Elastic Beanstalk using Terraform, I also need to setup Cloud Watch and email alerts. Can anyone guide me. I need this for AWS.
Thanks


text:
Q: d3 legend, Missing text labels and duplicates values I have been exploring how to add a legend to a plot and update the legend following a transition in which a new type of is plotted. I've run into two issues which I haven't been able to troubleshoot my way through.
The block is here  http://bl.ocks.org/natemiller/df4b96809580fe7d00a6
The sample JSON dataset includes several different variables (temp, pH, name, y, etc.) and what I am trying to develop is a plot that changes which variable is plotted on the x-axis and which variable determines the fill of the data points when a button is clicked. So far I have the x-axis changing, the points moving appropriately, and the legend color changing properly. However, I have two issues.

*

*I'm missing the legend text (labels). I'm not clear on why they are not being shown, but I assume its a small detail I am missing. I'd appreciate any help with that.

*As you can see in the dataset there are several "samples" from the same site, or with the same pH (7.2,8.0,7.2,7.2,8.0,8.0,7.6), or with the same temp (30, 25, 25, 30, 30, 25, 25). As such, when I generate the legend such as in the code here...
varlegend = svg.selectAll('rect')
   .data(data)
   .enter().append("rect")
   .attr('x', width-50)
   .attr('y', function(d,i) {return i*20;})
   .attr('width', 10)
   .attr('height', 10)
   .style('fill', function(d) {
     return color(d.name);
   });

...and set the color using d.name I get 7 rectangles (one for each value), through I would rather have 3 rectangles when the fill color is set by site or pH (and two if the fill is set by temp) given some values are duplicates. Is there a means of doing this? I've considered d3.nest, but when I initiate the transition I no longer want the data nested by name, but rather by pH (so the fill is set by d.pH). I'd appreciate any comments on this. Am I doing this in a too complicated manner? Are there simpler ways I should be thinking about accomplishing this same goal?
Thanks for you time and help,
Nate

A: 2 - When you provide the .data value, you can also provide a function that returns a uniquely identifying value. Something like this:
varlegend = svg.selectAll('rect')
   .data(data, function(d) { return d.name })
//...

From the documentation of selection.data: "To control how data is joined to elements, a key function may be specified. This replaces the default by-index behavior"
1 - Regarding the text not showing up, I think the issue is the missing 'stroke' attribute. You've probably got white on white. However, another approach to consider is using a 'g' tag to hold both the rect and the text. Something like this:
var legend = svg.selectAll('.legend')
      .data(data, function(d) { return d.name; })
      .enter().append('g')
      .attr('class', 'legend')
      .attr('ID', function(d) { return d.name })
      .attr("transform", function(d,i) {
        return "translate(" + 800 + "," + i*20 + ")";
      });

legend.append("rect")
      .attr('width', 10).attr('height', 10)
      .style('fill', function(d) {
        return color(d.name);
      });

legend.append("text")
      .attr('x', 25).attr('y', 10)
      .text(function(d) { return d.name; })
      .attr("font-family","sans-serif")
      .attr("font-size","11px")
      .attr("stroke","black");

A: Question 1: The text is not showing up because you cannot append text to a rect in SVG. That is to say, a rect cannot act like a container. Your problem is that you have specified legend = svg.selectAll('rect'), which means saying below legend.append("text") will not work. The solution is thus as explunit suggested: join the data to a g (group) and then separately append the rect and text to that group.
Question 2: One way is to first create an array that removes duplicate entries, then use that array for your legend data-join. Here is an example:
var legendData = d3.values(data.map(function (d) { return d.temp; }))

var unique = legendData.filter(function (elem, pos) {
   return legendData.indexOf(elem) == pos; })

This you the unique array, which contains: [30, 25].
To ease headache, I would recommend you put all of your .enter() and .transition() in a single redraw function into which you can pass your data. So you can first filter your legend data by pH or temp, then pass that newly created array into the redraw function and the legend will transition, also removing old/unneeded elements. See Mike Bostock's post on the General Update Pattern for info on how to lay out the redraw function.


text:
Q: Chrome input padding issue I'm having an issue with inconsistency with inputs in chrome.
I'm using a big font-size, but setting the height and line-height to smaller to remove gaps above and below the text.
input {
  font-size: 100px;
  padding: 0;
  margin: 0;
  height: 80px;
  line-height: 80px;
}

IE and Firefox seem to render it correctly, but chrome seems to add padding to the text of the input.
Fiddle showing what's going on here: http://jsfiddle.net/tomdickie/nZY8r/1/
EDIT:
To add a bit more clarity, to this here are some screenshots:
Firefox

Chrome

I'm trying to get Chrome to behave like Firefox (and IE) do.

A: try this and its woring here
HTML code
<input type="text" name="uname" value="223" />

and CSS code is
input {
  font-size: 100px;
  padding: 0;
  margin: 0;
  /*height: 80px;
  line-height: 80px;*/
}

I've tested this code.


text:
Q: cheetah parsing error trying to change cheetahVarStartToken I am writing a cheetah template and I want to change the cheetahVarStartToken so that I can use the $ for javascript libraries in that section of code however when I run the template I am getting this error

ConfigParser.ParsingError: File contains parsing errors:
      [line  2]: u'\t\t\t cheetahVarStartToken = "%"\n'

here is my code
#compiler-settings
cheetahVarStartToken = "%"
#end compiler-settings

  <script>
   //My javascript code
  </script>

#compiler-settings reset

A: That assignment must start in the first column, so remove the whitespace at the front of cheetahVarStartToken:
This works:
cheetahVarStartToken = "%"

This blows up:
 cheetahVarStartToken = "%"

 ConfigParser.ParsingError: File contains parsing errors: <???>
     [line  2]: ' cheetahVarStartToken = "%"\n'


text:
Q: When adding bordered links, the second link's border appears individually 2 other times
Alright, so the problem is that I wanted two bordered links, but as you can see, there are two extra borders in there which seem to belong to the bookings link, although by looking into the code I did not make the mistake to type the link twice.
EDIT:
added another picture in case my explanation wasn't clear enough. It's the rectangles I'm pointing at that I want to get rid of

I'm sure there's a problem with the divs, but everything I've tried failed.
HTML:

            EXPLORE

            BOOKINGS

CSS:
.button1 {
padding: 0 0 29px 50px;
letter-spacing: 1px;
text-transform: uppercase;
padding: 0 0 29px 0px;
display: inline-block;
float:left;}

.button2 {
padding: 0 0 29px 0px;
letter-spacing: 1px;
text-transform: uppercase;
padding: 0 0 29px 0px;
display: inline-block;}
.buttons a {
background-color: ffaaaa;
color: #832430;
border: 2px solid #832430;
padding: 14px 25px;
text-align: center;
text-decoration: none;
display: inline-block;}
.buttons a:hover{
background-color: #832430;
color: white;
padding: 14px 25px;
text-align: center;
text-decoration: none;
display: inline;}

A: here is your code fixed.

*

*do not repeat yourself, if you have the same properties for different elements use a class.

*you were missing a # in a property background

.btn {
  padding: 0 0 29px 50px;
  letter-spacing: 1px;
  text-transform: uppercase;
  padding: 0 0 29px 0;
  display: inline-block;
}

.buttons a {
  background-color: #faa;
  color: #832430;
  border: 2px solid #832430;
  padding: 14px 25px;
  text-align: center;
  text-decoration: none;
  display:block
}

.buttons a:hover {
  background-color: #832430;
  color: white;
}

    EXPLORE

    BOOKINGS

A: I don't have all the details from what you would like to do so I'll have to update it later.
Option 1: Quick way if you just want double border is to use border and box-shadow.
Option 2: More simple approach for this things is to use ::after selector, research it, your life will be a lot easier, :)!

.buttons a {
    background-color: ffaaaa;
    color: #832430;
    border: 2px solid #832430;
    padding: 14px 25px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    box-shadow: 0px 0px 0px 2px silver; /* one line of code for 2nd border */
    margin: 0 10px;
}

.buttons a:hover{
    background-color: #832430;
    color: white;
    padding: 14px 25px;
}

  EXPLORE
  BOOKINGS

::after selector way

.buttons .button-wrap{
  position: relative;
  display: inline-block;
  width: auto;
  height: auto;
  margin: 0 10px;
}
.buttons a {
    background-color: ffaaaa;
    color: #832430;
    border: 2px solid #832430;
    padding: 14px 25px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
}

.buttons a:hover{
    background-color: #832430;
    color: white;
}

.buttons a::after{
  position: absolute;
  display: inline-block;
  content: "";
  width: 100%;
  height: 100%;
  top: -6px;
  left: -6px;
  margin: 4px;
  border: 2px solid silver;
}

      EXPLORE

      BOOKINGS


text:
Q: Php remaking a table after data is added to the sql database I'm trying to display data from my SQL database unto this page. When I run my code with only one data in the SQL database so if there is only one Wifi to fetch then everything looks normal and works well, but as soon as the user adds another wifi then the table is drawn again on top of the other table
A picture with only one wifi in my database

A picture with only two wifi in my database

Here is my wifi_page.php:
<?php

require_once 'header.php';
require_once 'connect.php';

$sql = "SELECT ID, Name, Password FROM wifi";
$result = $mysqli->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $newWifi = "wifi_register_page.php";
        echo"

                Name
                Password
                +

             ". $row["Name"]. "
            ". $row["Password"]. "

";
    }
} else {
    echo "0 results";
}
$mysqli->close();

require_once 'footer.php'

 ?>

If you need any more code or images just let me know in the comments. Thank you in advance!

A: You need to take the table and the header out of the while, otherwise it will create a new table for each row of your database.
<?php

require_once 'header.php';
require_once 'connect.php';

$sql = "SELECT ID, Name, Password FROM wifi";
$result = $mysqli->query($sql);

if ($result->num_rows > 0) {
    $newWifi = "wifi_register_page.php";
    echo "

                Name
                Password
                +

    ";

    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo"

                 ". $row["Name"]. "
                ". $row["Password"]. "

            ";
    }

    echo '
';
} else {
    echo "0 results";
}
$mysqli->close();

require_once 'footer.php'

 ?>


text:
Q: SQL Server Analysis Services (msmdsrv.exe) command line switches I was wondering if anyone know what are the (undocumented) switches that the SSAS engine (msmdsrv.exe) is using. If I use the -? switch, I can see the following options and their descriptions:
c = console mode
azure = start server with functionality limmited to AS Azure
n <Name> = instance name
i = install (register) MSSQLServerOLAPService service
r = remove (unregister) MSSQLServerOLAPService service
t = registry for event log
s <Dir> = config file directory
f = initialize config file
d <Dir> = root data directory
l<number> = server locale #no space
q = unregistry for event log
b = backup file name
k = encryption password used to create backup file
g = extraction directory pathname
j = test backup file only

However, this isn't the exhaustive list - according to the first line of the output of the -? switch there's also the following switches for which I don't know what they do and how they're used:
m
v <String>
x
x <String>
e <c> <file> #experimented a bit with it, defaults to looking for "deploy_script.xml"; and what is <c> in the first place?
u <c>

I tried disassembling the executable with IDA to see if there's anything useful in there, but I couldn't find anything that would look interesting (I looked at the code surrounding words like "azure", "deploy_script", etc.). With IDA, I can see the output generated by the -? switch but then that's also about it. I should also note that I've never used IDA before...
Alternatively, I'd appreciate if someone could point me to an online resource explaining these switches in detail (I wasn't able to find anything like that).
Thanks!


text:
Q: Signal Dequantization via Convex Optimization How could one prove the following problem?
Given a vector $\mathbf{y}=\left(y_{k}\right) \in \mathbb{R}^{n},$ we consider the energy function $E: \mathbb{R}^{n} \rightarrow \mathbb{R}$ defined by
$$
\forall \mathbf{x}=\left(x_{k}\right) \in \mathbb{R}^{n}, \quad E(\mathbf{x})=\sum_{i=1}^{n-1}\left(x_{k+1}+x_{k-1}-2 x_{k}\right)^{2}
$$
and the set
$$
C=\left\{\mathbf{x} \in \mathbb{R}^{n}, \forall k \in \mathbb{N}, 1 \leq k \leq n,\left|x_{k}-y_{k}\right| \leq q\right\}
$$
where $q$ is a fixed positive real number.

*

*Compute the gradient of $E$

*Show that $E$ is convex.

*Show that $C$ is convex.

*Give an explicit formula for $\pi_{C}(\mathbf{x}),$ the projection on $C$ of a vector $\mathbf{x} \in \mathbb{R}^{n}$.

Background:
In this project we are given a temperature signal $\mathbf{y}=\left(y_{k}\right) \in \mathbb{R}^{n},$ where $y_{1}, y_{2}, \ldots, y_{n}$ represent the temperature measured at different times. Due to the poor resolution of the measure, the signal is quantized, in the sense that all measured values $y_{k}$ are multiples of $1 / 2 .$ the aim of the project is to build a non-quantized signal $\mathbf{x}=\left(x_{k}\right) \in \mathbb{R}^{n}$ that is smoother than $\mathbf{y}$ and has the property that $\left|x_{k}-y_{k}\right| \leq 1 / 4$ for all $k$  (so that the quantized version of $ \mathbf{x} $ is $ \mathbf{y}$.

A: Given the vector $ \boldsymbol{y} \in \mathbb{R}^{n} $ consider the Energy Function:
$$ E : \mathbb{R}^{n} \to \mathbb{R}, \; E \left( \boldsymbol{x} \right) = \sum_{k = 2}^{n} {\left( {x}_{k + 1} + {x}_{k - 1} - 2 {x}_{k} \right)}^{2} $$
And the set:
$$ \mathcal{C} = \left\{ \boldsymbol{x} \in \mathbb{R}^{n} \mid k \in \left\{ 1, 2, \ldots, n \right\}, \; \left| {x}_{k} - {y}_{k} \right| \leq q \right\} $$
The Gradient of $ E \left( \boldsymbol{x} \right) $
One could see that $ E \left( \boldsymbol{x} \right) $ could be written in Matrix Form:
$$ E \left( \boldsymbol{x} \right) = {\left\| A x \right\|}_{2}^{2} $$
Where the matrix $ A \in \mathbb{R}^{ \left( n - 2 \right) \times n } $ is given by:
$$ \begin{bmatrix}
1 & -2 & 1 & 0 & \ldots & 0 & 0\\
0 & 1 & -2 & 1 & 0 & \ldots & 0 \\
 &  & \vdots &  & \\
0 & 0 & \ldots & 0 & 1 & -2 & 1
\end{bmatrix} $$
So the gradient is given by:
$$ \frac{\partial E }{\partial \boldsymbol{x}} = {A}^{T} A x $$
Convexity of $ E \left( \boldsymbol{x} \right) $
The function $ E \left( \boldsymbol{x} \right) $ is convex since it is a norm of a Linear Term of $ \boldsymbol{x} $ which means its Hessian Matrix (Which is given by $ {A}^{T} A $) is a Positive Semi Definite (PSD) Matrix.
Convexity of the Set $ \mathcal{C} $
The set $ \mathcal{C} $ is basically a shifted $ {L}_{\infty} $ ball. Since a shift in space doesn't affect convexity and it is known that the $ {L}_{\infty} $ Ball is convex (See How to Prove the $ {L}_{\infty} $ Ball Is Convex?) the set is convex.
Projection onto the Set $ \mathcal{C} $
Since the set is a shifted version of the $ {L}_{\infty} $ ball one could use the known projection - Orthogonal Projection onto the $ {L}_{\infty} $ Unit Ball.
Basically in this case it means the projection, component wise, is given by:
$$ {{\pi}_{ \mathcal{C} } \left( \boldsymbol{x} \right)}_{k} = \begin{cases}
{y}_{k} + q & \text{ if } {x}_{k} - {y}_{k} > q  \\
{y}_{k} - q & \text{ if } {x}_{k} - {y}_{k} < -q \\
{x}_{k} & \text{ if } \left| {x}_{k} - {y}_{k} \right| \leq q
\end{cases} $$


text:
Q: Select element by (new) ID from AJAX response with jQuery Is it possible to select an element with an ID that was not in the HTML page prior to an AJAX update?
Example (semi-pseudo code and much simpler than the code I have the problem with):
The page is loaded and contains this div:

    <button onclick="hideElement('oldID')"></button>
    <element id="oldID"></element>

Then I call an AJAX function to update the div to this

    <button onclick="hideElement('newID')"></button>
    <element id="newID"></element>

The javascript function:
hideElement(id)
{
    $('#' + id).fadeOut();
}

When I view the page source in Chrome after the AJAX update I can not see the change (newID is not there, it is still oldID etc.). According to what I have read, this is normal.
In my case the $('#' + id) (when id = 'newID') does not give me the element. Is this normal?


text:
Q: UITableView Reload Not Updating the tableview with DispatchQueue.main.async I have written code with swift4 and running on iPhone simulator.
DispatchQueue.main.async {
     self.view.activityindicatorStop()
     self.mytableView.reloadData()
}

Above code has following operation
Stoping Activity indicator and update TableView after data filling with array..
But expected does not happen..
I got following

*

*Activity indicator stoped but indicator not
removed and background view not removed.

*TableView not updated.

code i have used:
 super.viewDidLoad()

        UserDefaults.lastAccessDate = Date()

        self.view.activityStartAnimating(activityColor: #colorLiteral(red: 0.9176470588, green: 0.2901960784, blue: 0.262745098, alpha: 1), backgroundColor: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0))

       //Calling the API
      Capsulle.retriveSpaceTimeCapsulle { (data, respose, error) in
        if nil == error
        {
         let ServerData = serverComm.toJSONObject(with: data!)
         let result = ServerData.0 as? Array<Dictionary<String, Any>>
         self.capsulleDetail = result

        if (result == nil)
        {
            if false ==  loginCredential.isHavingAccessToken
            {
            loginCredential.isHavingAccessToken = false;
            UserDefaults.standard.set( "", forKey: "UserEmailID")
            let objStoryBoard:UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
            let initialViewController:UIViewController = objStoryBoard.instantiateViewController(withIdentifier: "loginVC")

            self.present(initialViewController, animated: true, completion: {

            })

            return
            }
        }

         DispatchQueue.main.sync {

            self.CapsulleCollectionView.reloadData()

            self.view.activityStopAnimating()

         }
         }

      }

    }

func activityStartAnimating(activityColor: UIColor, backgroundColor: UIColor) {
        let backgroundView = UIView()
        backgroundView.frame = CGRect.init(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height)
        backgroundView.backgroundColor = backgroundColor
        backgroundView.tag = 475647

        var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
        activityIndicator = UIActivityIndicatorView(frame: CGRect.init(x: 0, y: 0, width: 50, height: 50))
        activityIndicator.center = self.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
        activityIndicator.color = activityColor
        activityIndicator.startAnimating()
        self.isUserInteractionEnabled = false

        backgroundView.addSubview(activityIndicator)

        self.addSubview(backgroundView)
    }

func activityStopAnimating() {
    if let background = self.viewWithTag(475647){

        background.removeFromSuperview()
    }
    self.isUserInteractionEnabled = true
}

i have created activityStopAnimating and activityStartAnimating  as extensions

A: For tableView to reload you have to make sure that self.capsulleDetail  have data  changed if this array is your data source
i think it not changed or still zero so reloadData()  will do nothing
To hide indicator you should set this property to hide it when stop or hide it directly by sting is-hidden to true
self.activityIndicator.hidesWhenStopped = true

A: DispatchQueue.main.async {
    self.view.activityIndicator.stopAnimating()
    self.view.activityIndicator.isHidden = true
    self.mytableView.beginUpdates()
    self.mytableView.endUpdates()
}

your code should work for tableView reload but you can also try using beginUpdates() and endUpdates() method. and to stopActivityindicator call stopAnimating() and then hide your activityindicator this code should work for you
Enjoy coding.

A: I don't Find any correct solutions to do this perfectly..
after long run i decided to do following and it is working some what i expect..
DispatchQueue.main.async {
                        // now update UI on main thread

                        self.myTableView.reloadData()
                        self.myTableView.setContentOffset(CGPoint(x: 0, y: -1), animated: true)
                        self.view.activityStopAnimating()

                    }

Thanks for all of your answers..i am awaiting for perfect answer..


text:
Q: Having trouble dealing with Moment JS (Angular) I am having trouble with Moment JS.  Basically, I have some metadata for a radio station, and in my php call, I get in return the 'duration' of the song, the 'timestamp' when the song started.
I did some calculation with Moment JS to get the time when the song will be finished, and then I find the difference. However, the difference is returning a negative number, which then breaks the app.
If someone can help me that would be great.
This is my plunk http://plnkr.co/edit/joVLYdTKY5dZBOTNfTOI
Services
angular.module('starter', [])

.run(function(CurrentTrack){
   CurrentTrack.refreshTrackData();
})

.controller('radioCtrl', function($scope,CurrentTrack) {
   console.log(CurrentTrack);
   $scope.CurrentTrack = CurrentTrack;
})

.service('CurrentTrack',function(radioData,$timeout){

   var currentTrack = this;

   this.setTrackData = function(trackData){

      currentTrack.coverUrl = trackData.cover_url;
      currentTrack.title = trackData.title;
      currentTrack.artist = trackData.artist;
      currentTrack.duration = moment.duration(parseInt(trackData.duration));
      currentTrack.startedAt = moment.unix(trackData.timestamp);
      currentTrack.finishesAt = moment(this.startedAt.add(this.duration));
      currentTrack.updateIn = this.finishesAt.diff(moment());

      currentTrack.refreshing = false;
      return currentTrack.updateIn;
   }

   this.refreshTrackData = function(){
      currentTrack.refreshing = true;
      return radioData.refresh()
         .then(currentTrack.setTrackData.bind(currentTrack))
         .then(currentTrack.scheduleUpdate);
   }

   this.scheduleUpdate = function(ms){
      console.log(ms)
      $timeout(function(){
         currentTrack.refreshTrackData()
      },ms);
      return;
   }
})

Factory
.factory('radioData', function($http,$timeout) {
   var retries = 0;

   function parseResponse(response){
      retries = 0;
      if(!response.data.results){
         console.log('no results')
         return false;
      }
      console.log('refreshed...')
      return response.data.results[0];
   }

   function makeRequest(){
      console.log('refreshing...')
      return $http.get('http://radio-sante-animale.fr/blah11.php?  callback=jsonpCallback')
   }

   function retry(errResponse){
      console.error('timed out');
      //wait for a sec
      retries++;
      if(retries > 5){
         throw new Error('timed out after 5 attempts!');
      }
      //oops
      return $timeout(makeRequest,1000).then(null,retry);
   }

   var radioData = {
      refresh: function() {
         return makeRequest()
           .then(null,retry)
           .then(parseResponse)
           .catch(function(err){
               console.log(err);
           });
      }
   };
   return radioData;
});

A: First I changed:
currentTrack.finishesAt = moment(this.startedAt.add(this.duration));

to:
currentTrack.finishesAt = moment(currentTrack.startedAt).add(currentTrack.duration);

In the original code you are mutating the startedAt time then cloning. I also changed all the this to currentTrack to make it more consistent.
The problem
The bug manifests when there is a difference in the time the server is keeping and the time that the client is keeping, (not because you have anything reversed).
Basically the server sends you trackData.timestamp which you parse and convert into a moment to use as your startedAt time. Then you change the trackData.duration into a moment.duration and add it to the startedAt time to get your finishesAt time.
If the time that the client is keeping is running ahead the server's time, the calculated finishesAt time will be earlier than when the actual song ends. An exaggerated example makes this more clear.

var app = angular.module('app', []);

app.controller('myController', function($scope, $timeout, $interval, Server) {
  function updateTime() {
    $scope.serverTime = moment().subtract(1,'s');
    $scope.clientTime = moment();
  }

  function refreshInfo() {
    Server.getSongInfo().then(parseInfo).then(scheduleRefresh);
  };

  function parseInfo(trackData) {
    $scope.songInfo = trackData;
    var startedAt = trackData.timestamp;
    $scope.finishesAt = moment(startedAt).add(trackData.duration, 'ms');
    $scope.updateIn = $scope.finishesAt.diff(moment());
    return $scope.updateIn;
  }

  function scheduleRefresh(updateIn) {
    if (updateIn < 0) {
      $scope.bugged = true;
    } else {
      $scope.bugged = false;
    }
    $timeout(refreshInfo, updateIn);
  }

  $scope.songInfo = "loading";
  updateTime();
  refreshInfo();

  $interval(updateTime, 1000);
});

app.service('Server', function($timeout, $interval) {
  var song = {
    duration: 5000
  };

  this.getSongInfo = function() {
    return $timeout(function() { return this.trackData });
  };

  function nextSong() {
    this.trackData = {
      duration: song.duration,
      timestamp: moment().subtract(1,'s')
    };
  }

  nextSong();

  $interval(nextSong, song.duration);
});
.container {
  display: flex;
  flex-flow: row wrap;
}
.row {
  display: flex;
  flex-direction: row;
  flex-flow: space-around;
  width: 100%;
}
.col {
  margin: auto;
  text-align: center;
}
.red {
  background-color: red;
}

Song Info

{{ songInfo }}

Server

{{ serverTime.format("hh:mm:ss") }}

Finishes At

{{ finishesAt.format("hh:mm:ss") }}

Update In

{{ updateIn }}

Client

{{ clientTime.format("hh:mm:ss") }}

Whenever the song info div is red, the client is in the loop where it is requesting new track info and parsing out a finish time that is earlier than the current moment, which immediately makes it request new track info.

angular.module('starter', [])

.run(function(CurrentTrack) {
  CurrentTrack.refreshTrackData();
})

.controller('radioCtrl', function($scope, CurrentTrack) {
  $scope.CurrentTrack = CurrentTrack;

})

.service('CurrentTrack', function(radioData, $timeout) {

  var currentTrack = this;

  this.setTrackData = function(trackData) {
    currentTrack.coverUrl = trackData.cover_url;
    currentTrack.title = trackData.title;
    currentTrack.artist = trackData.artist;
    currentTrack.duration = moment.duration(parseInt(trackData.duration));
    currentTrack.startedAt = moment.unix(trackData.timestamp);
    currentTrack.finishesAt = moment(currentTrack.startedAt).add(currentTrack.duration);
    currentTrack.updateIn = currentTrack.finishesAt.diff(moment())

    console.log(currentTrack, trackData);
    currentTrack.refreshing = false;
    return currentTrack.updateIn;
  }

  this.refreshTrackData = function() {
    currentTrack.refreshing = true;
    return radioData.refresh()
      .then(currentTrack.setTrackData)
      .then(currentTrack.scheduleUpdate);
  }

  this.scheduleUpdate = function(ms) {
    console.log("update in " + ms)
    $timeout(function() {
      currentTrack.refreshTrackData()
    }, ms);
    return;
  }
})

.factory('radioData', function($http, $timeout) {

  var retries = 0;

  function parseResponse(response) {
    retries = 0;
    if (!response.data.results) {
      console.log('no results')
      return false;
    }
    console.log('response parsed.')
    return response.data.results[0];
  }

  function makeRequest() {
    console.log('making request.')
    return $http.get('http://radio-sante-animale.fr/blah11.php?callback=jsonpCallback')
  }

  function retry(errResponse) {
    console.error('timed out');
    //wait for a sec
    retries++;
    if (retries > 5) {
      throw new Error('timed out after 5 attempts!');
    }
    //oops
    return $timeout(makeRequest, 1000).then(parseResponse, retry);
  }

  var radioData = {
    refresh: function() {
      return makeRequest()
        .then(parseResponse, retry)
        .catch(function(err) {
          console.log(err);
        });
    }
  };
  return radioData;
});
<!DOCTYPE html>

Current Music Information

refreshing...

    Title : {{ CurrentTrack.title }}

Artist : {{ CurrentTrack.artist }}

The song started at {{ CurrentTrack.startedAt }}

Duration of the song {{ CurrentTrack.duration.asSeconds() }} seconds

Finishes At {{ CurrentTrack.finishesAt }}

Update In {{ CurrentTrack.updateIn }}

I'm actually not sure the best approach to fixing this problem but hopefully some one has a better answer.
A hack solution is to add more time (some acceptable amount of error) to the finishesAt to give a little leeway.
currentTrack.finishesAt = moment(currentTrack.startedAt).add(currentTrack.duration).add(1, 's');

A: From my side, it worked by adding Math.abs in your $timeout method
this.scheduleUpdate = function(ms) {
    console.log( 'update in :' + ms)
    $timeout(function() {
        currentTrack.refreshTrackData()
    }, Math.abs(ms));
    return;
}

A: From http://momentjs.com/docs/#/displaying/difference/

If the moment is earlier than the moment you are passing to
  moment.fn.diff, the return value will be negative.

You need to reverse the dates in your diff.
EDIT: Like this -
currentTrack.updateIn = moment().diff(this.finishesAt);


text:
Q: Batch checking the last character I have a problem in a folder which contains sql files.
I want to check that the last line of each file contain only one slash '/' (without any spaces after that) and if there is issue to write in the output that an error is raised
ie     1.sql   error
       5.sql   error
Is there any easy way to do it with a batch file ?
Thank you in advance

A: This should do it :
@echo off&cls

setlocal enabledelayedexpansion

for %%a in (*.sql) do (echo Treating =^> %%a
    for /f "delims=" %%b in ('type "%%a"') do (
        set "$Line=%%b"
    )
    echo   - Last Char =^> [!$Line:~-1!]
    if not "!$Line:~-1!"=="/" (
        echo   - Result =^> error %%~nxa
        ) else (
        echo   - Result =^> OK %%~nxa
        )
    echo.^****
)


text:
Q: Schedule model saving data multiple times My function is running more than once it is saving the task multiple times. I cannot understand whether it is a server issue or some issue with the while loop. What I want is that my function should just run once and save the task to my django model. My code is below
    global test
    def test():
        print("The recursive task has been created and saved")
        task3 = Tasks(Users=user, Description=description, TOA=toa, TOE=toe, ETC=etc)
        task3.save()

    run_code="schedule.every()."+eday+".at(etime).do(test)"
    exec(run_code)

    while True:
        schedule.run_pending()
        time.sleep(1)