text:
Q: loop statement breaking please why is the loop statement breaking, after the multiplication it only update the last row, tried using a foreach loop for the $totalprice in the update statement it says invalid argument.
if(array_key_exists('item', $_POST)){

// $items = $_POST['item'];
  //foreach($_POST['item'] as $item){
    //echo $item['Pquantity'] . ", ";
    //echo $item['Pidno'] . ", ";
   // }
    //Loop through $_POST items, updating the database for each item
    foreach ($_POST['item'] as $item) {
        $Pquantity = intval($item['Pquantity']);
        $Pidno = ($item['Pidno']);
        //echo $Pquantity . ", ";
        //echo $Pidno . ", ";
        //$totalprice = intval($item['Pquantity'])
        $queryreg = mysql_query("
            UPDATE repplac
                 SET Pquantity = {$Pquantity}
                 WHERE
                       Pidno = '{$Pidno}'
                 AND
                       Uname = '{$_SESSION['username']}'
        ") or die(mysql_error());

    }
    }
    $pplresult = mysql_query("SELECT * FROM repplac WHERE Uname = '{$_SESSION['username']}'") or die(mysql_error());
  while ($row = mysql_fetch_assoc($pplresult))
  {
  $totalprice = $row['Price'] * $row['Pquantity'];
  //echo "$totalprice";
  //die();
   $queryreg = mysql_query("
  UPDATE repplac
  SET Tprice = {$totalprice}
  WHERE
                       Pidno = '{$Pidno}'
                 AND
                       Uname = '{$_SESSION['username']}'
    ") or die(mysql_error());
  }

A: Neither arguments in the second condition gets changed inside the loop:
WHERE
                   Pidno = '{$Pidno}'
             AND
                   Uname = '{$_SESSION['username']}

Perhaps you forgot to update $Pidno?
Also, I don't think the following is safe:
"SELECT * FROM repplac WHERE Uname = '{$_SESSION['username']}'"

You might want to sanitize $_SESSION['username'] before passing it to the query.

A: Inside your foreach you update $Pidno with the following code
$Pidno = ($item['Pidno']);

Thus you are updating different records in the database. But inside your while loop $Pidno is staying the same the entire time. Thus you are updating the same record over and over. To fix this add the following code at the beginning of the while loop
while ($row = mysql_fetch_assoc($pplresult))
{
    //get the correct Pidno for this row
    $Pidno = ($row['Pidno']);
    $totalprice = $row['Price'] * $row['Pquantity'];

    // ... the rest of your while loop


text:
Q: How to link multiple tables in Joomla 2.5 Component? I am trying to create a component which uses 3 tables in the database. I want to link the first table with the second one, then second with third.
To be more precise, consider this :

*

*Category: id, name

*Sub category: id, category_id, name

*Sub sub category: id, subcategory_id, name
I have created models, controllers and views for all the three tables. Just want to know how to link them together so that on the list view of Categories, I can have a link for subcategories and on clicking on that link, I can show the subcategories for the category.
I have googled this for almost 3 days now. But can't find an answer.
Any help is appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing desktop extension for a multi instance uwp app I followed this article to add desktop extension for my uwp app which is multi-instance. But I am getting deployment errors:
Deployment Error Prompt
Error   DEP0700: Registration of the app failed. [0x80073CF6] AppxManifest.xml(79,10): error 0x80080204: Cannot register the package because EntryPoint must be specified when SupportsMultipleInstances is true.
If I provide entrypoint same as my uwp app(UWP.App in this case) although there is no deployment errors but the appserviceconnection fails with this message:
App not available
Any suggestion how I should go about this??
[Edit]
I made an out-proc AppService as described in this article and started it from full trust process following the same procedure in the article. But I can't seem to find any way to capture its instance from my uwp app. Any help??

A: Create out-of-proc appservice as described here. Disable multi-instance for out-of-proc service. For each instance of uwp app create a new service. Create a static field in the background task class to store the appservice for desktop extension and initialize it when you create appservice from the desktop extension. Then you can pass messages from uwp app instances to out-of-proc appservice and then from appservice to desktop extension.

A: I am afraid the steps you are following are not applicable to multi-instance UWP apps, because in-proc AppService is not supported for multi-instance apps. This is documented here:
https://learn.microsoft.com/en-us/windows/uwp/launch-resume/multi-instance-uwp#background-tasks-and-multi-instancing
You can still launch a fulltrust process (desktop extension) from your multi-instance apps, but the cross-process communication as explained in the article you are following does not apply here. It's limited to standard, single-instance UWP applications.


text:
Q: Setting Tesseract.js data location I built a server with Adonis.js and Typescript that downloads an image from the web and performs OCD on it with Tesseract.js. The program works, but every time a new Tesseract worker gets initialized this error shows up:

The eng.traineddata is being generated and stored in the root folder of the project, but Tesseract still can not find it for some reason. I also tried creating a "tessdata" folder in the root directory and setting the TESSDATA_PREFIX to its path, but that did not help either. Wondering if there is a simpler way to solve this issue.


text:
Q: How can I delete a single entry from a table I have a listbox with usernames, and a remove button I want the selected a user (with all entered data associated with that user) to be deleted when the remove button is clicked.
My code
SqlConnection con = new SqlConnection("Data Source=JAMES-PC\\SQLEXPRESS;Initial Catalog=staff;Integrated Security=True");
con.Open();

string sql = @"DELETE FROM staff1;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();

this code deletes the whole table.
How can I just delete the selected user?

A: You need a WHERE clause to select the required record. You have to get the username of the selected user to be deleted and pass it to @UserName parameter.
 var userName = (listBox.SelectedItem as DataRowView)["UserName"].ToString();
 string sql = @"DELETE FROM staff1 WHERE Username = @UserName;";

 SqlCommand cmd = new SqlCommand(sql, con);
 cmd.Parameters.AddWithValue("@UserName",useName);

 cmd.ExecuteNonQuery();
 con.Close();

See this thread on how to use parameters in the SQL.

A: When you execute a delete query, in order to delete only 1 row from the table you need to add a WHERE clause.
Based on the comments the workflow should be something like: you click on a delete button, you send the name of the staff you want to delete to the command, which looks like:
 string sql = @"DELETE FROM staff1 where Name=@Name;";

 SqlCommand cmd = new SqlCommand(sql, con);
 cmd.Parameters.AddWithValue("@Name","NameReceivedFromList");

 cmd.ExecuteNonQuery();
 con.Close();

A: When you are deleting you should remember to add a Where clause, it is actually very powerfull here is some examples that will get you started
The following query will delete only one element
DELETE FROM Table WHERE Table.PrimaryField = Value

The following query will delete all items that matches
DELETE FROM Table WHERE Table.Field = Value

You can also have a join in your delete statement for more complex delete queries
DELETE A FROM Table A
INNER JOIN TableB B ON A.Key = B.Key
WHERE B.PrimaryField = Value


text:
Q: Vue router optional first parameter I have a list of routes that can all have an optional first parameter. If the parameter is present in the url, it will change a header I use in my api calls. Everything else remains the same.
Rather than create two sets of routes to handle this, is there a way I can list the first parameter as optional and only define my routes once?
For all routes, there can be an :environment param present in the front:
/:environment/:event_identifier/register/pages/:page_uuid

or it can be:
/:event_identifier/register/pages/:page_uuid

Everything else will remain the same.
let routes = [{
   path: '/:event_identifier/register/pages/:page_uuid',
   name: 'ContentPage',
   component: ContentPage,
   meta: {
      requiresAuth: true,
   },
}, {
   path: '/:event_identifier/register/:pagenum',
   name: 'Register',
   component: Register,
   meta: {
      requiresAuth: true,
   },
}, {
   path: '/:event_identifier',
   name: 'Login',
   component: Login,
   children: [{
      path: '/:event_identifier/:registration_uuid/:pagenum',
      name: 'editRegistration',
      component: Login,
   }]
}]

A: You can declare an optional param like this:
path: '/myroute/:param?'

The ? after :param makes it optional, so it will match http://domain/myroute with no param or http://domain/myroute/25 with a param.
But, I would suggest making your optional params last on each route. Otherwise, you get some unclear behavior. Imagine you had a route path like this with an optional first param..
path: '/myroute/:optional?/:notoptional'

If you visit http://domain/myroute/25/100, the 25 would match :optional?
But if you visit http://domain/myroute/25, the 25 would match :notoptional


text:
Q: Creating XML nodes based on XPATH I have a requirement to add XML nodes using XPATH. I got the below XSLT, from another thread in stackoverflow, which does the job.
But I am facing one issue where if we are not maintaining the order of XPATH in XSLT then it is creating same XML tags multiple times. Please refer below sample XML and XSLT to understand it better. Kindly help to resolve this issue.
Input XML:
<header>
  <txCtry>SG</txCtry>
  <msgId>b626c6be4a724f8aa92dcba1b4e07cf0</msgId>
</header>
<data>
  <txCtry>SG</txCtry>
  <txCityCd>SIN</txCityCd>
</data>

XSLT:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:my="my:my">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vPop" as="element()*">
<item path="/header/txCtryyyy">F</item>
<item path="/header/btchBookg">ddddddddddddd</item>
<item path="/data/txSttlmInf/instgRmbrsmntAgt/BICFIIIIII">FXZ9200136548878</item>
<item path="/header/prcgSubSts">ooooooooooooooo</item>
 </xsl:variable>

 <xsl:template match="/">
  <xsl:sequence select="my:subTree($vPop/@path/concat(.,'/',string(..)))"/>
 </xsl:template>

 <xsl:function name="my:subTree" as="node()*">
  <xsl:param name="pPaths" as="xs:string*"/>

  <xsl:for-each-group select="$pPaths"
    group-adjacent=
        "substring-before(substring-after(concat(., '/'), '/'), '/')">
    <xsl:if test="current-grouping-key()">
     <xsl:choose>
       <xsl:when test=
          "substring-after(current-group()[1], current-grouping-key())">
         <xsl:element name=
           "{substring-before(concat(current-grouping-key(), '['), '[')}">

          <xsl:sequence select=
            "my:subTree(for $s in current-group()
                         return
                            concat('/',substring-after(substring($s, 2),'/'))
                             )
            "/>
        </xsl:element>
       </xsl:when>
       <xsl:otherwise>
        <xsl:value-of select="current-grouping-key()"/>
       </xsl:otherwise>
     </xsl:choose>
     </xsl:if>
  </xsl:for-each-group>
 </xsl:function>
</xsl:stylesheet>

Transformed XML:
<header>
   <txCtryyyy>F</txCtryyyy>
</header>
<data>
   <txSttlmInf>
      <instgRmbrsmntAgt>
         <BICFIIIIII>FXZ9200136548878</BICFIIIIII>
      </instgRmbrsmntAgt>
   </txSttlmInf>
</data>
<header>
   <btchBookg>ddddddddddddd</btchBookg>
</header>
<data>
   <txSttlmInf>
      <instgRmbrsmntAgt>
         <BICFHHHH>FXZ92001365kkkkkkkk48878</BICFHHHH>
      </instgRmbrsmntAgt>
   </txSttlmInf>
</data>
<header>
   <prcgSubSts>ooooooooooooooo</prcgSubSts>
</header>

Here we can see header and data tags getting created multiple times.
Expected output:
<header>
   <txCtryyyy>F</txCtryyyy>
   <btchBookg>ddddddddddddd</btchBookg>
   <prcgSubSts>ooooooooooooooo</prcgSubSts>
</header>
<data>
   <txSttlmInf>
      <instgRmbrsmntAgt>
         <BICFIIIIII>FXZ9200136548878</BICFIIIIII>
         <BICFHHHH>FXZ92001365kkkkkkkk48878</BICFHHHH>
      </instgRmbrsmntAgt>
   </txSttlmInf>
</data>

A: Try to use group-by instead of group-adjacent in the function where you have <xsl:for-each-group select="$pPaths" group-adjacent="substring-before(substring-after(concat(., '/'), '/'), '/')">, try to use  <xsl:for-each-group select="$pPaths" group-by="substring-before(substring-after(concat(., '/'), '/'), '/')">.


text:
Q: Unnumbered equations: Any difference between \begin{equation*} and \[? Is there a difference between defining an unnumbered equation with
Option 1:
\begin{equation*} ...  \end{equation*}

versus
Option 2:
\[ ...  \]

If there are differences, they are not apparent in my use of the commands.


text:
Q: AS3 - Removing event listener failed here's my code, i don't know why it doesn't remove the event listener.
What i want to do is having some button to turn the sound on and off according to the beat. On the first click it worked perfectly, but when i want to remove the sound on the second click it cannot remove the event listener.
plat.BEAT1.addEventListener(TouchEvent.TOUCH_BEGIN, BEATDown(plat.BEAT1, hihatz, 2));
plat.BEAT2.addEventListener(TouchEvent.TOUCH_BEGIN, BEATDown(plat.BEAT2,cymbalz, 4));

function BEATDown (padNum, sounz, tiempo) {

    return function (e:TouchEvent) {

        var currentSound:Sound = null;
        var currentSoundChannel:SoundChannel;
        var active:int;

        if (padNum.currentFrame == 1) {
            padNum.gotoAndStop(3);
            padNum.addEventListener(Event.ENTER_FRAME, PlayBeats);
            active = 1;

        } else {
            padNum.gotoAndStop(1);
            padNum.removeEventListener(Event.ENTER_FRAME, PlayBeats);
            active = 0;
        }

        function playSound(sound:Sound):void
            {

                if (active == 0)
                {
                    // Stop playing ANY sound
                    currentSound = null;
                    currentSoundChannel = null;
                }
                else
                {
                    // Play a different sound
                    currentSound = sound;
                    currentSoundChannel = sound.play();
                }
            }

        function PlayBeats(event:Event):void
            {

                if (tiempo == 1) {
                    if (fl_SecondsElapsed <= 4) {
                        playSound(sounz);
                    }
                }
                if (tiempo == 2) {
                    if (fl_SecondsElapsed == 1 || fl_SecondsElapsed == 3) {
                        playSound(sounz);
                    }
                }
                if (tiempo == 4) {
                    if (fl_SecondsElapsed == 1) {
                    playSound(sounz);
                }

                }

            }

    }

}

EDIT:
The listener i want to remove is padNum.addEventListener(Event.ENTER_FRAME, PlayBeats);
plat.BEAT1 is the button instance. I use multiple instance to trigger different sound, each toggle sound on and off according to the Tiempo count.

A: I would say it's because you don't add / remove your listener on the same object;
is plat.BEAT1 et plat.BEAT2 are the same? I guess not.
I would recommend you to try by adding the EnterFrame listener on stage on this or on the parent element to the if the event is Removed correctly. Then if you want your object works independently, try to target the right object.
if (padNum.currentFrame == 1) {
    padNum.gotoAndStop(3);
    stage.addEventListener(Event.ENTER_FRAME, PlayBeats);
    active = 1;
} else {
    padNum.gotoAndStop(1);
    stage.removeEventListener(Event.ENTER_FRAME, PlayBeats);
    active = 0;
}


text:
Q: Proving that if $\;5\mid(a+11)\;$ and $\;5\mid(16-b),\;$ then $\;5\mid(a+b)$ Can you please help me a bit with this question?

How do we show that $\;$ if $\;\;5\mid(a+11)\;$ and $\;5\mid(16-b),\;\;$ then $\;5\mid(a+b)\;$?

Thanks a lot!

A: In general, for integers $a, b, n,$
$$n\mid a \;\;\text{and} \;\; n\mid b \quad \implies \quad n\mid (x - y)\tag{1}$$
So, if $5|(a+11)$ and $5|(16-b)$, then $5\mid [(a + 11)-(16-b)]\tag{by $(1)$}$
$$\iff 5\mid ((a + b) - 5) $$ $$\iff 5\mid (a + b),\;\; \text{ because}\;\; 5\mid -5\; $$ $$\therefore\quad 5\mid (a + b)\quad \checkmark$$

A: Since $5 \mid (a+11)$, let $$(a+11) = 5m. \tag{1}$$
Again since $5 \mid (16-b)$, let $$(16-b) = 5n.\tag{2}$$
(1) - (2) gives you: $$(a+b-5) = 5(m-n) \quad \Rightarrow \quad (a+b) = 5(m+n+1).$$
Hence $5$ divides $(a+b)$ or $5 \mid(a+b)$.
Hope the answer is clear!

A: Hint $\rm\ \ \ \ 5\mid \color{#C00}{11\!+\!a},\color{#0A0}{b\!-\!16}\:\Rightarrow\: 5\mid 5\!+\!\color{#C00}{11\!+\!a}\!+\!\color{#0A0}{b\!-\!16} = a\!+\!b.\ $ Alternatively
$\rm\ mod\ 5\!:\, \ a\equiv -11,\ b\equiv 16\:\Rightarrow\: a\!+\!b \equiv -11\!+\!16\equiv 5\equiv 0$

A: Hints:
$$5\mid (a+11)\iff a=4\mod 5$$
$$5\mid(16-b)\iff b=1\pmod 5$$
so...

A: $a|b$ can be written as $b \equiv 0 \pmod{a}$. So our two assumptions can be written as
$$
a+11 \equiv 0 \mod 5\\
16-b \equiv 0 \mod 5
$$
Subtracting the second equivalence from the first one, we have
$$
a+b-5 \equiv 0 \mod 5
$$
But of course, $5\equiv 0 \pmod5$, so we have
$$
a+b \equiv 0 \mod 5
$$
Therefore, $5|a+b$.


text:
Q: Enabling ProGuard in Android I plan on using ProGuard to obfuscate the code of my Android app. I have been researching about it. Most of the articles and videos on YouTube seem to be out dated. From all what I have gathered, here is what need to be done:

*

*In the project.properties class I will have to uncomment the line:
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt

*I am using Crashlytics and it says that to have informative stack traces, I must add a line to ProGuard configuration:
-keepattributes SourceFile,LineNumberTable
I am guessing that the above line is appended to proguard-project.txt?
And then that's it. Please correct me where I am wrong.

A: *

*Correct. In your project.properties you need to define the
path/filename for your Proguard configuration file, e.g.
proguard.config=proguard-project.txt

(in this case proguard-project.txt sits in the project's root folder)

*Also correct. As per the Proguard documentation:

-keepattributes [attribute_filter]
Specifies any optional attributes to be preserved.
...
You should also keep the SourceFile and LineNumberTable
  attributes for producing useful obfuscated stack traces. Finally, you
  may want to keep annotations if your code depends on them. Only
  applicable when obfuscating.


text:
Q: Swift - Alamofire .POST with parameters problem I want to sent a request with parameters, and I've a problem with the parameters sequence. I need to sent something like that:
 let parameters: Parameters = [
                     "name":"someName",
                     "parameters": {
                        "searchingMore": "[{\"name\": \"\(items.name)\",\"surname\": \"\(items.surname)\"}]"
                }] as Dictionary

And I'm always getting the Consecutive statements on a line must be separated by ';' and Expected expression problem on the searchingMore line.
I just want to know how to send the table as a parameter.

A: Try replacing the scopes {} with [] as follows -
let parameters: Parameters = [
            "name":"someName",
            "parameters": [
                "searchingMore": "[{\"name\": \"\(items.name)\",\"surname\": \"\(items.surname)\"}]"
            ]
        ] as Dictionary


text:
Q: Zf2 Form dependent on userId I want to create a dropdown unique to the users, and found a way to do that, but its not ok with the client.
here is what i`ve done:
 public function __construct($name = null, EntityManager $em = null, $userId = null)
 {

    parent::__construct($name);
    $this->setAttribute('method', 'post');

    [...]
 $this->add(array(
        'name' => 'religionId',
        'type' => 'DoctrineModule\Form\Element\ObjectSelect',

        'options' => array(
            'object_manager' => $this->getEntityManager(),
            'target_class' => 'Religions\Entity\Religions',
            'property' => 'name',
            'disable_inarray_validator' => true,
            'by_reference' => false,
            'is_method' => true,
            'find_method' => array(
                'name' => 'findBy',
                'params' => array(
                    'criteria' => array('reUserId' => $userId),
                    'orderBy' => array('name' => 'ASC'),
                ),
            ),

        ),
        'attributes' => array(
            'multiple' => false,
            'required' => false,

        )
    ));

}

This worked, as i was sending the variable reuserId when initializing the form, using $this->identity()
The client wants to inject the user entity and select from there....
Searched stackoverflow and google, but was not able to find anything...any help please? thanks!

A: To 'inject' anything in ZF2 you will need to use the ServiceManager and create service factories.
It is therefore important to ensure that you are always creating the form via the ServiceManager.
In a controller for instance:
$form = $this->getServiceLocator()->get('MyModule\Form\FooForm');

Then you would need to 'inject' the user buy creating a factory class or closure.
Module.php
 public function getFormElementConfig() {
    return array(
      'factories' => array(
        'MyModule\Form\FooForm' => function($fem) {

            $serviceManager = $fem->getServiceLocator();
            $entityManager  = $serviceManager->get('objectmanager'); // Doctrine object manager

            // Load the user
            // Example is the zfcUser authentication service, however replace
            // this with whatever you use to maintain the users id

            $user = $serviceManager->get('zfcuser_auth_service')->getIdentity();

            // Inject the user entity into the form constructor
            $form = new FooForm($user);

            return $form;
        },
      ),
    );
}

With that said I think you might need to think about the form dependencies. It seems to me that you do not depend on the user entity - but rather the user's id should be used in a database query that reduces the list of 'Religions'.
You could execute this query and then pass the result (The religion collection) to the form in the same way my example shows how to for the user entity - This would then mean you could use a 'normal' Zend\Form\Element\Select rather than the ObjectSelect - meaning no need to inject the ObjectManager etc.


text:
Q: How to delete a particular element from a matrix in SciLab disp(A)
1.     4.     5.
9.     13.    11.
46.    29.    11.

-->clear A(3,3)
              !--error 276
Missing operator, comma, or semicolon.
I want to delete 11

A: The clear command is used to remove entire variables, see the documentation. If you could clear the 3,3 field it would result in a malformed matrix:
1.     4.     5.
9.     13.    11.
46.    29.

I don't know of a way this is possible.
What is it that you want? Do you want to set certain fields to be ignored. You could just set it to NaN (Not a Number) and check if it is nan later in your code with isnan:
A = rand(3,3)

A(3,3)= %nan

disp(A)
non_nans_indices = find(~isnan(A))

disp(A(non_nans_indices))

A: In a regular matrix you can not delete just one element, as stated in the above answer: you have to delete a full row or a full column. However in a sparse matrix you can. A sparse matrix stores only the non-zero elements of the matrix. So if your data doesn't contain valid elements with 0 value, you can "delete" any element by setting it to 0 and then converting the matrix into sparse form with the sparse command:
A=rand(3,3);
disp(A,"original matrix:");
A(3,3)=0;
disp(A,"element is nulled out:");
A=sparse(A);
disp(A,"sparse matrix:");

This way you doesn't store the 0 values of tha matrix which may save memory or storage space. If you want to convert back, you can use the full command: the "missing" elements are representeted with zeros again:
B=full(A);
disp(B,"full form:");

But I think, that for missing or invalid values it's better to use %nan as advised above too: it's easier to deal with, more consistent, and you can have zeros in the matrix as valid data.


text:
Q: SCIM userName in PATCH operation I have implemented user provisioning/deprovisioning with SCIM like so :
users_controller.rb
class Scim::UsersController < Scim::ScimController
  before_action :set_scim_provider

  def index

    startIndex = params[:startIndex].to_i
    startIndex = 1 if startIndex < 1# if the user send a startIndex < 1, it is bad data, we don't take it.

    itemsPerPage = params[:count].to_i

    if itemsPerPage < 1 || itemsPerPage > @scim_provider.max_results
      itemsPerPage = @scim_provider.default_number_of_results
    end

    scim_users = @scim_provider.identity_provider.communaute_accesses.from_scim

    if params["filter"]
      parser = Scim::QueryFilter::Parser.new
      rpn_array = parser.parse(params["filter"])
      tree = parser.tree
      if tree.length == 3 and tree[0]== 'eq' and tree[1] == 'userName'
        userName = tree[2]
        scim_users = scim_users.where(provider_identifier: userName.delete('"'))
      else
        fail 'e'
      end

    end

    paginated_users = scim_users.order(:created_at).offset(startIndex - 1).limit(itemsPerPage)

    r = {
      "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
      "totalResults": scim_users.size,
      "Resources": paginated_users.map { |ca| @scim_provider.representation_for_user(ca) },
      "startIndex": startIndex,
      "itemsPerPage": itemsPerPage
    }

    render_json_result(r, 200)

  end

  def create
    if @scim_provider.identity_provider.communaute_accesses.from_scim.find_by(provider_identifier: @body_params['userName'])
      render_409_conflict("uniqueness")
    else
      ca = @scim_provider.identity_provider.communaute_accesses.find_by(provider_identifier: @body_params['userName'], communaute_id: @scim_provider.identity_provider.communaute.id)
      if ca.nil?
        ca = @scim_provider.identity_provider.communaute_accesses.create(provider_identifier: @body_params['userName'], communaute_id: @scim_provider.identity_provider.communaute.id)
      end
      ca.update_last_raw_value("scim", @body_string)
      ca.extract_values_from_scim

      ca.queue_send
    end

    render_json_result(@scim_provider.representation_for_user(ca), 201)
  end

  def show
    user = @scim_provider.identity_provider.communaute_accesses.from_scim.find_by(provider_identifier: @body_params['userName'])
    if user
      render_json_result(@scim_provider.representation_for_user(user), 200)
    else
      render_404_not_found(params[:id])
    end
  end

  def update
    ca = @scim_provider.identity_provider.communaute_accesses.from_scim.find_by(provider_identifier: @body_params['userName'])
    uc = UserCommunaute.find_by(provider_identifier: @body_params['userName'])

    ca.update_last_raw_value("scim", @body_string)
    ca.extract_values_from_scim

    unless ca.nil?
      if ca.pending?
        ca.update_last_raw_value("scim", @body_string)
        ca.update(active: false)

        if ca.active == false
          fail "Unable to delete this user because of activeness" if ca.active == true
          ca.destroy!
        end

        render_json_result(@scim_provider.representation_for_communaute_access_patch(ca), 200)
      end
    end

    unless uc.nil?
      uc.update(active: @body_params['active'])
      if uc.active == false
        uc.user.communaute_accesses.from_scim.destroy_all
        uc.user.user_communautes.from_scim.destroy_all
        render_json_result(@scim_provider.representation_for_user_communaute_patch(uc), 200)
      end
    end
  end

end

Explanations:
When updating a user, SCIM sends a PATCH request like this:
{"schemas"=>["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations"=>[{"op"=>"Replace", "path"=>"active", "value"=>"False"}]} (@body_params in the code)
Which is what i am expecting. But, for a while, i was receiving the userName also in the body response during the PATCH operation.
This is how I fetch the correct user in my DB.

Actual result:
I don't receive the userName anymore when SCIM hits my update action.

Expected results:
Being able to receive information about the user during the PATCH operation to fetch the userName and find the right user in my database.

I have tried almost everything. When SCIM hits the index action, which it does everytime before going anywhere else, it does return me a userName et everything ends up as a 200 OK.
Then, when passing through update, it sends me nothing.
What I have tried last is to isolate the userName as an instance variable in the index action to fetch it after in the update like so:
# index
...
if params["filter"]
      parser = Scim::QueryFilter::Parser.new
      rpn_array = parser.parse(params["filter"])
      tree = parser.tree
      if tree.length == 3 and tree[0]== 'eq' and tree[1] == 'userName'
        @user_name = tree[2]
        scim_users = scim_users.where(provider_identifier: @user_name.delete('"'))
      else
        fail 'e'
      end
    end
...

# update

def update
    ca = @scim_provider.identity_provider.communaute_accesses.from_scim.find_by(provider_identifier: @user_name)
    uc = UserCommunaute.find_by(provider_identifier: @user_name)

    ca.update_last_raw_value("scim", @body_string)
    ca.extract_values_from_scim
...

But, @user_name in update seems to disappear as its value is nil.

I am deprovisioning from Azure Active Directory and Okta in a production environment.
Mapping is ok in both platforms.
Provisioning is working like a charm.

A: Please refer to https://developer.okta.com/docs/reference/scim/scim-20/#update-a-specific-user-patch for PATCH /Users/{userId}. Could you not make use of the userId in the url to identify the user ?


text:
Q: DataSvcUtil.exe and generating a custom namespace I am using DataSvcUtil and I wanted to generate a custom namespace for my generated class but this does not seem to be allowed.  Is there a reason for this?

A: DataSvcUtil.exe is a fairly thin wrapper over the System.Data.Services.Design.EntityClassGenerator class, which has support for using a custom namespace prefix, but not arbitrarily customizing the namespaces. I don't know of a specific reason this support was not provided, there may not have been a compelling enough scenario for it at the time.
If you need more flexible code generation, I strongly suggest you take a look at the T4 template the team released some time ago. It is very likely that code generation for WCF Data Services will more towards using T4 rather than DataSvcUtil/EntityClassGenerator.


text:
Q: Should I use Facebook Share Dialog or Feed Dialog? I'd need to redirect users to another page after succcessfull response I'm making a very simple site where users can do a silly little test, and share the result to Facebook. After visitor shares they should be redirected to another page on the site.
I've gotten it working using the Feed dialog but it seems like the Share dialog is recommended and somehow maybe better?
So:

*

*How are Share dialog and Feed dialog different?

*Which one should I use for what purpose?

*Is it possible to redirect the user to a new page after successful share with the Share dialog? It says that the ID of response data is "Only available if the user is logged into your app using Facebook and has granted publish_actions. If present, this is the ID of the published Open Graph story."

Here is the code I'm using (Feed Dialog). What we share will depend on the the results of the test the user did.
function share_prompt() {
    FB.ui(
       {
         method: 'feed',
         name: fbName,
         link: fbLink,
         picture: fbPictureUrl,
         caption: fbCaption,
         description: fbDescription,
         message: fbMessage
       },
       function(response) {
         if (response && response.post_id) {
           //alert('Post was published.');
           alert('redirect to a page-->');
           window.location.href = "http://redirect-user-here.com";
         } else {
           alert('User didin't share the story, we'll do something else);

         }
       }
     ); //FB.ui
 }

A: *

*The Feed Dialog allowed to set your own custom data, the Share Dialog takes the Open Graph tags from the shared URL.

*Debug the callback of the Share Dialog when you cancel the Share and when you approve it. But you should not redirect users after Sharing, maybe they want to use the Share Dialog again to share the URL in another channel.


text:
Q: Intel 845GL graphics driver issues
Possible Duplicate:
Fixing display issues on Intel 82845GL

The screen divides into 4 segments after Ubuntu 11.4 or 11.10 is installed on the HDD.  This issue does not show up when running from CD.
Is there a quick way to tell Ubuntu 11.10 to use the same driver used from CD?
The issue is exactly same as reported here: Fixing display issues on Intel 82845GL
But none of the answers posted there solved the issue.
Any help for a newbe?


text:
Q: PostgreSQL password generator I need some help with sql pass generator. I already have a function which returns 8 random characters, but I have to be sure, that there are lowercase and uppercase characters and numbers. Any advice? Here is my old function.
CREATE FUNCTION f_generate_password() RETURNS text AS $$
DECLARE
   password text;
   chars text;
BEGIN
   password := '';
   chars :=
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
   FOR i IN 1..8 LOOP
     password := password || SUBSTRING(chars,
ceil(random()*LENGTH(chars))::integer, 1);
   END LOOP;
   return password;
END;
$$
LANGUAGE plpgsql;

A: Here is a solution for these with a same or similar problem :)
CREATE OR REPLACE FUNCTION f_generate_password()
  RETURNS text AS
$BODY$
DECLARE
   vPassword text;
   chars text;
BEGIN
   vPassword := '';
   chars :=
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  WHILE((select COALESCE(substring(vPassword from '.*[a-z]+.*'),'')) = '' OR (select COALESCE(substring(vPassword from '.*[A-Z]+.*'),'')) = '' OR (select COALESCE(substring(vPassword from '.*[0-9]+.*'),'')) = '') LOOP
  vPassword := '';
   FOR i IN 1..8 LOOP
     vPassword := vPassword || SUBSTRING(chars, ceil(random()*LENGTH(chars))::integer, 1);
  END LOOP;
   END LOOP;
   return vPassword;
END;
$BODY$
  LANGUAGE plpgsql;

A: If you wonder about an algorithm... I don't know PostgreSQL syntax/dialect but you can e.g.:
1) pick 3 random positions (1 to 8) and put 3 random lower-case letters there
2) pick 3 random positions (from the remaining ones) and put 3 random upper-case letters there
3) put 2 random digits in the remaining two positions.


text:
Q: React losing focus on input field (component added dynamically) Stack : React16, ES6, Redux
I'm currently unable to figure what's wrong here. The goal here is to add dynamically an infinite number of components (one by one) when clicking on an add button.
I need to make them appear, if possible by pair or more, e.g. if I click on the ADD button, there should be 2 fields appearing each time (one select field and one textfield at the same time, for ex)
I'm able to make the components appear, with the help of Redux, and I'm also able to manage the datas correctly (everything's wired on the back of the app)
THE PROBLEM HERE :
When trying to type text in an input field, it's ALWAYS losing the focus. I've seen that each time I update my props, the whole component named MultipleInputChoiceList is mounted again, and that each fields are re-created anew. That's what I need to fix here :
EDIT : The MultipleInputChoiceList component is mounted via a Conditional Rendering HOC (It takes some values and check if they are true, if they are, it's rendering the component without touching the whole form)
ConditionalRenderingHOC.js
import  React from 'react'
import {connect} from 'react-redux'
import _ from 'lodash'

const mapStateToProps = state => {
  return {
    form: state.form.form
  }
}

const mapDispatchToProps = dispatch => {
    return {
    }
  }

  /**
   * HOC Component to check conditional rendering on form component, using requireField property
   * To be enhanced at will
   */
  export default (WrappedComponent, formItem = {}) => {
    class ConditionalRenderingHOC extends React.Component {
        componentWillMount() {
            //Check if all informations are available
            if (formItem.requireField !== undefined) {
                const requireField = formItem.requireField
                if (requireField.value !== undefined &&
                    requireField.name !== undefined &&
                    requireField.field !== undefined &&
                    requireField.property !== undefined) {
                        //If everything's here let's call canBeRendered
                        this.canBeRendered()
                    }
            }
        }

        //Check if the count of fetched values is directly linked to the number of fetched config asked, if true, return the same number
        canBeRendered() {
            formItem.requireField.isRendered = false
            let required = formItem.requireField
            let isEqual = false
            if (this.props.form[required.field] !== undefined) {
                let field = this.props.form[required.field]
                _.forEach(field.value, (properties, index) => {
                    if (properties[required.name] !== undefined) {
                        if (properties[required.name] === required.value) {
                            if (properties[required.property] === required.isEqualTo) {
                                formItem.requireField.isRendered = true
                                isEqual = true
                            }
                        }
                    }
                })
            }

            return isEqual
        }

        render() {
            let isConditionMet = this.canBeRendered()
            let render = null
            if (isConditionMet === true) {
                render = <WrappedComponent items={formItem}/>
            }

        return (<React.Fragment>
            {render}
          </React.Fragment>)
        }
    }

    return connect(mapStateToProps, mapDispatchToProps)(ConditionalRenderingHOC)
}

The code
    //Essentials
import React, { Component } from 'react'
import _ from 'lodash'
//Material UI
import TextField from 'material-ui/TextField'
import IconButton from 'material-ui/IconButton'
import AddBox from 'material-ui/svg-icons/content/add-box'
//Components
import SelectItemChoiceList from '../form/SelectItemChoiceList'
import TextFieldGeneric from './TextFieldGeneric'

//Redux
import { connect } from 'react-redux'
import { createNewField } from '../../../actions/formActions'

const mapStateToProps = (state) => {
  return {
    form: state.form.form
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    createNewField: (field, state) => dispatch(createNewField(field, state))
  }
}

class MultipleInputChoiceList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      inputList: [],
    }
  }

  onAddBtnClick() {
    const name = this.props.items.name
    /**Create a new field in Redux store, giving it some datas to display */
    this.props.createNewField(this.props.form[name], this.props.form)
  }

  render() {
    const name = this.props.items.name
    /**I think the error is around this place, as it always re-render the same thing again and again */
    const inputs = this.props.form[name].inputList.map((input, index) => {
      switch(input) {
      case 'selectfield': {
        return React.createElement(SelectItemChoiceList, {
          items: this.props.form[name].multipleField[index],
          key:this.props.form[name].multipleField[index].name
        })

      }
      case 'textfield': {
        return React.createElement(TextFieldGeneric, {
          items: this.props.form[name].multipleField[index],
          index:index,
          key:this.props.form[name].multipleField[index].name
        })
      }
      default: {
        break
      }
      }
    })

    return (
      <div>
        <IconButton onClick={this.onAddBtnClick.bind(this)}>
          <AddBox />
        </IconButton>
        {inputs}
      </div>
    )
  }
}

const MultipleInputChoiceListRedux = connect(mapStateToProps, mapDispatchToProps)(MultipleInputChoiceList)

export default MultipleInputChoiceListRedux

And the TextField used here :
TextFieldGeneric.js
//Essentials
import React, { Component } from 'react';
//Components
import TextField from 'material-ui/TextField'
//Redux
import { connect } from 'react-redux'
import { validateField, isValid } from '../../../actions/formActions'

const mapStateToProps = (state) => {
  return {
    form: state.form.form
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    validateField: (field) => dispatch(validateField(field)),
    isValid: () => dispatch(isValid())
  }
}

class TextFieldGeneric extends Component {
  constructor(props) {
    super(props)
    this.state = {
      form: {},
      field: {},
      index: 0
    }
  }

  componentWillMount() {
    console.log(this.props)
    //first, let's load those dynamic datas before rendering
    let form = this.props.form
    let index = this.props.index
    /** Check if there's a correctly defined parent in form (taken from the name) */
    let matchName = /[a-zA-Z]+/g
    let origin = this.props.items.name.match(matchName)

    //form.company.value = this.getCompaniesFormChoice()
    this.setState({form: form, field: form[origin], index: index})
  }

  //setState and check validationFields if errors
  handleFieldChange(event){
    const name = event.target.name
    const value = event.target.value
    //Change value of state form field
    const item = this.props.items
    item.value = value
    //validate each fields
    this.props.validateField(item)
    //validate form
    this.props.isValid()

    event.preventDefault()
  }

  render() {
    const index = this.state.index
    console.log(index)
    return (
      <React.Fragment>
        <TextField
          key={index}
          floatingLabelText={this.state.field.multipleField[index].namefield}
          name={this.state.field.multipleField[index].namefield}
          floatingLabelFixed={true}
          value = {this.state.field.multipleField[index].value}
          onChange = {this.handleFieldChange.bind(this)}
          errorText={this.state.field.multipleField[index].error === 0 ? '' : this.state.field.multipleField[index].error}
        />
      </React.Fragment>
    )
  }
}

const TextFieldGenericRedux = connect(mapStateToProps, mapDispatchToProps)(TextFieldGeneric)
export default TextFieldGenericRedux

I also do understand that a part of the problem lies in the render method of the parent class (MultipleInputChoiceList.js) ...
Any help or comments REALLY appreciated!

A: As of now, I've not come to a real answer to that question, as it's a structural problem in my data (When updating a field via a Redux action, it's re-rendering the whole component). Maybe stock those data elsewhere would be a better option.
I've only used a onBlur method on the field, that dismiss the validation I want to do on each user input, but for the moment I could not think to another viable solution.
So far, the TextFieldGeneric.js looks like that :
//setState and check validationFields if errors
  handleFieldChange(event){
    this.setState({value: event.target.value})

    event.preventDefault()
  }

  handleValidation(event){
    const value = this.state.value
    //Change value of state form field
    const item = this.props.items
    item.value = value
    //validate each fields
    this.props.validateField(item)
    //validate form
    this.props.isValid()
  }

  render() {
    return (
      <React.Fragment>
        <TextField
          name='name'
          floatingLabelFixed={true}
          value = {this.state.value}
          onChange = {this.handleFieldChange.bind(this)}
          onBlur = {this.handleValidation.bind(this)}
        />
      </React.Fragment>
    )
  }

If anyone have another solution, I'll gladly hear it !


text:
Q: Reading unstructured dictionaries in pandas dataframe I am trying to create a pandas dataframe from a collection of dictionaries that I read from a json file. The dictionaries are as follows -
d1 = {"DisplayName": "Test_drive", "permissions": {"read": True, "read_acp": True, "write": True, "write_acp": True}}
d2= {"DisplayName": "Log delivery","URI": "http://test_drive.com/Logs", "permissions": {"read": False, "read_acp": True, "write": True, "write_acp": False}}

I am trying to get these into a pandas dataframe. When I try to read them in a dataframe like following -
df = pd.DataFrame(d) **or** df = pd.DataFrame.from_dict(d)

it generates this -
                DisplayName  permissions
read       Test_drive         True
read_acp   Test_drive         True
write      Test_drive         True
write_acp  Test_drive         True

or read it as following -
df1 = pd.DataFrame(d).Transpose()

it generates this -
                         read          read_acp             write         write_acp
DisplayName  Test_drive  Test_drive  Test_drive  Test_drive
permissions              True              True              True              True

I am trying to read these dictionaries and join them into one dataframe -
**DisplayName**              **read**          **read_acp**             **write**         **write_acp**         URI
Test_drive         True              True              True              True         NA
Log delivery            False             True              True             False         http://test_drive.com/Logs

Is there any pytonic way to do this?

A: Create dataframe by appending and then reshape to the structure you need using pivot
df = pd.DataFrame.from_dict(d1).append(pd.DataFrame.from_dict(d2))
df.reset_index().pivot(index='DisplayName', columns='index', values='permissions')

To include URI
>>> df.reset_index().pivot(index='DisplayName', columns='index', values=['permissions', 'URI'])
             permissions                                                  URI
index               read read_acp write write_acp                        read                    read_acp                       write                   write_acp
DisplayName
Log delivery       False     True  True     False  http://test_drive.com/Logs  http://test_drive.com/Logs  http://test_drive.com/Logs  http://test_drive.com/Logs
Test_drive          True     True  True      True                         NaN                         NaN                         NaN                         NaN

A: import pandas as pd

# Input Data
d1 = {"DisplayName": "Test_drive", "permissions": {"read": True, "read_acp": True, "write": True, "write_acp": True}}
d2= {"DisplayName": "Log delivery","URI": "http://test_drive.com/Logs", "permissions": {"read": False, "read_acp": True, "write": True, "write_acp": False}}

# Convert to DataFrame
dicts = [d1, d2]
df_rows = [pd.DataFrame(d) for d in dicts]
df = pd.concat(df_rows, axis=0).reset_index(drop=False)

# Reshape As Desired
tp1 = df.pivot(index='DisplayName', columns='index', values='permissions')
answer = tp1.merge(df[['DisplayName', 'URI']].drop_duplicates(),
                   how='left',
                   left_index=True,
                   right_on='DisplayName').set_index('DisplayName')

Output:
>>> answer
               read  read_acp  write  write_acp                         URI
DisplayName
Log delivery  False      True   True      False  http://test_drive.com/Logs
Test_drive     True      True   True       True                         NaN

A: Thank you Vishnudev and Max Power for your help. I think the following answer gives me the exact dataframe that I was trying to get.
d1 = {"DisplayName": "Test_drive", "permissions": {"read": True, "read_acp": True, "write": True, "write_acp": True}}
d2= {"DisplayName": "Log delivery","URI": "http://test_drive.com/Logs", "permissions": {"read": False, "read_acp": True, "write": True, "write_acp": False}}
df = pd.concat([pd.Series(d1),pd.Series(d2)], axis=1).transpose()
df = pd.concat([df.drop(['permissions'], axis=1),df['permissions'].apply(pd.Series)],axis=1)

**DisplayName                         URI   read  read_acp  write  write_acp**
0    Test_drive                         NaN   True      True   True       True
1  Log delivery  http://test_drive.com/Logs  False      True   True      False


text:
Q: Retrieve google+ user info from User authenticated in a GAE Maybe I'm not really clear how Google APIs and OAuth2 are working, but I can't extract user profile info using the Google+ API client library. What I'm trying to do is to log in to my GAE project with an android client, then from the backend retrieve some info about the user profile (firstname and lastname). Is that possibile? I tried to use the keyword "me" in my api call but I think that is not the right route since what the api call returns is only my e-mail and all the other field are blank; I know that they are all filled in in my profile. Is this because I am on the dev server?
Here is my function to retrieve the user profile:
private Person retrieveUserInfo(User user) throws IOException, GeneralSecurityException{
    // Set up the HTTP transport and JSON factory
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
            .setJsonFactory(jsonFactory)
            .setServiceAccountId("146433070678-dpj18aug5amtqqfqcnmnco4lne91uii5@developer.gserviceaccount.com")
            .setServiceAccountScopes(Collections.singleton(PlusScopes.USERINFO_PROFILE))
            .setServiceAccountPrivateKeyFromP12File(new File("secretkey.p12"))
            .build();

    // Set up the main Google+ class
    Plus plus = new Plus.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("no_app_id")
        .build();

    // Make a request to access your profile and display it to console
    Person profile = plus.people().get("me").execute();
    return profile;
}

I would appreciate any hints about accessing user details from a GAE backend. Thanks.


text:
Q: Crystal Reports in MVC throwing exception I am loading report in mvc4 using following code. but its throwing error on Exporting. Error is "The system cannot find the path specified."
Please guide me ; remember its not find file path

 ReportClass rptH = new ReportClass();
         rptH.FileName = Server.MapPath("~/CrReports/CrProductsList.rpt");
         rptH.Load();
         rptH.SetDataSource(new ReportingFactory().AllProductsReport());

     Stream stream =rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
     return File(stream, "application/pdf");

this line throwing error
Stream stream =rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

A: did you try back slashes instead of forward slashes (that's what I use)
rptH.FileName = Server.MapPath("~\CrReport\CrProductsList.rpt");

Here's what I use:
rptH.FileName = @"~\App_Pages\Secure\CrReports\CrProductsList.rpt";

See here:
https://stackoverflow.com/a/14592492/1438215
Edit: another thing to consider, if your reports directory is not a subdirectory of your solution, make sure the account IIS uses to run the application has read access to the CrReport folder.


text:
Q: REST based web services the server returns more arrays than expected I am building a REST based web services, in the server, I have a service called display_all_products the code is like so:
case 'display_all_products':
    $KEY = filter_input(INPUT_GET, 'api_key');
    try {
        $token = JWT::decode($KEY, $secret);
        $jsonProducts = getProducts();
        $products = json_decode($jsonProducts, TRUE);
    } catch (Exception $ex) {
        return -1;
    }
    if($products != NULL){
        echo $jsonProducts;
    }else{
        echo "error";
    }

Function getProducts() will get all the products information from database and return a json string. When I tested the function, I got a json string like this:
[{"product_id":1,"0":1,"product_name":"Chocolate","1":"Chocolate","price":3,"2":3,"description":"Dark chocolate","3":"Dark chocolate"},{"product_id":2,"0":2,"product_name":"Toilet tissue","1":"Toilet tissue","price":10,"2":10,"description":"Nature and Soft","3":"Nature and Soft"},{"product_id":3,"0":3,"product_name":"Rice","1":"Rice","price":5,"2":5,"description":"Basmati Rice","3":"Basmati Rice"},{"product_id":4,"0":4,"product_name":"Fruit Loaf","1":"Fruit Loaf","price":5,"2":5,"description":"Rich Fruit Bread","3":"Rich Fruit Bread"},{"product_id":5,"0":5,"product_name":"Raspberry Jam","1":"Raspberry Jam","price":6,"2":6,"description":"Full of Flavour","3":"Full of Flavour"}]

It looks like a json string, nothing wrong with it. And also I can get it from the client which means I can do the json_decode in the code I provided above.
The problem is I can not do the json_decode in the client. When it comes to the client, I am getting a json string from the server like this:
[{"product_id":1,"0":1,"product_name":"Chocolate","1":"Chocolate","price":3,"2":3,"description":"Dark chocolate","3":"Dark chocolate"},{"product_id":2,"0":2,"product_name":"Toilet tissue","1":"Toilet tissue","price":10,"2":10,"description":"Nature and Soft","3":"Nature and Soft"},{"product_id":3,"0":3,"product_name":"Rice","1":"Rice","price":5,"2":5,"description":"Basmati Rice","3":"Basmati Rice"},{"product_id":4,"0":4,"product_name":"Fruit Loaf","1":"Fruit Loaf","price":5,"2":5,"description":"Rich Fruit Bread","3":"Rich Fruit Bread"},{"product_id":5,"0":5,"product_name":"Raspberry Jam","1":"Raspberry Jam","price":6,"2":6,"description":"Full of Flavour","3":"Full of Flavour"}][][]

Both of the json string are very similar but at the very end of the second json string has two more[] in there. I did not encode twice. I think that is the reason why I can not decode it but where are the two[] come from and how to get rid of them.
Here is my code form the client:
$keyReq = "?api_key=" . $api_key . "&service=display_all_products";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $basicUrl . $keyReq);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json"));
    $jsonProducts = curl_exec($ch);

    curl_close($ch);
    $products = json_decode($jsonProducts, TRUE);


text:
Q: Aws get S3 Bucket Size using java api I have searched on google about efficient way to get metadata about S3 bucket like its size and number of files in it. I found this link discussing such problem. But it's for PHP and aws cli using cloud-watch. I want to know is there some java api to fetch the s3 bucket metadata?
Thanks

A: You can find the extensive documentation of the AWS S3 Java library here:
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/overview-summary.html
Answering your question, you can use getSize() for getting the size of an object in S3 and you can iterate over all of your files to get the size of your bucket.
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/model/S3ObjectSummary.html#getSize()
S3 does not support gathering disk usage directly (meaning not iterating through all of the items) but you can use CloudWatch to get the data you would like to use with a single request.
Example query:
aws cloudwatch get-metric-statistics --namespace AWS/S3 --start-time 2016-01-01T10:00:00 --end-time 2016-02-12T01:00:00 --period 86400 --statistics Average --region us-east-1 --metric-name BucketSizeBytes --dimensions Name=BucketName,Value=www.streambrightdata.com Name=StorageType,Value=StandardStorage

Returns:
{
    "Datapoints": [
        {
            "Timestamp": "2016-02-05T10:00:00Z",
            "Average": 54027423.0,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2016-02-03T10:00:00Z",
            "Average": 52917504.0,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2016-02-04T10:00:00Z",
            "Average": 53417421.0,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2016-02-07T10:00:00Z",
            "Average": 54949563.0,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2016-02-01T10:00:00Z",
            "Average": 24951965.0,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2016-02-02T10:00:00Z",
            "Average": 28254636.0,
            "Unit": "Bytes"
        },
        {
            "Timestamp": "2016-02-06T10:00:00Z",
            "Average": 54577328.0,
            "Unit": "Bytes"
        }
    ],
    "Label": "BucketSizeBytes"
}

AWS Java SDK for CloudWatch:
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/cloudwatch/AmazonCloudWatchClient.html


text:
Q: Re-create hard deleted stream I have accidentally hard-deleted a stream from EventStore using ES-HardDelete in request header. When I am trying to create it again it fails with 410 Permanently Deleted.
I tried deleting the EventStore db and log folder. No luck. Also tried deleting entire EventStore and installing fresh one, still it fails to create the same stream.
Is there any way so that I can create the stream with same name again?


text:
Q: Performance considerations of instantiating DbContext for every request My project involves entity framework 6, asp.net mvc 5, owin and ninject.
Owin is used because I use ASP.NET Identity. My dbContext FhtDbContext inherits from IdentityDbContext.
Since one DbContext per request is the norm, my current solution is as follows:
In Startup.cs:
app.CreatePerOwinContext(FhtDbContext.Create);

Then in ninject configuration:
kernel.Bind<FhtDbContext>().ToProvider(new CallbackProvider<FhtDbContext>(ctx =>
{
    return HttpContext.Current.GetOwinContext().Get<FhtDbContext>();
})).InRequestScope();

However, in this setup, a FhtDbContext is created even if a request doesn't need database read/write at all.
So my question is, how expensive is creating a dbcontext and discard it?


text:
Q: VLC Player: Ignoring faulty playlist items ("main input error: Your input can't be opened" locks up the application) When a malformed URL is given to VLC through the "Open network stream" interface, the command like option "--open " or the Lua CLI command "add", the interface locks up and the console spits out the error message
[00007f31355cea20] filesystem stream error: cannot open file /home/paul/c (No such file or directory)
[00007f313c000c40] main input error: Your input can't be opened
[00007f313c000c40] main input error: VLC is unable to open the MRL 'file:///home/paul/c'. Check the log for details.

at a rate of multiple (hundred?) repetitions per second.
I assume the faulty item is added to the playlist and VLC keeps trying to play it back over and over.
How can I make it ignore this error?
My current ideas are hooking into the error to remove the last item added or having a preprocessor check whether VLC can actually open the resulting playlist item. How would I do this? Maybe this is only a configuration issue after all?
Thanks.

A: I thought this looks like a bug, my VLC (3.0.6) doesn't do that when opening via command line's --open or the gui's "open network stream"...  but further testing with looping files or a playlist reveals that I think your vlc is set to loop files, but the only file your trying to open results in an error, so vlc tries the next file, that loops happens to be the same file again...

*

*vlc --loop filedoesnotexist caused the same errors you're seeing. (Also trying to "play" a text file like vlc's --help output caused the error too, so even checking if a file exists won't necessarily ensure vlc won't have trouble).

Turning off looping stops the looping errors

*

*vlc --no-loop filedoesnotexist only resulted in one error message, and no problems with still using vlc to open other files, etc.

My vlc does not default to looping, but it looks like yours does and it's probably causing the errors even without using the --loop flag. I'm not sure how to change the "default" of looping on/off though, mine just turns off looping if I close it when enabled. vlc -H (warning, it's +300k!) only mentions hot key loop options, and:
-L, --loop, --no-loop          Repeat all
                               (default disabled)
      VLC will keep playing the playlist indefinitely.

I'd argue it might still be a bug if a playlist is full of entries that all cause errors & don't play, but keeps looping through them over and over. If not a bug, at least a "feature request" to stop looping in case everything errors.
If looping can't be stopped, you could monitor vlc's log (might have to enable logging first) and if you (or your script) start seeing the same errors, or the file just starts uncontrollably growing, then kill the vlc process (plain pkill vlc looks effective).

[It appears plain bug reports might be off-topic, but figuring out a work-around for bugs looks on-topic...]


text:
Q: How to interpret intercept and coefficient with binomial variables in statsmodels Logit We trying to assess the chances to sell Personal Loan to the person who has CD Account. So in our database, we have observations with different sets of both variables.
I'm fitting logistic regression with two binomial variables. All is work but I can't understand the meaning of intercept and variable coefficients of its size...
log_mod = sm.Logit(bin_df['Personal Loan'], bin_df[['intercept', 'CD Account']]).fit()

log_mod.summary()

This is what i got:
              coef  std err     z   P>|z|    [0.025 0.975]
intercept   -2.5508 0.056   -45.301 0.000   -2.661  -2.440
CD Account  2.4049  0.128   18.730  0.000   2.153   2.657

The odds for CD Account is:
np.exp(log_mod.params[1])
11.076978939724048

How to interpret negative intercept?
How to interpret such big odds? What can i say?


text:
Q: Can a "plain" php application use a laravel user table for authentication? Currently I have a Laravel application with authentication. I'm wondering if I could have another PHP application (framework independent) that uses the same user table for authentication. I don't want to use Laravel again because it would be a over engineering.
My main concern is how the hashing of the password is done in Laravel. Can I configure the plain PHP application to hash passwords the same way? If so, how can I do this?

A: Laravel uses password_hash() to create a password hash (see the make() method source code):
password_hash('somePassword555', PASSWORD_BCRYPT);

And password_verify() to check password hash (see the check() method source code):
password_verify('somePassword555', $hashedPasswordFromDB);

A: This is the file you want to check out
vendor/laravel/framework/src/Illuminate/Hashing/BcryptHasher.php
And these are the functions they are using, password_hash(); and password_verify();
function make($value, array $options = [])
    {
        $cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds;
    $hash = password_hash($value, PASSWORD_BCRYPT, ['cost' => $cost]);

    if ($hash === false) {
        throw new RuntimeException('Bcrypt hashing not supported.');
    }

    return $hash;
}

function check($value, $hashedValue, array $options = [])
{
    if (strlen($hashedValue) === 0) {
        return false;
    }

    return password_verify($value, $hashedValue);
}


text:
Q: How to get a dataframe from XML? I have a fairly large xml file that I need to convert to a dataframe, but I keep getting an error code.
library(ggplot2)
library(tidyverse)
library(data.table)
library(XML)

xmldata <- xmlInternalTreeParse("C:\\Users\\Lee\\Documents\\R\\housing\\housing_census_2006\\housing_census_2006.xml", useInternalNodes = TRUE)

housing_census_2006 <- xmlToDataFrame(xmldata)
#> Error in `[<-.data.frame`(`*tmp*`, i, names(nodes[[i]]), value = c(ID = "97-554-XCB2006007", : duplicate subscripts for columns

The error is occuring when I try to use xmlToDataFrame. Is there something wrong with my code or is this not the right way to do it?
For clarification, this is what the xml file looks like (this is just one record):
-<generic:Series>

-<generic:SeriesKey>

<generic:Value value="01" concept="GEO"/>

<generic:Value value="1" concept="B06_Hhtype1CFOnly"/>

<generic:Value value="1" concept="B06_HhMainAge"/>

</generic:SeriesKey>

-<generic:Obs>

<generic:Time>2006</generic:Time>

<generic:ObsValue value="12437470"/>

</generic:Obs>

</generic:Series>


text:
Q: how to get google style fixed header in mobile (no jquery mobile) I'm looking to get a fixed header without using jQuery mobile.
I found a page from google detailing how to implement this feature, but they have left some code out as a 'user exercise'
this code is somewhat beyond me and I cant figure it out, has any one done this, or can anyone figure out what the 'missing' code should be?
https://developers.google.com/mobile/articles/webapp_fixed_ui
or does anyone have a better/ easier way? (again, no jQuery mobile, please)
any help would be appreciated! thanks

A:

        ... toolbar content ...

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sollicitudin molestie augue vel venenatis. Maecenas sit amet dui vitae odio posuere tempus eu eu ante. Mauris scelerisque sagittis iaculis. Praesent posuere id sem vel iaculis. Praesent mollis feugiat mauris. Integer consectetur dui nibh, in hendrerit est fermentum quis. Nunc porttitor diam sit amet nisl convallis molestie. Pellentesque ligula odio, feugiat eget pellentesque ut, varius ut ligula.

Sed aliquam, nisi quis condimentum accumsan, quam neque varius massa, et aliquam dui diam vitae erat. Nullam commodo blandit sollicitudin. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed vestibulum leo urna, et adipiscing leo porttitor vitae. Nam ultrices rutrum orci, eget ultricies elit tempus a. Etiam pellentesque tellus sodales fermentum sodales. Vivamus ipsum arcu, tincidunt et quam sit amet, aliquet sollicitudin risus.

Phasellus id fermentum nibh. Donec lacus nisi, placerat at tortor dignissim, imperdiet consectetur odio. Praesent id eros diam. Curabitur felis enim, porta nec faucibus et, rhoncus vel turpis. Quisque eu orci posuere, mattis purus vel, iaculis ipsum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nam semper luctus nulla gravida congue. Nullam rhoncus gravida arcu, at cursus urna porttitor ut. Fusce vehicula malesuada metus, non placerat velit. Nullam ut justo dui. Aenean eget erat eu purus vestibulum blandit. Donec viverra dictum tellus sed congue. In iaculis egestas pharetra. Nulla sollicitudin, justo ut congue elementum, lorem mauris ultrices turpis, non tincidunt leo libero quis lorem.

Donec eu euismod ligula. Vestibulum nec ornare urna. Aenean tempor ligula nisi, vitae iaculis felis pretium a. Suspendisse sollicitudin ac purus eu consequat. Fusce elementum rhoncus gravida. Nullam gravida, est eget vehicula condimentum, mauris quam laoreet libero, ac convallis nulla quam ac velit. Nunc a aliquet enim. Praesent volutpat, massa ultricies adipiscing porta, lectus urna molestie orci, vel aliquam tellus nibh sit amet justo. Donec venenatis sed augue id varius. Ut bibendum nunc ut nisl venenatis, nec varius dui commodo. Praesent urna mi, sagittis vel congue ac, dapibus at urna. Maecenas auctor tortor dapibus leo laoreet vestibulum.

Pellentesque sit amet suscipit ante. Nullam nec urna in arcu faucibus cursus pharetra sit amet lacus. Quisque eu bibendum diam, eget suscipit leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ullamcorper, nulla vel egestas interdum, mauris dui pretium lectus, et gravida dolor sapien vel risus. Aenean id ante interdum augue tristique cursus ut eu magna. Ut nisi elit, sollicitudin in justo vitae, facilisis commodo magna. Integer suscipit, lectus sed aliquam iaculis, erat lacus lacinia ipsum, ut rhoncus sem neque ac tellus. Sed sit amet varius velit. Curabitur sit amet tellus luctus, consectetur lacus et, pharetra tellus. Morbi leo lorem, condimentum in justo non, volutpat ornare quam.

    ... toolbar content ...

This worked for me, the only I've changed is position to fixed


text:
Q: Locking orientation at run-time on demand I currently have the following code:
PROCEDURE LockOrientation(Orientation : TOrientation);
  BEGIN
    {$IFDEF MOBILE }
      VAR ScreenService : IFMXScreenService;
      IF TPlatformServices.Current.SupportsPlatformService(IFMXScreenService,IInterface(ScreenService)) THEN BEGIN
        VAR OrientSet : TScreenOrientations;
        CASE Orientation OF
           TOrientation.Portrait : OrientSet:=[TScreenOrientation.Portrait];
          TOrientation.Landscape : OrientSet:=[TScreenOrientation.Landscape]
        END;
        ScreenService.SetSupportedScreenOrientations(OrientSet)
      END
    {$ENDIF }
  END;

to force a specific orientation (and a companion UnlockOrientation when I want to "release" it again). It works fine on Android, but not on iOS.
How do I (programmatically) "lock" the orientation to a specific value (it'll always be the "current" orientation) and (later on) unlock it (make it fully rotatable) on iOS?


text:
Q: Linking Microsoft Access to Microsoft outlook How can I link Microsoft Access to  Microsoft Outlook so as to generate reminders for deadlines in my Microsoft Access database?

A: I would use something like this
https://support.microsoft.com/en-us/kb/162371, but I made some "improvements" to it to make it a little more functional if you are working with variables.
Function AddOutLookTask(reminderDateAndTime As Date, dueDate As Date)
     Dim appOutLook As Outlook.Application
     Dim taskOutLook As Outlook.TaskItem
     Set appOutLook = CreateObject("Outlook.Application")
     Set taskOutLook = appOutLook.CreateItem(olTaskItem)
  With taskOutLook
      .Subject = "This is the subject of my task"
      .Body = "This is the body of my task."
      .ReminderSet = True
      .ReminderTime = reminderDateAndTime
      .dueDate = dueDate
      .ReminderPlaySound = True
       'add the path to a .wav file on your computer.
      .ReminderSoundFile = "C:\Windows\media\Notify.wav"

     .Save
  End With
End Function

You can test it in the immediate window using the code below with raw numbers, variables, etc.   Be sure to include the Microsoft Outlook 8.0 or higher Object Library Reference or it will not work
?addOutlookTask(#6/10/2015 3:45PM#, #6/11/2015#)

A: This should be quiet easy, you need to link the Calender table to Access. Look at this link for more info : http://www.fmsinc.com/microsoftaccess/email/linked/index.htm


text:
Q: Retrieving results from Mturk Sandbox I'm working on retrieving my HIT results from my local computer. I followed the template of get_results.py and entered my key_id, access_key correctly, and installed xmltodict but got the error message. Could anyone help me figure out why? Here is my HIT address if anyone needs the format of my HIT https://workersandbox.mturk.com/mturk/preview?groupId=3MKP0VNPM2VVY0K5UTNZX9OO9Q8RJE

    import boto3
    mturk = boto3.client('mturk',
       aws_access_key_id = "PASTE_YOUR_IAM_USER_ACCESS_KEY",
       aws_secret_access_key = "PASTE_YOUR_IAM_USER_SECRET_KEY",
       region_name='us-east-1',
       endpoint_url = MTURK_SANDBOX
    )
    # You will need the following library
    # to help parse the XML answers supplied from MTurk
    # Install it in your local environment with
    # pip install xmltodict
    import xmltodict
    # Use the hit_id previously created
    hit_id = 'PASTE_IN_YOUR_HIT_ID'
    # We are only publishing this task to one Worker
    # So we will get back an array with one item if it has been completed
    worker_results = mturk.list_assignments_for_hit(HITId=hit_id, AssignmentStatuses=['Submitted'])


text:
Q: Checking debug/release build i need to check the build in DEBUG/RELEASE in android on run time.
I have search some way for it but not working efficiently for like reading PKG and getting information for it.

A: you can check the application whether it is release mode or debug mode
boolean isDebuggable = (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));


text:
Q: Microsoft Kinect for Windows Camera driver not found I'm working with Microsoft Kinect for Windows using SDK 1.8.
It automatically finds all of the drivers required, except for the Kinect Camera driver. Because of this, whenever I run a progra,m it gives an exception at: sensor.Colorstream.Enable();
When I use Xbox 360 instead it works perfectly fine.
Can anyone please tell me how to get this Kinect for Windows working?
Thanks

A: If someone has a similar issue, I just solved it in the following way:
In the device manager the kinect can be recognized in 2 ways:

*

*Primesense

*Kinect for windows

In my case, it only works when it is installed as Kinect for Windows.
When it is recognized as Primesense, you can do the following for all 3 devices (camera, motor, audio):

*

*right click: update driver

*Choose 'search on my computer for driver'

*Choose from list of drivers on my computer

*Choose the Kinect for Windows driver


text:
Q: Why use ionic element tags/components vs standard html? Whats the benefit of using ionic elements like ion-button, ion-item, ion-row, ion-text ion-img instead of regular html?

A: The first benefit is that each component has been implemented to work properly on mobile devices and with mobile events like clicks, taps, and so on (do you remember the 300 ms delay issue?).
It's also important to notice that Ionic components were designed/implemented according to each platform's design guidelines and recommended patterns. Users expect all apps to respect some UI/UX patterns they are already used to, and Ionic does that extremely well.
Last but not least, some components also encapsulates a lot of logic that would be kind of hard to be implemented with just html elements (for example, the ion-item-sliding component).
But please notice that there're some scenarios where using standard html may be a good option. For example, if you need to show a very long list of items, using ion-items would mean that a new instance of the ion-item component is created for each item of the list, and your Ionic app will need to keep them in memory. Ionic components were implemented to be very performant so this won't be an issue for most of the mobile devices nowadays, but if you need to support old/slow devices this may improve the performance a lot.


text:
Q: What should i use for rails file attachment and jruby? Normally I'd use carrierwave, but they do not officially support jruby, and I've been running in to bugs, possibly related. (https://github.com/jnicklas/carrierwave/issues/620, Image corruption on upload to s3, production only.  (carrierwave, engineyard))
Have others had success here?
I'm considering trying out paperclip, but it looks like that may not be perfect either-- https://github.com/thoughtbot/paperclip/issues/100

A: Try dragonfly it's a really great library to manage you file attachment.

A: check out this guide, it's cake
http://webtempest.com/how-to-allow-image-uploads-in-rails-on-heroku/
It uses paperclip and amazon web s3 gems


text:
Q: How to delete tr row from table with modal dialog using bootstrap I'm using Bootstrap along with the jQuery plugins it comes with on a small project.  Right now I have a modal dialog popping up for deletion confirmation, and when the user clicks the confirm button it deletes the record just fine.
However, what I also want to do is have the table row that had the button it was clicked on to be removed as well.  So, if the user clicks on the "Delete" button on tr row 5, when the user confirms it'll remove tr row 5 as well from the table.
The table is generated dynamically but here's a small example:

test
eqeI0Tt-V7rzijDfLqrna2
eqeI0Tt-V7rzijDfLqrn

<input type="hidden" id="api_server_31" value="test" />
<input type="hidden" id="api_server_31_sid" value="null" />
<input type="hidden" id="api_server_31_tid" value="0" />
<button type="submit" class="api_key_edit btn btn-small btn-primary" value="31">Edit</button>
<button type="submit" class="api_key_delete btn btn-small btn-danger" value="31">Delete</button>

My dialog is also dynamically generated but here's what it shows for this example:

<button class="close" aria="hidden="true"" data-dismiss="modal" type="button"> … </button>

      Delete API Key for

      test

      ?

 …

 …

My JS code is this:
$("#conf_delete").click(function(e){
    e.preventDefault();

    if($(this).hasClass("disabled")){
        return false;
    }

    var conf = $("#conf_delete").val();
    conf = conf.split("|");

    var server = conf[0];
    var kid = conf[1];
    var tid = conf[2].substring(4);

    $.post("/api",
        {server : server, id : kid, api_act : "deletek"},
        function(data){
            var n = data.split("|");
            var type = n[0];
            var msg = n[1];
            var dak = $("#delete_api_key_msgbox");

            dak.show();

            if(type == "e"){
                dak.addClass("alert-error");
            } else{
                dak.addClass("alert-success");

                $("#conf_delete").addClass("disabled");

                $("#api_key_delete").modal("hide");
                // issue is here, though tr is captured, the fadeout/remove doesn't work
                var tr = $("#api_server_"+server).closest("tr");
                console.log("tr:"+tr);
                tr.fadeOut(400, function(){
                    tr.remove();
                });
            }

            $("#dak_msg").html(msg);
        }
    );
});

What happens is that the dialog pops up, user clicks confirm and the dialog shows the message, but it doesn't seem to do anything to the background no matter where I place the fadeOut/remove code.

A: I was using the wrong variable.  This is quite embarassing.


text:
Q: Banner overlaps Sub-Menu Wordpress I just upgraded Wordpress to version 3.5.1 and it messed up something in my site that now the Submenus load but are instantly hidden behind the Banner (They load up but are quickly hidden). I have tried a few modifications here and there but nothing (Now I may have messed it even more).
I think it's in the CSS File.
Here is a link to the site: http://www.fiestacolegial.com and the Submenus that are meant to appear go below MULTIMEDIA, NOTICIAS, SOBRE NOSOTROS.
Here is a link to the CSS File: http://pastie.org/6381132
Any help will be greatly appreciated.

A: The issue is that jQuery 1.9 is causing trouble with a plugin that handles this interaction.
This tutorial should show you how to use version 1.8 of jQuery instead: http://www.wpbeginner.com/wp-themes/replace-default-wordpress-jquery-script-with-google-library/


text:
Q: SwiftUI NavigationLink behaviour is different when selection is set directly, rather than from viewModel I've been working with SwiftUI and ran into unexpected behavior.
I have View A and View B and View C. View C has EnviromentObject that changes AppState from View A
View B has ViewModel with selection
If I call function from ViewModel to change the selection then
View C is shown for a few seconds and then it automatically pops back to View B
If I change selection directly from View B (not from ViewModel), everything works as expected.
Also, if I comment out onDissapear, it also works. But, I need to change environmentObject when screen dissapeared
Here is View B and ViewModel
import SwiftUI

class AppState: ObservableObject {
    @Published
    var shouldHideUserInfo = false
}

struct ContentView: View {

    @EnvironmentObject
    var appState: AppState

    @State
    var selection: Int? = nil

    var body: some View {
        NavigationView {
            VStack {
                if !appState.shouldHideUserInfo {
                    Text("USER INFO")
                }

                NavigationLink(
                    destination: ViewA(),
                    tag: 1,
                    selection: $selection,
                    label: { EmptyView()})

                Button("MOVE TO VIEW A") {
                    selection = 1
                }
            }
        }
    }
}

class ViewAModel: ObservableObject {
    @Published
    var selection: Int? = nil

    func navigate() {
        selection = 2 //<- this doesnt
    }
}

struct ViewA: View {

    @ObservedObject
    var viewModel: ViewAModel

    init() {
        viewModel = ViewAModel()
    }

    @State
    var selection: Int? = nil //<- this works

    var body: some View {
        VStack
        {
            Text("VIEW A")

            NavigationLink(
                destination: ViewB(),
                tag: 2,
                selection: $viewModel.selection,
                label: { EmptyView()})

            Button("MOVE TO VIEW B") {
                //selection = 2 <-- this works
                viewModel.navigate() //<- this doesnt
            }

        }
    }
}

struct ViewB: View {

    @EnvironmentObject
    var appState: AppState

    @State
    var selection: Int? = nil

    var body: some View {
        VStack
        {
            Text("VIEW B")

        }
        .onAppear {
            appState.shouldHideUserInfo = true
        }
    }
}

Factory pattern didn't solve the issue:
    static func makeViewA(param: Int?) -> some View {
        let viewModel = ViewAModel(param: param)
        return ViewA(viewModel: viewModel)
    }
}

A: I see... it is a bit different than in post. The issue is because view model is recreated (this is long observed behavior of NavigationView) and thus binding lost.
The quick fix is
struct ViewA: View {

    @StateObject
    var viewModel: ViewAModel = ViewAModel()

    init() {
//        viewModel = ViewAModel()
    }

    // ... other code
}

alternate is to keep ownership of view model outside of ViewA.
Update: SwiftUI 1.0 compatible - here is variant that works everywhere. The reason of the issue is in AppState. The code in ViewB updates appState
.onAppear {
    appState.shouldHideUserInfo = true
}

that causes rebuild of ContentView body, which recreates ViewA, which recreates NavigationLink, which drops previous link and ViewB got closed.
To prevent this we need to avoid rebuild ViewA. This can be done by making ViewA is-a Equatable, so SwiftUI check if ViewA needs to be recreated and we will answer NO.
Here is how it goes:
NavigationLink(
    destination: ViewA().equatable(),    // << here !!
    tag: 1,
    selection: $selection,
    label: { EmptyView()})

and
struct ViewA: View, Equatable {
    static func == (lhs: ViewA, rhs: ViewA) -> Bool {
        true
    }

    // .. other code


text:
Q: Options for custom connecting a temperature sensor with a USB 2.0 I'm exploring a little project that would involve creating a custom USB device by connecting a temperature sensor to a USB device. There seems to be a dearth of information online about how to do this. Originally I found a pretty good sensor that uses the 1-wire protocol, and someone outlined how they were able to connect this with USB in this tutorial. However, they still ended up having to use a proprietary library from 1-wire's manufacturer to read data from the sensor. Ideally, I would avoid this, and could write my own device driver in C if necessary.
I'm inexperienced with embedded and hardware, so just trying to explore options and find good resources for this project. Is something like this even possible without using a proprietary SDK?  What would be a good standard to work with (1-wire, I2C, etc.)?

A: No, you don't need a proprietary library for bitbanging onewire. The following code is from an application for AVR µCs I did some years ago. If you used another µC family, you may have to implement the special Onewire/iButton crc functions yourself.
You don't need much more to communicate with an onewire slave chip. The OwReadROM() function is the only one I needed for my application but you can easily write functions for triggering a temperature conversion and reading the result based on that.
For the USB part, either use V-USB as I did (USB1.1 low-speed only) or an  USB-enabled µC.
#include <avr/io.h>
#include <util/delay.h>     /* for _delay_ms() */
#include <util/crc16.h>     /* for _crc_ibutton_update() */

/*
 *  Onewire host functions.
 */
static inline void owClear(void) {
    DDRB  |= (1 << PB0);
    PORTB &= ~(1 << PB0);
}

static inline void owSet(void) {
    PORTB |= (1 << PB0);
    DDRB  &= ~(1 << PB0);
}

static inline uchar owGet(void) {
    return ((PINB & (1 << PB0)) == 0);
}

/* Onewire idle load function. */
void owIdleLoad(void) {
    /* Release OW line from master. */
    owSet();

    /* Wait 20ms to allow slaves load their power capacitor. */
    _delay_ms(20);
}

/* Onewire transfer reset */
uchar owReset(void) {
    uchar sample;

    /* Reset all slaves. */
    owClear();
    _delay_ms(0.7);

    /* Release OW line from master. */
    owSet();
    _delay_ms(0.04);

    /* Check presence pulse from slave(s). */
    sample = owGet();

    /* Wait until slaves release OW line, max. 240µs. */
    _delay_ms(0.24);

    /* Return whether some device was present on onewire. */
    return sample;
}

/* Read a single bit from onewire. */
static uchar owReadBit(void) {
    uchar sample;

    /* Send bit marker. */
    owClear();
    _delay_us(1);
    owSet();
    _delay_us(10);

    /* Check if a slave keeps pulled the OW line low. */
    sample = owGet();

    /* Wait until slaves release OW line, max. 120µs. */
    _delay_us(120);

    /* Return bit from slave. */
    return (sample?0:0x80);
}

/* Read a byte from onewire. */
uchar owReadByte(void) {
  uchar data;

    data=owReadBit();
    data>>=1;
    data|=owReadBit();
    data>>=1;
    data|=owReadBit();
    data>>=1;
    data|=owReadBit();
    data>>=1;
    data|=owReadBit();
    data>>=1;
    data|=owReadBit();
    data>>=1;
    data|=owReadBit();
    data>>=1;
    data|=owReadBit();

  return data;
}

/* Write a bit to onewire. */
static void owWriteBit(uchar bit) {
    /* Start bit marker. */
    owClear();
    _delay_us(1);

    /* If bit should be 1, immediately release OW line. */
    if (bit & 0x01) {
        /* Release OW line. */
        owSet();

        /* Wait 60µs. */
        _delay_us(60);
    } else {
        /* Wait 60µs. */
        _delay_us(60);

        /* Release OW line. */
        owSet();
    }
}

/* Write a byte to onewire. */
void owWriteByte(uchar data) {
    owWriteBit(data);
    data>>=1;
    owWriteBit(data);
    data>>=1;
    owWriteBit(data);
    data>>=1;
    owWriteBit(data);
    data>>=1;
    owWriteBit(data);
    data>>=1;
    owWriteBit(data);
    data>>=1;
    owWriteBit(data);
    data>>=1;
    owWriteBit(data);
}

/* Read ROM onewire command. */
uchar owReadROM(void) {
    uchar i, crc;

    /* Onewire reset. */
    if (owReset() == 0) {
        /* No slave present. Fail. */
        return 0;
    }

    /* Read ROM for DS2400 and DS2401. Other slaves will ignore this command. */
    //owWriteByte(0x0f);
    owWriteByte(0x33);

    /* Read 8 bytes answer from OW slave. */
    crc = 0;
    for (i = 0; i < 8; i++) {
        iButtonBuffer[i] = owReadByte();
        crc = _crc_ibutton_update(crc,iButtonBuffer[i]);
    }

    /* Remember the iButton ID is valid. */
    iButtonBufferValid = (crc == 0);

    /* Success if crc is 0. */
    return iButtonBufferValid;
}


text:
Q: How can I make databasefields unchangeable in Django? Let's say I have Cars, CarTypes, and their BuildDates like this:
class Car(db.models):
    licence_name = models.CharField(max_length=64)
    car_type = models.ForeignKey(Type)

class Type(db.models):
    name = models.CharField(max_length=64)
    build_during = models.ForeignKey(BuildDate)

class BuildDate(db.models):
    begin = models.DateField(null=True)
    end = models.DateField(null=True)

    class Meta(object):
        unique_together = (('begin', 'end'),)

I want to have the BuildDates in a seperate table such I can do faster queries and other stuff with Django-external tools.
Since BuildDates are unique but shared between CarTypes, I want to make sure this: If the BuildDate d0 of one CarType t1 is changed, the other CarTypes are not affected and they still share the identical BuildDate d0 – but not with t1 which now has d1.  I believe it is necessary to create a new BuildDate d1 for that CarType t1. Is there a recommended or recommendable way to do this?

A: Use "editable" attribute. When you set "False", element will not be shown in the admin, that is, you can't change its value.
e.g.
licence_name = models.CharField(max_length=64, editable=False)


text:
Q: Точное регулярное выражение по нахождению IPv4-адресов Здесь я предложил пример регулярного выражения, которое, однако, будет находить и числа в промежутке между 256 и 999, что уже не IPv4. Наткнулся в книге на более точный шаблон:
(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))

Но тестирование показывает, что он прямо ошибочен, поскольку отсекается последняя цифра IP-адреса. Видимо, т. к. в модели стоят операторы | (или), обработчик регулярных выражений выбирает из двух возможных вариантов — к примеру, 20 и 200, — тот, который покороче.
Логично предположить, что я где-то допустил синтаксическую опечатку. Но выверял несколько раз, так и не отыскал оной.

В книге подсвечивается 200, а у меня 20. Что я делаю не так?

A: Всё решается очень просто.
Достаточно более длинные варианты альтернатив поставить перед более короткими.
Альтернативы в регулярных выражениях, можно сказать, имеют приоритет слева направо.
(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))

https://regex101.com/r/uJ0hU7/2
Данное регулярное выражение обладает более серьёзной проблемой: в IP-адресе могут быть ведущие нули. Разве недопустима запись 010.010.010.010 ?
Не знаю, где Вы нашли это регулярное выражение, но первый же результат из поиска regex ip4 лишен всех этих проблем:
((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

https://regex101.com/r/uJ0hU7/3

A: Я бы дополнительно ужесточил регулярное выражение:
^((25[0-5]|2[4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[4]\d|[01]?\d\d?)$

https://regex101.com/r/wkxYGz/2/
В варианте, предложенном ранее, в выборку попадают некорректные адреса вида:
001.234.100.1.1
336.245.123.4

A:
Видимо, т. к. в модели стоят операторы | (или), обработчик регулярных выражений выбирает из двух возможных вариантов — к примеру, 20 и 200, — тот, который покороче.

Если проблема действительно заключается в этом, то надо просто переставить выбираемые через | варианты в порядке уменьшения их длины.
Однако можно заметить, что чего-то типа 7891.2.3.4000 скорее всего выберется 91.2.3.40, потому я не вижу никаких проверок на символы по краям и адрес может вытаскиваться из любого текста.


text:
Q: While loop and for statement I am trying to build an online reading test for my students. I currently have two tables in my database : 'student' and 'questions'. In 'student', I have a row for each student which containts it's name, group number and answers to the questions. Questions cols are called question[1], question [2], and so on.
In 'questions', I have 4 cols : ID, 'first', 'chapter' and 'question'. 'first' is a true/false field, if it is the first question to a chapter its value is 1. I call those with a while loop.
echo '
';
$query = mysql_query("SELECT * FROM `question`");
while($row_q = mysql_fetch_assoc($query)) {
if($row_q['first']==1){
echo '
Chapter '.$row_q['chapter'].'

';
}
echo '
';
echo $row_q['question'];
echo '
';
echo '
';
}
echo '
';

It echoes beautifuly. Now, I'm trying to put an input field under each question so the student can give an answer and submit it at the end of the page. How can I do this? I tried using a for($i=1;$i<=10;$i++) statement since I want each field to be named with a different number, but no matter where I insert it, I either end up with a bunch of identical fields next to each other or my questions echoed over and over again.
I'm open to all suggestions. Thanks!

A: there's no need to do a for loop, you're already in a loop :) just set a variable called question number and increment it in the while loop.
$question_number =1;

echo '
';
$query = mysql_query("SELECT * FROM `question`");
while($row_q = mysql_fetch_assoc($query)) {
    if($row_q['first']==1){
        echo '
Chapter '.$row_q['chapter'].'

';
    }
    echo '
';
    echo "$question_number".$row_q['question']."";
    echo "<input type='text' name='$row_q[\'ID\']'></input>";
    echo '
';
    echo '
';

    $question_number++;
}
echo '
';

A:
echo '<input name="answer[' . htmlspecialchars($row_q['ID']) . ']" type="text" value="" />';

under the question text... Then in PHP var_dump($_REQUEST) to see the answers...
EDIT:
For displaying the saved answer, you'll want to do something like this:
echo '<input name="answer_' . $idx . '" type="text" ' .
  value="' . htmlspecialchars($student_row["answer_$idx"]) . '" />';

and maintain a counter $idx as you loop...
That's if your answer are laid out flat in the student table per your description and the answer value columns are named "answer_1" etc.
If the answers are normalized in a separate table, you can join the tables together:
select * from question q left join answer a on a.question_id = q.question_id and
  a.student_id = <current student id>


text:
Q: Why can't I update my ObservableCollection with Filtered CollectionView attached during unit testing? I've got an ObservableCollection in a ViewModel that I need to modify in code on a background thread (using a Task object). I've also got an ICollectionView attached to that collection. When I modify the collection at run-time, the code runs fine. In unit testing I get the error, "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."
I create the collection thusly (on the UI thread at run-time):
    CashDeliveryDepots = new ObservableCollection<CashDeliveryDepot>();
    FilteredCashDeliveryDepots = CollectionViewSource.GetDefaultView(CashDeliveryDepots);

and modify it using this code (which will be running on a non-UI thread at run-time):
    CurrentDispatcher.Invoke(() =>
    {
        foreach (var depot in depots)
        {
            CashDeliveryDepots.Add(depot);
        }
    });

The CurrentDispatcher class executes code according to whether or not there is an application dispatcher.
internal static class CurrentDispatcher
{
    internal static void Invoke(Action action)
    {
        if (Application.Current != null)
            Application.Current.Dispatcher.Invoke(action);
        else
            action();
    }
}

So at run-time the dispatcher is picked up correctly, the observable collection is updated and the filtered view updates too. When running the unit tests I get the exception at the point of trying to add a new item to the collection.
Can anyone suggest a way around this so I can get my tests working?


text:
Q: Use gatsby-image's tracedSVG as the actual picture TL;DR: Is it possible to use Gatsby's rendered tracedSVG from childImageSharp as the actual picture on your website?
Long version:
So, I was working on a small website for my recital with Gatsby earlier today and while I was hosting it on my machine the pictures load just fine, but when I deployed the project to Github Pages, the image files failed to load, only the tracedSVG placeholders loaded.
Now I am sure there is a solution for this; I haven't yet looked into that. The thing is, I kinda like how those artsy tracedSVGs look on my website, and I want to keep them. I can of course, just leave it as is, but if there is a proper and more elegant way of doing this, I'd love to know.

I tried
fluid
{
    tracedSVG
}

instead of
fluid
{
   ...GatsbyImageSharpFluid_tracedSVG
}

in the js file and the images and the placeholders failed to load.

A:
Is it possible to use Gatsby's rendered tracedSVG from childImageSharp
as the actual picture on your website?

Short answer: yes, you can. Your query should look like this:
export const query = graphql`
  query {
    file(relativePath: { eq: "/path/to/your/traced/svg/traced.svg" }) {
      childImageSharp {
        fluid(width: 125, height: 125) {
          ...GatsbyImageSharpFluid_tracedSVG
        }
      }
    }
  }
`

Then, use your gatsby-image:
export default ({ data }) => (

Hello gatsby-image

)


text:
Q: Sum method in LINQ with long type How can I get sum of some items in long type... here is mycode :
using (gEn myEntities = new gEn)
{
var load = (from items in myEntities.Orders
select items.PayO).DefaultIfEmpty(0).Sum();
}

but the Sum gives me int... I also wants to know if DefaultIfEmpty method has any conflict with Sum method when use it for long type... thanks in advance...

A: If Sum() returns an int it's because that's the data type of your collection. All these LINQ to Object methods are generic. And no, DefaultIfEmpty will have no side effects. It's just going to give you 0 if there are no items in the collection, then Sum is going to work on the result of that which is going to be an IEnumberable<int> with a single item which will have a value of 0.
I'm just assuming you're using EF here. If that is the case you need to either do a cast after you retrieve the data or change your model on the C# side so that it has long. You may also want to check what the data type for that table is because if you generated your C# model from the data source and it's using an int32, then that's probably what your table has too.

A: Sum returns whatever type the expression used in the select returns (provided it's one of the defined overloads).  If you want to return a long then cast items.PasO:
var load = (from items in myEntities.Orders
            select (long)(items.PayO)
           )
           .DefaultIfEmpty(0).Sum();

I also wants to know if DefaultIfEmpty method has any conflict with Sum method when use it for long type

No, DefaultIfEmpty works with any type, including long.  As long as there's a Sum overload for that type it works just fine.


text:
Q: create automatic datetime when update the data in postgresql(phppgadmin) create automatic datetime(date with timestamp) when update the data in postgresql(phppgadmin) on database table
Plese advise me
thanks

A: 1.if you use timestamp type in the column when you update the record then date time also updated
2.if you use varchar type in the column when you fire a query
demo
$sql = "update table_name set field_name=now() where your condition";