text:
Q: Delphi Kiosk mode template issue with C++ Builder (can find xml) I could desperately use some help with finding out why Embarcadero's Android Kiosk Lock mode template is having issues deploying.  I have C++ Builder 11.0 Alexandria, moved PAS files over and compiles and links.  However, when I deploy per Embarcadero directions, I get this error.

[PAClient Error] Error: E2312
C:\Users\rodge\Documents\Embarcadero\Studio\Projects\fun\Source\Android\Debug\Kiosk\AndroidManifest.xml:69: error: Error: No resource found that matches the given name (at 'resource' with value '@xml/device_owner_receiver').

Stock Android.manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<!-- BEGIN_INCLUDE(manifest) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.embarcadero.Kiosk"
    android:versionCode="1"
    android:versionName="1.0.0"
    android:installLocation="preferExternal">

    <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="30" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BIND_DEVICE_ADMIN" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_CALENDAR" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature android:glEsVersion="0x00020000" android:required="True"/>
    <application android:persistent="False"
        android:restoreAnyVersion="False"
        android:label="Kiosk"
        android:debuggable="true"
        android:largeHeap="False"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme"
        android:hardwareAccelerated="true"
        android:resizeableActivity="false">

        <!-- Our activity is a subclass of the built-in NativeActivity framework class.
         This will take care of integrating with our NDK code. -->
        <activity android:name="com.embarcadero.firemonkey.FMXNativeActivity"
            android:label="Kiosk"
            android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
            android:launchMode="singleTask"
            android:lockTaskMode="always">

            <!-- Tell NativeActivity the name of our .so -->
            <meta-data android:name="android.app.lib_name"
                android:value="Kiosk" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="com.embarcadero.rtl.notifications.NotificationAlarm"
  />

        <receiver android:name="com.kiosk.app.BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <receiver
            android:name="com.kiosk.admin.AdminReceiver"
            android:permission="android.permission.BIND_DEVICE_ADMIN">

            <meta-data
                android:name="android.app.device_admin"
                android:resource="@xml/device_owner_receiver"/>

            <intent-filter>

                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
                <action android:name="android.app.action.PROFILE_PROVISIONING_COMPLETE"/>

            </intent-filter>

        </receiver>
    </application>
</manifest>
<!-- END_INCLUDE(manifest) -->

The stock device_owner_reciever.xml file contains:
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <limit-password/>
        <watch-login/>
        <reset-password/>
        <force-lock/>
        <wipe-data/>
        <expire-password/>
        <encrypted-storage/>
        <disable-camera/>
    </uses-policies>
</device-admin>

I have tried adding to resource and as a file.  What am I missing here?

A: you must add the resource to the deployment

*

*press Project - Deployment

*select configuration (release/debug)

*press Add Files and find the file: device_owner_receiver.xml (you find it in xml folder)

the result should be:
   local path = xml\
   local name = device_owner_reciver.xml
   remote path = res\xml
   remote name = device_owner_reciver.xml


text:
Q: JQuery - Append variable to formdata of a form in file upload I'm trying to upload a file. The problem is I want to add a JSON variable to the form.
I will be needing that variable to my php file.
Here's my html:

 <form method="POST" id='closeoutfile_form' class = "upload_form" action = "{{ url('/store-files-closeout') }}">
   <input type="hidden" class="form-control" id = "closeoutfile_hidden" value = "none">

   <input type="hidden" name="_token" value="{{ csrf_token() }}">
   Closeout file:
   <input id="closeoutfile_input" type="file" name="closeoutfile_input[]" class="form-control file_upload" style="margin-right:10px;">

   <button type="submit" style="color:gray; margin-top:10px; margin-right:5px;" class="btn btn-default btn-sm pull-right save_btn" id = "closeoutfile_save" disabled> Save   </button>
 </form>

Here's my jquery AJAX
$('.upload_form').on('submit',function(e){
        id_value = $(this).attr('id').replace('_form','');
        formdata = new FormData($(this));
        formdata.append('id_value',JSON.stringify(id_value));  // i want to add this variable
        $(this).ajaxSubmit({
            beforeSubmit: function() {
                $("#progress-bar-"+id_value).width('0%');
            },
            uploadProgress: function(event, position, total, percentComplete) {
                $("#progress-bar-"+id_value).width(percentComplete + '%');
                $("#progress-bar-"+id_value).html('
' + percentComplete + ' %
')
            },
            success: function() {

            }
        });
    });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mobile API registration security I have web and mobile versions of registration API. I have CAPTCHA in web-version to verify human or bot. Im afraid that someone can get mobile api registration parameters, make script and begin to brute force user's emails etc. And i don't want to make CAPTCHA in mobile app.
What can i do to verify real device?

A: My suggestion is you need to encrypt the payload using any encryption algorithm like AES or RSA so that attacker cannot get parameters easily or did not get.
Also you can apply following in client-server communication for better security,
1> Cryptographic algorithm with password based key.
2> Use of  SSL


text:
Q: Need example for testing an asp.net web handler deployed on a server I have modified asp.net web handler and deployed it on a server.
The handler works greate on my local machine using a static XML file but
is giving IIS 500 errors when deployed.
Is there and example which I could use to modify my code to run against a
live data feed ?
This is what I have used with the static file :
WebRequest req = null;
            WebResponse rsp = null;
            try
            {
                string uri = "https://mytestSite.com/Test_Handler.ashx";
            req = WebRequest.Create(uri);
            req.Method = "POST";        // Post method
            req.ContentType = "text/xml";     // content type

            // Wrap the request stream with a text-based writer
            StreamWriter writer = new StreamWriter(req.GetRequestStream());

            // Write the XML text into the stream
                            //StreamReader reader = new StreamReader(Server.MapPath("~/20121129-0121-1.xml"));

            -- Would this line capture the stream ????????
            StreamReader reader = new StreamReader(req.GetRequestStream());

           string ret = reader.ReadToEnd();
           reader.Close();

            writer.WriteLine(ret);
            writer.Close();

            // Send the data to the webserver
            rsp = req.GetResponse();         //Calls the handler code
            StreamReader sr = new StreamReader(rsp.GetResponseStream());
            string responseString = sr.ReadToEnd();
            sr.Close();


text:
Q: Как изменить duration по клику? Доброго времени суток! Я написал простенький аудиоплеер. Всё работает отлично, но недавно захотел реализовать одну фишку, которая есть во вконтактовском аудиоплеере: время воспроизведения песни меняется по клику на него (отображается либо текущее время воспроизведения либо общее время, которое уменьшается во время прослушивания). Так вот: как сие реализовать?
Вот код для код активити, где отображаем duration:
 private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        long totalDuration = mp.getDuration();
        long currentDuration = mp.getCurrentPosition();
        // Displaying Total Duration time
        songTotalDurationLabel.setText(""+utils.getReversedProgressPercentage(currentDuration,totalDuration));
        // Displaying time completed playing
        songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
        // Updating progress bar
        int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
        //Log.d("Progress", ""+progress);
        songProgressBar.setProgress(progress);
        // Running this thread after 100 milliseconds
        handler.postDelayed(this, 100);
    }
};

getProgressPercentage() для отображения текущего времени воспроизведения,а getReversedProgressPercentage() отображает totalDuration,который уменьшается по ходу воспроизведения.
Новый вариант Runnable с меняющимся по клику duration:
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
    final long totalDuration = mp.getDuration();
    final long currentDuration = mp.getCurrentPosition();        songTotalDurationLabel.setText(""+utils.getReversedProgressPercentage(currentDuration,totalDuration));
    songTotalDurationLabel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isCurrent) {
                isCurrent = false;
                songTotalDurationLabel.setText("" + utils.milliSecondsToTimer(currentDuration));
            } else {
                isCurrent = true;
                songTotalDurationLabel.setText("" + utils.getReversedProgressPercentage(currentDuration, totalDuration));
            }

        }

    });

        int progress =(int)(utils.getProgressPercentage(currentDuration, totalDuration));
        //Log.d("Progress", ""+progress);
        songProgressBar.setProgress(progress);
        // Running this thread after 100 milliseconds
   handler.postDelayed(this, 4000);
    }
};

A: Думаю нужно вынести часть переменных вне класса, так будет хранится их состояние. Привязываешь клик - меняешь состояние. Если я правильно понял вопрос конечно.
Еще можно привязать к прогресс-бару обработчик, который будет получать тек значание и менять твою переменную или несколько.


text:
Q: Magento 2 : Change Language Code I'm facing issues while update language code for website.
<!doctype html>
<html lang="en">

I want to change it with en-GB. I've already locale setup with default configurations.
Any help would be appreciate.

A:
Set Locale from Admin >> Store >> Configuration >> General >> General >> Locale Option >> Locale >> English (United Kingdom)

Set above configuration and run below command, It will generate only pub\static\frontend\VendorName\thmemeName\en_GB
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy

A:

Follow these steps to change the lanugage.


text:
Q: Favouriting a question then leaving it quickly crashes the Android app When you favourite a question, this little flydown notification appears saying "Post favorited":

(I don't know if it's actually called a flydown, but stick with me.)
The same kind of notification appears when you unfavourite a question.
Here's how to crash the app:

*

*Visit a question.

*Favourite it.

*Hit Back to leave the question before that flydown notification appears. If you've got a little bit of network latency, that will give you a better opportunity to do it.

*Wait for the crash! It'll happen around the time that notification should have appeared, I think.

This isn't a problem with other notifications. For example, if I try to remove my upvote on that question then hit back, the error saying I can't remove my upvote will still appear even though I'm now on the questions list.
This occurs in app version 1.0.51 1.0.77 on a HTC One running Android 4.4.3.


text:
Q: Assembly: is numeric operations for signed different from that of unsigned? Does numeric operations for (1) two signed integers and (2) for two unsigned integers result in different assembly code? Assume integer width are the same, say, 64-bits.
By "numeric operations" I mean operations like +, -, *, /, % (especially the last two). My guess of the answer is "they are the same" judging from the x86 assembly reference and the impression that signedness is how computer display a given bit pattern to screen, but I'd like to verify this claim. It might seem a silly question..


text:
Q: Access violation in Windows Form project that uses fstream in a library I have a lib project with a few utility functions of mine and it works fine with console applications.
Now I started a Windows Form application, included that lib and it gives me an "Exception thrown at 0xxxx (ntdll.dll) in : 0xC0000005: Access violation reading location 0xxxx."
The application code is just the code Visual Studio added to the new project. No code of my own added, except the #include of my lib header.
I commented my lib code, piece by piece and found that when I comment the line "ofstream MyLog;" the exception goes away.
I did rebuild this project from scratch a couple of time: same results. Pretty much: (1) Create new WinForm project, (2) add existing project MyLibTest, (3) 'Add reference...' to connect them, (4) add the #include in the main cpp and (5) run it.
I dont know if this is relevant, but since I started this WinForm project, Visual Studio spent many, many hours downloading symbols from Microsoft Symbol Server. (elsewhere here at stackoverflow it is said that this MS server is really slow)
This is relevant: I am new to c++ and I have created several mini projects in Visual Studio 2015 to experiment with several aspects of the language (file reading, classes, string manipulation, vectors, lists, Windows forms, etc). Now I am trying to put all of them together.
My code
//------ MyLibTest.h --------

#pragma once

#include <stdio.h>
#include <string>
#include <map>
#include <Windows.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <time.h>
#include <cstdarg>
#include <memory>

//------ MyLibTest.cpp --------

#include "MyLibTEST.h"

using namespace std;

ofstream MyLog;     // <<<< if i comment this line, the Access violation exception does not happen

WinForm application CODE added by Visual Studio 2015
//------ MyForm.h --------

 #pragma once

namespace MyWindowsFormTest {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for MyForm
    /// </summary>
    public ref class MyForm : public System::Windows::Forms::Form
    {
    public:
        MyForm(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~MyForm()
        {
            if (components)
            {
                delete components;
            }
        }

    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->components = gcnew System::ComponentModel::Container();
            this->Size = System::Drawing::Size(300,300);
            this->Text = L"MyForm";
            this->Padding = System::Windows::Forms::Padding(0);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
        }
#pragma endregion
    };
}

//------ MyForm.cpp --------

#include "Q:\MyDesv\Visual Studio Projects\Projects\MyLibTest\MyLib\MyLibTest.h"

#include "MyForm.h"

using namespace System;
using namespace System::Windows::Forms;

[STAThread]
void Main(array<String^>^ args)
{
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);

    MyWindowsFormTest::MyForm form;
    Application::Run(%form);
}

Call Stack
    ntdll.dll!RtlValidateHeap() Unknown
    KernelBase.dll!_HeapValidate@12()   Unknown
>   ucrtbased.dll!_CrtIsValidHeapPointer(const void * block) Line 1407  C++
    ucrtbased.dll!_msize_dbg(void * block, int block_use) Line 1059 C++
    ucrtbased.dll!_msize(void * block) Line 38  C++
    ucrtbased.dll!_recalloc_dbg(void * block, unsigned int count, unsigned int element_size, int block_use, const char * file_name, int line_number) Line 784   C++
    ucrtbased.dll!_register_onexit_function::__l2::<lambda>() Line 112  C++
    ucrtbased.dll!__crt_seh_guarded_call<int>::operator()<void <lambda>(void),int <lambda>(void) &,void <lambda>(void) >(__acrt_lock_and_call::__l2::void <lambda>(void) && setup, _register_onexit_function::__l2::int <lambda>(void) & action, __acrt_lock_and_call::__l2::void <lambda>(void) && cleanup) Line 204   C++
    ucrtbased.dll!__acrt_lock_and_call<int <lambda>(void) >(const __acrt_lock_id lock_id, _register_onexit_function::__l2::int <lambda>(void) && action) Line 912   C++
    ucrtbased.dll!_register_onexit_function(_onexit_table_t * table, int(*)() function) Line 84 C++
    CppWinForm2.exe!_onexit(int(*)() function) Line 268 C++
    CppWinForm2.exe!atexit(void(*)() function) Line 276 C++
    CppWinForm2.exe!std::`dynamic initializer for '_Fac_tidy_reg''() Line 65    C++
    [External Code]
    mscoreei.dll!__CorExeMain@0()   Unknown
    mscoree.dll!__CorExeMain_Exported@0()   Unknown
    kernel32.dll!@BaseThreadInitThunk@12()  Unknown
    ntdll.dll!__RtlUserThreadStart()    Unknown
    ntdll.dll!__RtlUserThreadStart@8()  Unknown

A: This is a known issue (since around 2007). It is related to having a winforms project with native C++ static objects. It seems that Winform projects by default skip the crt initialization, which obviously has an impact on any static objects.
You can read more about it in This link from a Microsoft support person and This link from another stackoverflow question.
Basically your Winforms project has a Main function that looks something like
[STAThread]
void Main(array<String^>^ args)
{
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);

    MyWindowsFormTest::MyForm form;
    Application::Run(%form);
}

First step is change the main declaration to:
int main(..)

Then go Project->Properties->Linker->Advanced->Entry Point. Change this from "Main" to something like "?mainCRTStartupStrArray@@$$FYMHP$01EAPE$AAVString@System@@@Z". This may vary depending on your VS version.
IMO though, unless you are deep into project development rather don't use WinForms. As I understand it, the support is discontinued... .


text:
Q: learning django and i getting this, TemplateSyntaxError, message erro message
16          {% if request.user.is_authenticated %}
17

18

19                  My dashboard
20

21
28          {% endif %}

this is the code thats giving me the error i don't know what am i doing wrong
error message: Could not parse the remainder: '=="dashboard"' from 'section=="dashboard"'

A: Francisco,
You need to put a space between the operator (==) and the variable (section) and the value to be compared ("dashboard").
          {% if request.user.is_authenticated %}

                  My dashboard

          {% endif %}


text:
Q: How do i display multiple MessageDialog with JOptionPane How do I display a message dialog for every char in a string with the JOptionPane?
I'm converting the string to char already and storing it in an ArrayList but I cannot make 1 char appear for every JOptionPane.
Here's my code:
public static void main(String[] args) {
    ArrayList<Character> arr = new ArrayList<Character>();

    String oracion = JOptionPane.showInputDialog(null,"Favor Ingrese oracion: ");

    for(int i=0;i<oracion.length();i++)
    {
        arr.add(oracion.charAt(i));
        JOptionPane.showMessageDialog(null, arr);

    }

A: Try this:
for (int i = 0; i < oracion.length(); i++) {
    JOptionPane.showMessageDialog(null, oracion.charAt(i));
}

instead of
for(int i=0;i<oracion.length();i++)
{
    arr.add(oracion.charAt(i));
    JOptionPane.showMessageDialog(null, arr);

}

and you don't need this line anymore:
ArrayList<Character> arr = new ArrayList<Character>();

A: You should replace code
arr.add(oracion.charAt(i));
JOptionPane.showMessageDialog(null, arr);

with
JOptionPane.showMessageDialog(null, oracion.charAt(i));


text:
Q: How to slide in a UIView in a portrait mode application? I am working on an iPhone application that runs in portrait mode only. This app have only view controller and 1 interface file (.xib). I want to slide in some additional views when user taps on button on either toolbar / navigation bar. Let's say like info button on navigation bar. When I click it UIView should slide in from bottom. And when user taps on done button on that view that view slides down. I have made separate uiview for those views in same xib. I also looked into couple of transition examples by others but could not got that concept. Can any one give me some pointers on this ?

A: You can reset the frames through animation like
UIView *view= [[UIView alloc] initWithFrame:CGRectMake(0.0f,-100.0f,320.0f,100.0f)];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationTransition:UIViewAnimationTransitionNone forView:[self view]      cache:YES];

[view setFrame:CGRectMake(0.0f,0.0f,320.0f,100.0f)];

[UIView commitAnimations];

A: I think you mean modal view transitions.  Like what the app store does when you enter a gift card on the iPhone.
Example:
UIViewController *controllerForSecondView = ..;
controllerForSecondView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:controllerForSecondView animated:YES];

Then make a done button in the second xib and call:
dismissModalViewController


text:
Q: limit including box function Which of the following is/are correct ?
$(1)\lim_{x\to 0}\big[\frac x{sinx}\big]=1$
$(2)\lim_{x\to 0}\big[\frac x{cosx}\big]=0$
$(3)\lim_{x\to 0}\big[\frac {sinx}x\big]=0$
$(4)\lim_{x\to 0}\big[\frac {cosx}x\big]=1$
My attempt:-
We have $\lim_{x\to 0}\frac{sinx}x=\lim_{x\to 0}\frac x{sinx}=1$
So for a given $\epsilon \gt 0, \exists \delta \gt 0$ such that
$1-\epsilon \lt \frac{sinx}x,\frac x{sinx}\lt 1+\epsilon, \forall x\in (-\delta,\delta)$ (Actually there are two $\delta$'s , I am selecting the minimum out of them.
Now if $ \sin x \lt$ or $\gt x$ according as $x\gt $ or $\lt 0$.
So for $x\in (0,\delta)$,
$1-\epsilon \lt \frac{\sin x}x \lt 1$
Thus $\lim_{x\to 0+}\big[\frac{\sin x}x \big]=0$
For $x\in (-\delta,0)$
$\sin x\gt x \Rightarrow \frac{\sin x}x\lt 1$ (since $x\lt 0$)
By similar reasoning as above
$\lim_{x\to 0-}\big[\frac{\sin x}x \big]=0$
Hence , $\lim_{x\to 0}\big[\frac{\sin x}x\big]=0$
In the case of $\frac x{\sin x}$ , we would have
$1\lt \frac x{\sin x}\lt 1+\epsilon$, for $x\in (-\delta,\delta)$
Thus $\lim_{x\to 0} \big[\frac x{\sin x}\big]=1$
So $(1)$ and $(3)$ are true
Well for $(4)$ ...
$\cos x\ge 1-\frac{x^2}2,\forall x \in \mathbb{R}$
So for $x\gt 0$, we have
$\frac{\cos x}x\ge \frac 1x-\frac x2\to \infty$ as $x\to 0$
So the limit in $(4)$  does not exist.
For $(2)$,
Now , $\lim_{x\to 0}\frac x{\cos x}=0$
So for arbitary $\epsilon \gt 0, \exists \delta \gt 0$ such that
$-\epsilon  \lt \frac x{\cos x} \lt \epsilon$
Now for $x\in (0, \delta), 0\lt \frac x{\cos x}\lt \epsilon $ (since $\cos x\gt 0$ in close neighbourhood of zero) giving
$\lim_{x\to 0+} \big[\frac x{\cos x}\big]=0$
Similarly,
$\lim_{x\to 0-} \big[\frac x{\cos x}\big]=0$
Thus
$\lim_{x\to 0} \big[\frac x{\cos x}\big]=0$
So $(2)$ is true.
I request you to go through my solution and check if there is any technical difficulty.
I would like any alternative ideas. Thanks for your time.


text:
Q: Ruby MySQL backups using System() call with spaces So I'm trying to create local daily backups of my MySQL database using a ruby script, but I'm not able to run this because there are issues in the mysql_dump_call string, when I call it in my script.
time = Time.new

puts "Current time: #{time.inspect}"

backup_path = "C:\\redmine_backups\\#{time.year}-#{time.month}-#{time.day}-time-#{time.hour}h-#{time.min}min-#{time.sec}sec\\"
backup_filename = "#{time.year}-#{time.month}-#{time.day}-redmine.sql"

system("mkdir #{backup_path}")

mysql_dump_executable = "C:\\Program Files\\MySQL\\MySQL Workbench 8.0 CE\\mysqldump.exe"

mysql_dump_call = "C:\\Program Files\\MySQL\\MySQL Workbench 8.0 CE\\mysqldump.exe --defaults-file=\"C:\\ProgramData\\MySQL\\MySQL Server 8.0\\my.conf\"
--user=root --host=localhost --protocol=tcp --port=3306 --default-character-set=utf8 --skip-triggers \"redmine\" > #{backup_path}"

if File.exist?(mysql_dump_executable)
    system('start', '', mysql_dump_call)
else
    puts "MySQLDump executable does not exist."
end

Anyone have any idea why it isn't working?

It looks like it's including my --defaults-file which is supposed to be a parameter. It works fine when I run this in powershell directly, or in command prompt.

A: You don't have a file with the name of the string stored in mysql_dump_call. Look at the documentation of the system function:

system([env,] command... [,options]) → true, false or nil
Executes command… in a subshell. command… is one of following forms.
commandline          : command line string which is passed to the standard shell

cmdname, arg1, ...   : command name and one or more arguments (no shell)

[cmdname, argv0], arg1, ... : command name, argv[0] and zero or more arguments

From what I know, the start command wants to see the program to start and the arguments as individual parameters. Hence I would try something like:
 system('start', mysql_dump_executable, '--defaults-file=\"C:\\ProgramData\\MySQL\\MySQL Server 8.0\\my.conf\"', ....)

Or use the command line form:
system("start #{mysql_dump_call}")


text:
Q: Fetch and display Wordpress category of custom post type I am currently working on a personal project and the this page basically has two tabs each will display the archive for specific categories under one custom post type called webinar.
I am calling the category in one of the tabs using
<?php query_posts('category_name=demos-on-demand-videos'); ?>

However when i do this i' just getting the no post's found screen, what am i doing wrong? I am trying to display the post archive from the category demos-on-demand-videos which is under the webinar custom post type.

A: use this

query_posts( array( 'post_type' => 'webinar','your-custom-taxnomy' => 'demos-on-demand-videos' ) );

while ( have_posts() ) :
the_post();
$post_id = $post->ID;
endwhile;

Follow this link:
http://eyan16.wordpress.com/2013/09/16/how-to-fetch-posts-from-custom-posts-type-with-custom-taxonomy/

A: Make a page template for each of your tabs and use this custom loop in it. Make sure to adjust it for your specific post type, taxonomy, or term.
<?php $args=array(
'post_type' => 'webinar', //set the post_type to use.
'taxonomy' => 'demos-on-demand-videos', // set the taxonomy to use.
'term' => 'term1', //set which term to use or comment out if not using.
'posts_per_page' => 10  // how many posts or comment out for all.
);

$webinarloop = new WP_Query($args);
if($webinarloop->have_posts()) : while($webinarloop->have_posts()) :
$webinarloop->the_post();

get_template_part( 'content' ); //or whatever method you use for displaying your content.

endwhile; endif; //end the custom post_type loop

?>

A: This code works for me just fine
* x is taxonomy name name you have created
* y is category slug
      $args = array('post_type' => 'client','posts_per_page'=>'8','order'=>'DESC','x'=>'y');

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();


text:
Q: Запуск Python скриптов на Apache2: mod_python или mod_wsgi? Нужно запустить файлы .py на Apache2. Пробовал настроить CGI - выдавало "Internal Server Error". Максимум, что смог сделать, - содержимое .py файла в браузере отобразить как текст.
Хотелось бы написать легкий сайт и залить его на тестовый хостинг. Столкнулся и с тем, что Python без каких-то mod_python или mod_wsgi не работает. Устанавливал mod_python, но не знал как настроить.
Использую Ubuntu 14.04 LTS, Apache 2, Python 3.4.0.

A: mod_python hello world
в репозитории ubuntu 14.04, к сожалению, есть пакет с модулем только для python 2.*

*

*необходимо установить пакет libapache2-mod-python:
$ sudo apt-get install libapache2-mod-python

*в конфигурации дефолтного virtualhost-а добавьте, если её нет, секцию directory (путь здесь взят из дефолтной конфигурации) и впишите в неё три директивы:
<directory /var/www/html>
  addhandler mod_python .py
  pythonhandler hello
  pythondebug on
</directory>

*создайте файл /var/www/html/hello.py следующего минимального содержания:
import sys

from mod_python import apache

def handler(req):
  req.content_type = 'text/plain'
  req.write("hello world! " + sys.version)
  return apache.OK

*перезапустите apache
$ sudo service apache2 restart

*запустите скрипт gui-браузером, или консольным, например, curl-ом:
$ curl http://localhost/test.py
hello world! 2.7.6 (default, Jun 22 2015, 18:01:27)
[GCC 4.8.2]

mod_wsgi hello world
в репозитории есть пакет и для python 3

*

*установите пакет с модулем:
$ sudo apt-get install libapache2-mod-wsgi-py3

*в конфигурации дефолтного virtualhost-а добавьте строку, предварительно закомментировав (если есть) все секции directory:
wsgiscriptalias / /var/www/html/hello.wsgi

*создайте файл /var/www/html/hello.wsgi такого содержания:
import sys

def application(environ, start_response):
  status = '200 OK'
  output = 'hello world from wsgi! ' + sys.version

  response_headers = [('Content-type', 'text/plain'),
                      ('Content-Length', str(len(output)))]
  start_response(status, response_headers)

  return [output]

*отключите модуль mod-python — вместе они работать не будут:
$ sudo a2dismod python

*перезапустите apache:
$ sudo service apache2 restart

*запустите скрипт gui-браузером, или консольным, например, curl-ом:
$ curl http://localhost/
hello world from wsgi! 3.4.0 (default, Jun 19 2015, 14:24:19)
[GCC 4.8.2]


text:
Q: Angular directive change ngmodel value from null to undefined breaks validation I have created a plnkr to describe my problem: Link to plnkr
Problem description:
I have a number field, the value from which is written to the model. First I implemented this feature like the first input. The problem with this implementation is that if I input something and then delete, I have the following model:
{"firstNumber":null,"secondNumber":64}

For me unfortunately this representation is not acceptable, I need the following result:
{"secondNumber":64}

For that I taken the directive and implemented the second field. Now I receive the correct output, but when I remove the value, the form becomes invalid.
Also I added third and fourth input to demonstrate that the directive also breaks the required validation.
So, the question is:
How can I improve the input field not to have the model
{"firstNumber":null,"secondNumber":64}

but
{"secondNumber":64}

and do not broke the validation mechanism of Angular forms.
For reference:
I have the following HTML:

Validating input inside ng-repeat with Angular 1.3

<form name="vm.myForm" novalidate>
  <input type="number" ng-model="vm.fields.firstNumber" name="firstNumber">
  <input type="number" ng-model="vm.fields.secondNumber" name="secondNumber" null-to-undefined>

  <input type="number" ng-model="vm.fields.thirdNumber" name="thirdNumber" ng-required = "true">
  <input type="number" ng-model="vm.fields.fourthNumber" name="fourthNumber" null-to-undefined ng-required="true">
</form>

And following controller and directive code:
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  var vm = this;

  vm.fields = {};
  vm.fields.firstNumber = 12;
  vm.fields.secondNumber = 24;
  vm.fields.thirdNumber = 64;
  vm.fields.fourthNumber = 128;

});

app.directive('nullToUndefined', function($timeout) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attrs, ctrl) {
      ctrl.$parsers.push(function(viewValue, modelValue) {
        if (viewValue === null) {
          $timeout(function() {
            //ctrl.$setValidity('number', true);
          });
          return undefined;
        }
        return viewValue;
      });
    }
  };
});

p.s. I cut the code as much as possible to reproduce the problem from my main project. I would appreciate any solution, but it would be very cool, if somebody can suggest the solution, which:
1. Shows good performance
2. Behaves in angular way.

A: You should probably focus on other solution, instead of writing directive.
You have object with props (firstNumber, secondNumber, ...).
You need to validate property with Angular (is null ? is correct number ?).
Then, you need to filter the object props with non-null values, without mutation of your model : your input is bind to model property, if you destroy a property, Angular can't be able to validate and fail.
We can do it :

*

*Select all keys of a.fields

*Iterate all keys, filters

*We got all non-null keys

*Reduce non-null keys to a new object, without mutation of "a"

const a = {
  fields: {
    a: 1,
    b: 2,
    c: null,
  },
};

// After form validation
const newA = Object
  .keys(a.fields)
  .filter(k => a.fields[k] !== null)
  .reduce(
    (accumulator, k) =>
      Object.assign(
        accumulator,
        {
          fields: Object.assign(accumulator.fields, { [k]: a.fields[k] })
        }
      ),
    { fields: {} }
  );

And if you need to filter undefined + null, just do little check on filter :
  .filter(k => a.fields[k] != null)

Edit : fix code.


text:
Q: Not able to open jupyter notebook on my Windows10 system using anaconda navigator I am trying to open Jupyter notebook on my windows 10 system using anaconda navigator but not able to open it as it is showing following error.
Traceback (most recent call last):
File "C:\Users\kaushiki\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 10, in
import sqlite3
ModuleNotFoundError: No module named 'sqlite3'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\kaushiki\Anaconda3\Scripts\jupyter-notebook-script.py", line 6, in
from notebook.notebookapp import main
File "C:\Users\kaushiki\Anaconda3\lib\site-packages\notebook\notebookapp.py", line 85, in
from .services.sessions.sessionmanager import SessionManager
File "C:\Users\kaushiki\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 13, in
from pysqlite2 import dbapi2 as sqlite3
ModuleNotFoundError: No module named 'pysqlite2'


text:
Q: How to fix error in converting "numeric string" to float data type I am trying to Create a Web crawler which could monitor the product prices on e-commerce sites
from bs4 import BeautifulSoup

URL = "https://www.amazon.in/Apple-MacBook-Pro-9th-Generation-Intel-Core-i9/dp/B07SDPJ531/ref=sr_1_10?keywords=macbook+pro&qid=1568561733&sr=8-10"

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36"}

page = requests.get(URL, headers = headers )

soup = BeautifulSoup(page.content, 'html.parser')

title = soup.find(id = "productTitle").getText()
price = soup.find(id = "priceblock_ourprice").getText()
converted_price = float(price[1:10])
print(title.strip())
#print(price)
print(converted_price)

I got an error
 Traceback (most recent call last):
  File "C:/Users/siddi/PycharmProjects/webscraping/venv/amazonscraping.py", line 15, in <module>
    converted_price = float(price[1:10])
ValueError: could not convert string to float: '\xa02,29,990'

A: This is a trivial problem, the text contains ,[comma] instead of .[decimal] and also unicode character for currency's symbol, So you'll have to strip them off. Try below code snippet
converted_price = price[1:10].replace(',','.') # replace , with .
converted_price = ''.join([ch for ch in converted_price if ch in '0123456789.')]) # remove everything except decimal and digits
converted_price = float(converted_price) # now do the convertion


text:
Q: Can the Amazon AMI Operating System (in particular 2016.03) use huge pages on a paravirtual (PV) instance? I don't believe huge pages work on PV machine running Amazon's AMI OS. I would like to know if this is related to the Amazon OS, or the virtualisation type. I believe huge pages can be enabled (somehow) on a PV machine, but it is more generally supported on a HVM virtualisation type. Is that right?
I believe Amazon 2016.03 is running a modified version of Centos 6.x.
I am using Amazon Linux AMI 2016.03, but I don't think that really matters.
Huge pages are recommended with the database I am using.
References both relating to Oracle (DB, I think):

*

*https://forums.aws.amazon.com/message.jspa?messageID=406807

*https://www.pythian.com/blog/linux-hugepages-for-oracle-on-amazon-ec2-possible-but-not-convenient-easy-or-fully-supported/
Related question with a different OS (Debian):
How can I use huge pages and libhugetlbfs on a Debian EC2 PVM instance?


text:
Q: logic behind vanity numbers i started learning to program a few months ago. Totally love the idea and the concept of it. Im currently learning to program in vb6 as ive heard it is easy to learn.
Id like to make a basic program where the inputed phone number gives out vanity numbers for it. This sounded very easy to me until  i started gathering ideas and the logic behind the program.
I cant seem to figure out the logic behind it to save my life. I have googled and have done some research but wasnt able to find anything on the topic
If someone could explain to me how i can approach this idea, id very much appreciate that
thanks in advance

A: You need to define a vanity number or we cannot answer. For discussion I'm assuming the last 4 digits to be two pairs.
This is VBScript. Vbscript is legal VB6. However you'll have to set a reference to Microsoft VBScript Regular Expressions 5.5.
xmlstring = "2756-1122"
Set regEx = New RegExp
regEx.Pattern = "\d\d\d\d-(\d)\1(\d)\2"
regEx.IgnoreCase = True
regEx.Global = True
Msgbox regEx.Test(xmlstring)

Test that the number is 4 digits, a dash, then two pairs of numbers.
\d Matches a digit character. Equivalent to [0-9].
\num Matches num, where num is a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.


text:
Q: Composition, Inheritance, and Aggregation in JavaScript There is a lot of information about composition vs inheritance online, but I haven't found decent examples with JavaScript. Using the below code to demonstrate inheritance:
function Stock( /* object with stock names and prices */ ) {
    for (var company_name in arguments[0]) {
        // copy the passed object into the new object created by the constructor
        this[company_name] = arguments[0][company_name];
    }
}

// example methods in prototype, their implementation is probably redundant for
// this question, but list() returns an array with toString() invoked; total()
// adds up the stock prices and returns them. Using ES5 feature to make
// inherited properties non-enumerable

Stock.prototype =  {
    list: function () {
        var company_list = [];
        for (var company_name in this)
            company_list.push(company_name);
        return company_list.toString();
    },
    total: function () {
        var price_total = 0;
        for (var company_name in this)
            price_total += this[company_name];
        return '$' + price_total;
    }
};

Object.defineProperties(Stock.prototype, {
    list: { enumerable: false },
    total: { enumerable:false }
});

var portfolio = new Stock({ MSFT: 25.96, YHOO: 16.13, AMZN: 173.10 });
portfolio.list();  // MSFT,YHOO,AMZN
portfolio.total(); // $215.19

(To make the code smaller, you can leave out the method implementations, like: Stock.total = function(){ /* code */ } I just put them in there to be fancy). If composition is favored for a lot of situations in OOP, how come most people using JavaScript seem to only use prototypes and inheritance? I did not find a lot of information about composition in JavaScript online, only in other languages.
Can someone give me an example using the above code to demonstrate composition and aggregation?

A: The language is irrelevant when dealing with composition vs inheritance.  If you understand what class is and what an instance of a class is, then you have all you need.
Composition is simply when a class is composed of other classes; or to say it another way, an instance of an object has references to instances of other objects.
Inheritance is when a class inherits methods and properties from another class.
Let's say you have two functionality, A and B.  You want to define a third functionality, C, that has some or all of both A and B.  You could either make C extend from B and A, in which case C has everything B and A has because C isA B and A, or you can make each instance of C have an instance of A and an instance of B, and invoke items on those functionalities.  In the latter case, each instance C in effect wraps an instance of B and an instance of A.
Of course, depending on the language, you might not be able to have a class extend from 2 classes (e.g. Java doesn't support multiple inheritance), but that's a language specific detail that has nothing to do with the concept.
Now, for the language specific details...
I used the word class, but javascript has no notion of Class as such.  It has objects, and thats it (other than the simple types).  Javascript uses prototypal inheritance, which means it has a way of efficiently defining objects and the methods on those objects (this is the topic for another question; you can search SO as there are already answers.)
So going with our example above, you have A, B, and C.
For inheritance, you would have
// define an object (which can be viewed as a "class")
function A(){}

// define some functionality
A.prototype.someMethod = function(){}

If you wanted C to extend A, you would do
C.prototype = new A();
C.prototype.constructor = A;

Now every instance of C would have the method someMethod, because every instance of C "isA" A.
Javascript doesn't have multiple inheritance* (more on this later), so you can't have C extend both A and B.  You can use composition, however, to give it the functionality.  Indeed, this is one of the reasons composition is preferred by some over inheritance; there are no limits on combining functionality (but this isn't the only reason).
function C(){
   this.a = new A();
   this.b = new B();
}

// someMethod on C invokes the someMethod on B.
C.someMethod = function(){
    this.a.someMethod()
}

So there are your simple examples for both inheritance and composition.  However, this is not the end of the story.  I said before that Javascript does not support multiple inheritance, and in a sense it doesn't, because you can't base the prototype of an object off the prototypes of multiple objects; i.e. you can't do
C.prototype = new B();
C.prototype.constructor = B;
C.prototype.constructor = A;

because as soon as you do the third, line, you just undid the the second line.  This has implications for the instanceof operator.
However, this doesn't really matter, because just because you can't redefine the constructor of an object twice, you can still add any methods you want to the prototype of an object.  So just because you can't do the above example, you can still add anything you want to C.prototype, including all the methods on the prototypes of both A and B.
Many frameworks support this and make it easy.  I do a lot of Sproutcore work; with that framework you can do
A = {
   method1: function(){}
}

B = {
   method2: function(){}
}

C = SC.Object.extend(A, B, {
   method3: function(){}
}

Here I defined functionality in object literals A and B, and then added the functionality of both to C, so every instance of C has methods 1, 2, and 3.  In this particular case, the extend method (provided by the framework) does all the heavy lifting of setting up the prototypes of the objects.
EDIT -- In your comments, you bring out a good question, namely "If you use composition, how do you reconcile the scope of the main object against the scope of the objects of which the main object is composed".
There are a bunch of ways.  The first is simply to pass arguments.  So
C.someMethod = function(){
    this.a.someMethod(arg1, arg2...);
}

Here you are not messing with scopes, you are simply passing arguments around.  This is a simple and very viable approach. (the arguments can come from this or be passed in, whatever...)
Another way to do it would be to use the call (or apply) methods of javascript, which basically allows you to set the scope of a function.
C.someMethod = function(){
    this.a.someMethod.call(this, arg1, arg2...);
}

to be a bit more clear, the following is equivalent
C.someMethod = function(){
    var someMethodOnA = this.a.someMethod;
    someMethodOnA.call(this, arg1, arg2...);
}

In javascript, functions are object, so you can assign them to variables.
the call invocation here is setting the scope of someMethodOnA to this, which is the instance of C.

A:
...
  Can someone give me an example using the above code to demonstrate
  composition and aggregation?

At first glance the provided example does not seem to be the best
choice in order to demonstrate composition in JavaScript. The prototype
property of the Stock constructor function still remains the ideal
place for both methods total and list for both do access any stock
object's own properties.
What can be done is decoupling the implementations of these methods
from the constructors prototype and providing them back exactly there -
yet in an additional form of code reuse - Mixins ...
example:
var Iterable_listAllKeys = (function () {

    var
        Mixin,

        object_keys = Object.keys,

        listAllKeys = function () {
            return object_keys(this).join(", ");
        }
    ;

    Mixin = function () {
        this.list = listAllKeys;
    };

    return Mixin;

}());

var Iterable_computeTotal = (function (global) {

  var
      Mixin,

      currencyFlag,

      object_keys = global.Object.keys,
      parse_float = global.parseFloat,

      aggregateNumberValue = function (collector, key) {
          collector.value = (
              collector.value
              + parse_float(collector.target[key], 10)
          );
          return collector;
      },
      computeTotal = function () {
          return [

              currencyFlag,
              object_keys(this)
                  .reduce(aggregateNumberValue, {value: 0, target: this})
                  .value
                  .toFixed(2)

          ].join(" ");
      }
    ;

    Mixin = function (config) {
        currencyFlag = (config && config.currencyFlag) || "";

        this.total = computeTotal;
    };

    return Mixin;

}(this));

var Stock = (function () {

  var
      Stock,

      object_keys = Object.keys,

      createKeyValueForTarget = function (collector, key) {
          collector.target[key] = collector.config[key];
          return collector;
      },
      createStock = function (config) { // Factory
          return (new Stock(config));
      },
      isStock = function (type) {
          return (type instanceof Stock);
      }
  ;

  Stock = function (config) { // Constructor
      var stock = this;
      object_keys(config).reduce(createKeyValueForTarget, {

          config: config,
          target: stock
      });
      return stock;
  };

  /**
   *  composition:
   *  - apply both mixins to the constructor's prototype
   *  - by delegating them explicitly via [call].
   */
  Iterable_listAllKeys.call(Stock.prototype);
  Iterable_computeTotal.call(Stock.prototype, {currencyFlag: "$"});

  /**
   *  [[Stock]] factory module
   */
  return {
      isStock : isStock,
      create  : createStock
  };

}());

var stock = Stock.create({MSFT: 25.96, YHOO: 16.13, AMZN: 173.10});

/**
 *  both methods are available due to JavaScript's
 *  - prototypal delegation automatism that covers inheritance.
 */
console.log(stock.list());
console.log(stock.total());

console.log(stock);
console.dir(stock);

There is a lot of information about composition vs inheritance
  online, but I haven't found decent examples with JavaScript.
  ...
I did not find a lot of information about composition in JavaScript
  online, only in other languages.
  ...

Maybe the search query was not specific enough but even in 2012
searching for "JavaScript Mixin composition" should have led into
a not that bad direction.

...
  If composition is favored for a lot of situations in OOP, how
  come most people using JavaScript seem to only use prototypes
  and inheritance?

Because most of them use, what they got tought and/or what they
are familar with. Maybe there should be more knowledge spread
about JavaScript as delegation based language too and what can
be achieved with it.
appendix:
This are related threads, recently updated and hopefully helping ...

*

*stackoverflow.com :: How to use mixins properly in Javascript

*stackoverflow.com :: Traits in javascript

*stackoverflow.com :: Javascript Distinguish between Composition vs. Inheritance

A: I think I can show you how to rewrite your code in "object composition" fashion by using plain JavaScript (ES5). I use factory functions instead of constructor functions for creating an object instance, so no new keyword needed. That way, I can favour object augmentation (composition) over classical/pseudo-classical/prototypal inheritance, so no Object.create function is called.
The resulting object is a nice flat-composed object:
/*
 * Factory function for creating "abstract stock" object.
 */
var AbstractStock = function (options) {

  /**
   * Private properties :)
   * @see http://javascript.crockford.com/private.html
   */
  var companyList = [],
      priceTotal = 0;

  for (var companyName in options) {

    if (options.hasOwnProperty(companyName)) {
      companyList.push(companyName);
      priceTotal = priceTotal + options[companyName];
    }
  }

  return {
    /**
     * Privileged methods; methods that use private properties by using closure. ;)
     * @see http://javascript.crockford.com/private.html
     */
    getCompanyList: function () {
      return companyList;
    },
    getPriceTotal: function () {
      return priceTotal;
    },
    /*
     * Abstract methods
     */
    list: function () {
      throw new Error('list() method not implemented.');
    },
    total: function () {
      throw new Error('total() method not implemented.');
    }
  };
};

/*
 * Factory function for creating "stock" object.
 * Here, since the stock object is composed from abstract stock
 * object, you can make use of properties/methods exposed by the
 * abstract stock object.
 */
var Stock = compose(AbstractStock, function (options) {

  return {
    /*
     * More concrete methods
     */
    list: function () {
      console.log(this.getCompanyList().toString());
    },
    total: function () {
      console.log('$' + this.getPriceTotal());
    }
  };
});

// Create an instance of stock object. No `new`! (!)
var portofolio = Stock({MSFT: 25.96, YHOO: 16.13, AMZN: 173.10});
portofolio.list(); // MSFT,YHOO,AMZN
portofolio.total(); // $215.19

/*
 * No deep level of prototypal (or whatsoever) inheritance hierarchy;
 * just a flat object inherited directly from the `Object` prototype.
 * "What could be more object-oriented than that?" –Douglas Crockford
 */
console.log(portofolio);

/*
 * Here is the magic potion:
 * Create a composed factory function for creating a composed object.
 * Factory that creates more abstract object should come first.
 */
function compose(factory0, factoryN) {
  var factories = arguments;

  /*
   * Note that the `options` passed earlier to the composed factory
   * will be passed to each factory when creating object.
   */
  return function (options) {

    // Collect objects after creating them from each factory.
    var objects = [].map.call(factories, function(factory) {
      return factory(options);
    });

    // ...and then, compose the objects.
    return Object.assign.apply(this, objects);
  };
};

Fiddle here.


text:
Q: "No current user": Isn't it even possible to make unauth calls to AWS AppSync through Amplify with authentication type AMAZON_COGNITO_USER_POOLS? I have an AWS AppSync schema with the default authorization mode set to Amazon Cognito User Pool. I make calls to this AppSync endpoint from a web app using AWS Amplify GraphQL Client and, coherently, its configuration points Cognito User Pools as authentication type, too:
aws_appsync_authenticationType: 'AMAZON_COGNITO_USER_POOLS'

It works as expected when the user is authenticated; however (although the involving Cognito Identity Pool has proper Auth and Unath roles set already), when the website runs some Amplify fetch command like for a unauthenticated(guest) user:
const item = await API.graphql(graphqlOperation(getItem, { id: 'my-id' }))

Ends up with throwing an error:
"No current user"

Well, I expected it to perform if I allow unauthenticated users, but it simply fails. Seeking for a way out, I found some discussions like:

*

*a GitHub issue comment here,

*another Github issue,

*or an SO question here.

And, all of the above suggest revisiting the Amplify configs so that the AppSync authentication type is converted from AMAZON_COGNITO_USER_POOLS to AWS_IAM or API_KEY. However, for some detailed reason 1:

*

*I want to stick with AMAZON_COGNITO_USER_POOLS authentication type,

*And still be able to fetch some AppSync resources as a guest user unless they are restricted with
@aws_auth decorators or such.

Is it possible in any way?

1 I have more granular controls depending on the user's group (admin, normal etc.) with decorators such as @aws_auth(cognito_groups: ["default-user-group"]) on the AppSync schema. So, I need Cognito User Pools for that usage.

A: So, I just went through a similar issue and managed to get it sorted. I hope this might help you sort this out. The SO question you mentioned in your question is almost the right way to do it. However, there are one "little" tiny details that are not documented and took me a while to find out.
Apart from having to enable both authenticated and unauthenticated access by running amplify update auth (you can see how in the SO linked above) there are other tweaks you need to do.
First, in your model you need to adjust your rules to be something like:
  @auth(
    rules: [
      # allow owners ability to update and delete their these messages (user pools)
      { allow: owner },
      # allow all authenticated users to access this data
      { allow: private, provider: userPools },
      # allow all guest users (not authenticated) to access this data
      { allow: public, provider: iam }
    ]
  )

Once you set up this model to allow user pools to access all the data they "own",  you can also let any "guest" user to access the data too.
In the frontend, let's get your code as an example, you need to use a bit of a different approach:
Instead of
const item = await API.graphql(graphqlOperation(getItem, { id: 'my-id' }))

try something like
// Check if the user is logged in or not
let isLoggedIn = await isLoggedIn();

const item = (await API.graphql({
      query: getItem,
      variables: { id: 'my-id' },
      authMode: isLoggedIn ? GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS : GRAPHQL_AUTH_MODE.AWS_IAM,
  }));

by the way the "isLoggedIn" function look like this
async function isLoggedIn() {
  // Another way to get if its a guest or not
  //return await Auth.Credentials.getCredSource() === "guest"
  try {
      await Auth.currentAuthenticatedUser();
      return true;
  } catch {
      return false;
  }
}

So... this line is what it does the trick, which is not really well documented.
authMode: isLoggedIn ? GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS : GRAPHQL_AUTH_MODE.AWS_IAM
you need to path the different methods according to the state of the user (logged in or guest), not just the AWS_IAM one.
This will only get you as far as READING the data, in order to make sure guests can do Create/Update/Delete, and separate the data ownership from each other and logged users, that's a completely different story that you will need to start digging up on resolvers to get it sorted. But the good news is, there is a way :)


text:
Q: Create symbolic link for directory, symbolic link end up inside target I know it's been asked many times, but I followed the instruction  and cannot create the link. The symlink (gradle-current) always ends up inside the target (gradle-2.7)
cd ~
ln --symbolic -t /home/tung/gradle-2.7/  /home/tung/gradle-current/

or other version:
cd ~
ln --symbolic -t gradle-2.7  gradle-current

still no luck, any tip? Thanks

A: -t specifies a directory in which to create a symlink.  It doesn't specify a directory which is to be targeted by the symlink.
What you want is ln -s gradle-2.7 gradle-current.  This creates a symlink called "gradle-current" which points to "gradle-2.7".
In actual fact it doesn't matter whether gradle-2.7 is a directory or a file—the command is the same.
Actually, it doesn't matter if gradle-2.7 exists or not, the command is still the same for creating the symlink.  (The symlink won't work if the target doesn't exist, but it can still be created.  If the target is later created, the symlink will then operate without any additional work.)


text:
Q: Add Select columns dynamically in R with ends_with in Shiny App Using stackoverflow, I created a shiny app which uploads a csv file and then displays a datatable.
After selecting columns dynamically, where some columns have "_down" end.
I require help in shortening the dataframe (as in the code below) and also remove duplicates by ID column (if present).
    # install.packages("shiny")
    # install.packages("DT")
    # install.packages("shinycssloaders")
    library(DT)
    library(shiny)
    library(shinycssloaders)

UI code
    ##Creating the UI as a fluidPage,
    ##fluidPage allows scaling components of the browser in realtime to fill all available broswer width
    ##This is standard
    ui <- fluidPage(

      # Title of app
      titlePanel("Upload file to table"),

        # Main panel for displaying outputs
        mainPanel(

          #fileInput with acceptance of text/csv and more
          fileInput('file', 'Choose file to upload',
                    accept = c(
                      'text/csv',
                      'text/comma-separated-values',
                      'text/tab-separated-values',
                      'text/plain',
                      '.csv',
                      '.tsv',
                      '.html'
                    )),

          # Output: datatable
          DT::dataTableOutput("data_as_table")%>%withSpinner(),

          #Download button
          downloadButton("downloadData", "Download")

        )
    )

Server Code
Creating server
    server <- function(input, output) {

      #Data is a reactive element meaning it will update when the reactive input inside it change
      #Data will update when input$file changes
      #input$file is the uploaded file (se fileInput in ui)
      data <-reactive({

        #Store input$file as inFile
        inFile <- input$file

        #if its empty return nothing
        if (is.null(inFile))
          return(NULL)

        #read in the file as a csv, with headers, comma seperated
        dd = read.csv(inFile$datapath, header = T,
                 sep = ",")
        dd  = as.data.frame(dd)

        #Shortening dataframe
        #dd= dd[apply(dd[, endsWith(colnames(dd), "_down")], 1, function(x) any(x == "TRUE")), ]

        #Remove duplicates by ID column, and show unique
        #xxx
        return(dd)
      })

    #Make the output data_as_table a datatable containing the reactive element data
     output$data_as_table<-DT::renderDataTable({
       data()
     })

     # Downloadable csv of reactive data() object
     output$downloadData <- downloadHandler(
       filename = function() {
         paste("Download", Sys.date(), ".csv", sep = "")
       },
       content = function(file) {
         write.csv(data(), file, row.names = FALSE)
       }
     )
    }

    #Launch shiny app
    shinyApp(ui = ui, server = server)

A: You can remove duplicates using dplyr::distinct. It'll only keep the first instance of the ID and remove others. In your case add this before return(dd) in data reactive -
if("ID" %in% names(dd)) {
    dd <- dplyr::distinct(dd, ID, .keep_all = T)
}


text:
Q: Laravel Query builder - query not working but works in SQL console I've become extremely confused I'm trying to run a query through laravels query builder which should work but it's throwing odd errors.
I'm trying to count records from the tips table where the status is 'Won' between a daterange and then join the users table on the user_id to retrieve the users username.
This is my query builder
    $topfiveTipsters = DB::table('tips')
      ->select(DB::raw('count(status) as wincount, users.name'))
      ->join('users', 'users.id', '=', 'tips.user_id')
      ->whereBetween('tips.created_at',[$start,$end])
      ->where('status','Won')
      ->groupBy('users.id')
      ->orderBy('wincount', 'desc')
      ->get();

However it's throwing the error

QLSTATE[42000]: Syntax error or access violation: 1055 'digthetip.users.name' isn't in GROUP BY (SQL: select count(status) as wincount, users.name from tips inner join users on users.id = tips.user_id where tips.created_at between 2016-11-01 00:00:00 and 2016-11-02 10:39:02 and status = Won group by users.id order by wincount desc)

but if I run the exact query the error has outputted into the SQL console within PHPMyAdmin the query runs fine and returns the results I require.
Am I missing something? I'm relatively new to Laravel and I'm massively confused how it's still throwing an error.

A: Ok so it turns out you can turn of SQL strict mode in /app/database.php which will prevent the error from happening.
'strict' => false,


text:
Q: jQuery wont work? animate function Hello stackoverflow
Im running through some tutorials to jQuery, cause i wanna start a 2d chat.
I have a code that should make some images at 50% opacity, and 100% when a mouser hover the images, but it wont work? The images is 50%, but wont change to 100%.
My code:
$(function(){

    $('#container img').animate({
        "opacity" : .50
    });

    $('#container img').hover(function() {
        $(this).animate({  "opactiy": 1  });
        console.log("Den er nu 100% klar");
    });

});

A: You've got a typo in your hover statement:
 $(this).animate({  "opactiy": 1  });

should be:
 $(this).animate({  "opacity": 1  });

A: Just change opactiy to opacity in your second .animate():
$(function(){

    $('#container img').animate({
        "opacity" : .50
    });

    $('#container img').hover(function() {
        $(this).animate({  "opacity": 1  }); // <-- Right here
        console.log("Den er nu 100% klar");
    });

});

jsFiddle

A: $(function(){

    $('#container img').animate({
        opacity : '1'
    });

    $('#container img').hover(function() {
        $(this).animate({  opacity:'0.5'  });

    },function(){
            $(this).animate({ opacity:'1'  });

    });

});

JSFIDDLE


text:
Q: Is there a way to get the type of a variable in a macro? I have an procedural attribute macro which given a function operates on each binary expression e.g. let a = b + c; and returns another expression depending on it. With the + operation depending on the types, it needs to know the types of a, b and c.
Is there a way to get the inferred types of variables at compile time?
(like rust-analyser might display inferred types, can I get these inside a macro?)
Quick example - Playground
To illustrate my approach a bit more succinctly in a Rust playground we can use a declarative macro which calls a function on a given variable, the specifics of this function being based on the type of the given variable.
The closest I can get to my desired functionality in a Rust playground:
macro_rules! SomeMacro {
    ($x:expr) => {{
        $x.some_function(3.)
    }};
}
trait SomeTrait {
    fn some_function(&self,x:f32) -> f32;
}
impl SomeTrait for u32 {
    fn some_function(&self,x:f32) -> f32 {
        x * 3.
    }
}

fn main() {
    let a = 3u32;
    let b = SomeMacro!(a);
    assert_eq!(b,9.);
}

How would I make something work like:
fn some_function<u32>(x:f32) -> f32 {
    3. * x
}
fn some_function<u32,i8,f32>(x:f32) -> f32 {
    3. * x
}
fn main() {
    let a = 3u32;
    let b = <type_of<a>()>::some_function(3.);
    assert_eq!(b,9.);
    let c = 5i8;
    let d = <type_of<a>(),type_of<b>(),type_of<c>()>::some_function(2.);
    assert_eq!(c,6.);
}

Comprehensive example - .zip
lib.rs
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro_attribute]
pub fn my_attribute_macro(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let ast = syn::parse_macro_input!(item as syn::Item);
    // eprintln!("{:#?}",ast);

    // Checks item is function.
    let mut function = match ast {
        syn::Item::Fn(func) => func,
        _ => panic!("Only `fn` items are supported."),
    };
    let block = &mut function.block;

    // Updates statements
    let statements = block.stmts
        .iter()
        .filter_map(|statement| update_statements(statement))
        .collect::<Vec<_>>();
    block.stmts = statements;

    let new = quote::quote! { #function };
    TokenStream::from(new)
}
fn update_statements(stmt: &syn::Stmt) -> Option<syn::Stmt> {
    let local = match stmt {
        syn::Stmt::Local(local) => local,
        _ => return Some(stmt.clone())
    };
    let init = &local.init;
    let bin_expr = match *init.as_ref().unwrap().1 {
        syn::Expr::Binary(ref bin) => bin,
        _ => return Some(stmt.clone())
    };

    eprintln!("looking at: {:#?}",stmt);
    //
    None
}

main.rs
use macro_test::*;
// Goals:
// - Map from `x` being equal to `a+b` to `x` being equal to `a*b` based off `x` being `f32`.
// - Map from `y` being equal to `c+d` to `y` being equal to `c/d` based off `y` being `u32`.
#[my_attribute_macro]
fn my_function(a: f32, b: f32, c: u32, d: u32) {
    let x = a + b;
    let y = c + d;
}

fn main() {
}

With one of the prints looking like (from cargo expand --bin macro-test):
looking at: Local(
    Local {
        attrs: [],
        let_token: Let,
        pat: Ident(
            PatIdent {
                attrs: [],
                by_ref: None,
                mutability: None,
                ident: Ident {
                    ident: "y",
                    span: #0 bytes(316..317),
                },
                subpat: None,
            },
        ),
        init: Some(
            (
                Eq,
                Binary(
                    ExprBinary {
                        attrs: [],
                        left: Path(
                            ExprPath {
                                attrs: [],
                                qself: None,
                                path: Path {
                                    leading_colon: None,
                                    segments: [
                                        PathSegment {
                                            ident: Ident {
                                                ident: "c",
                                                span: #0 bytes(320..321),
                                            },
                                            arguments: None,
                                        },
                                    ],
                                },
                            },
                        ),
                        op: Add(
                            Add,
                        ),
                        right: Path(
                            ExprPath {
                                attrs: [],
                                qself: None,
                                path: Path {
                                    leading_colon: None,
                                    segments: [
                                        PathSegment {
                                            ident: Ident {
                                                ident: "d",
                                                span: #0 bytes(324..325),
                                            },
                                            arguments: None,
                                        },
                                    ],
                                },
                            },
                        ),
                    },
                ),
            ),
        ),
        semi_token: Semi,
    },
)

A: The compiler doesn't decide the types until the macros have been processed. In many cases, a macro can change the inferred types. This is why it's possible to write things like:
let mut xs = vec![];
xs.push(1);

Type inference can go back and assign the right type to xs. This wouldn't be possible if vec! had to know the type prior to expansion. You will need to approach this problem another way. See @PossiblyAShrub's answer for one approach.
As The Rust Programming Language:Macros notes (emphasis added):

Also, macros are expanded before the compiler interprets the meaning of the code, so a macro can, for example, implement a trait on a given type.

You may want to explore the Native Differential Programming Support for Rust discussion from the forums, and particularly the follow-up threads linked.

A: Addition
OP has updated their post clarifying their issue, this addition is in response to that.
It appears that you may want to implement the new type pattern. In your comment you mention that you want to change the behavior of standard operators (+, -, *, /, ...) on functions decorated with a specific procedural macro.
The newtype pattern looks like this:
struct Differentiable(f32);

Note: we could even use generics here such that our new type can be over f32, u32, u8 ...

We can now implement our desired operators on top of our new type.
impl Add for Differentiable {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self(self.0 * other.0)
    }
}

This gives us the behavior:
fn main() {
  let x = Differentiable(5.0);
  let y = Differentiable(2.0);
  assert_eq!(x + y, 10);
}

Furthermore we could implement Into and From on the type to make it's use more ergonomic. We can also implement the other operators via implementing the traits in std::ops.
Now, you mentioned wanting to implement this as a procedural macro on a function. I would strongly suggest otherwise. I would argue that such a feature would:

*

*Increase likelihood for confusion

*Increase the complexity of your library

*Directly violate standard rust idoms

*Impact IDE usage

*Increase compile times

See:

*

*@GManNickG's comment

*https://rust-analyzer.github.io/blog/2021/11/21/ides-and-macros.html

*https://matklad.github.io/2021/09/04/fast-rust-builds.html
Personally I do not see the value in providing such a macro, nor how it could even be implemented in a way which "feels" right. Nevertheless it is possible:
Simply convert from this ast:
fn my_function(a: f32, b: f32, c: u32, d: u32) {
  let x = a + b;
  let y = c + d;
}

to:
fn my_function(a: f32, b: f32, c: u32, d: u32) {
  fn inner(
    a: Differentiable,
    b: Differentiable,
    c: Differentiable,
    d: Differentiable,
  ) {
    let x = a + b;
    let y = c + d;
  }

  inner(
    Differentiable(a),
    Differentiable(b),
    Differentiable(c),
    Differentiable(d),
  )
}

Further reading:

*

*https://doc.rust-lang.org/stable/book/ch19-04-advanced-types.html#using-the-newtype-pattern-for-type-safety-and-abstraction

*https://doc.rust-lang.org/stable/book/ch19-03-advanced-traits.html#default-generic-type-parameters-and-operator-overloading

Previous response
I am not sure what use knowing the type of an expression inside of a macro would be for you. Rust's type inference system should be powerful enough to handle most cases of type resolution.
For example, I would implement the above snippet using generics and trait bounds:
use std::ops::Add;

fn add<A: Into<B>, B: Add>(a: A, b: B) -> <B as Add>::Output {
    a.into() + b
}

fn main() {
    let a: u8 = 4;
    let b: f32 = 3.5;
    assert_eq!(add(a, b), 7.5);
}

Rust will automatically find the right values for A and B. In the case that it cannot, due to our trait restrictions, rustc will output  helpful error message:
fn main() {
    let a = "Hello, world!";
    let b = 56;
    add(a, b);
}

Results in:
error[E0277]: the trait bound `{integer}: From<&str>` is not satisfied
  --> src/main.rs:10:12
   |
10 |     add(a, b);
   |     ---    ^ the trait `From<&str>` is not implemented for `{integer}`
   |     |
   |     required by a bound introduced by this call
   |
   = help: the following implementations were found:
             <Arc<B> as From<Cow<'a, B>>>
             <Arc<CStr> as From<&CStr>>
             <Arc<CStr> as From<CString>>
             <Arc<OsStr> as From<&OsStr>>
           and 329 others
   = note: required because of the requirements on the impl of `Into<{integer}>` for `&str`
note: required by a bound in `add`
  --> src/main.rs:3:11
   |
3  | fn add<A: Into<B>, B: Add>(a: A, b: B) -> <B as Add>::Output {
   |           ^^^^^^^ required by this bound in `add`

For more information about this error, try `rustc --explain E0277`.

Here rust could not resolve the type of a to fit our restrictions in the add function.
Now this works through macros, with no extra work necessary:
macro_rules! some_macro {
  ($x:expr) => (add($x, 3.0))
}

fn main() {
    let x = 42u32;
    let y = some_macro!(x);
    assert_eq!(y, 45.0);
}

Further reading:

*

*https://doc.rust-lang.org/stable/book/ch03-02-data-types.html

*https://doc.rust-lang.org/stable/book/ch10-00-generics.html

*https://doc.rust-lang.org/stable/book/ch10-02-traits.html

*https://doc.rust-lang.org/stable/book/ch19-03-advanced-traits.html


text:
Q: Validating form and sending a confirmation email on submission I am creating an admin page, where the admin person can create users accounts for people. The idea is, that once the form is completed, when clicking 'Submit' an email must be sent to the user (containing the ID and name of account selected). In the same action, the form must also first be validated and if there are any errors with the validation the data should not be submitted to the database. None of this is happening though and I cannot figure out why.

*

*The email is not being sent,

*the data is inserted in the database even if there are errors and upon loading the page,

*errors are displayed for all form fields even though the submit button have not been clicked.

Any help, advice or links to possible sources/tutorials would be greatly appreciated.
Below is my code: (Note that I am only working in PHP, HTML and using a MYSQL database)

    <title>
        User Registration
    </title>
    <?PHP

    include_once 'includes\functions.php';
    connect();

    error_reporting(E_ERROR | E_PARSE);

//Assign variables
    $accounttype=mysql_real_escape_string($_POST['accounttype']);
    $sname = mysql_real_escape_string($_POST['sname']);
    $fname = mysql_real_escape_string($_POST['fname']);
    $email = mysql_real_escape_string($_POST['email']);
    $address = mysql_real_escape_string($_POST['address']);
    $contact_flag = mysql_real_escape_string($_POST['contact_flag']);

//Validating form(part1)

    $error='';

//Connect to database
        $SQL=
            "INSERT INTO student
                        (
                            sname,fname,email, address, contact_flag
                        )
            VALUES
                        (

                        '$sname', '$fname', '$email', '$address', '$contact_flag'
                        )
            ";
        if (!mysql_query($SQL))
            {
                print'Error: '.mysql_error();
            }

        mysql_close($db_handle);
//Validate form(part 2)
    if (isset($_POST['sname'], $_POST['fname'],$_POST['email'],$_POST['address']));
        {
            $errors=array();

                $accounttype= mysql_real_escape_string($_POST['accounttype']);
                $sname = mysql_real_escape_string($_POST['sname']);
                $fname = mysql_real_escape_string($_POST['fname']);
                $email = mysql_real_escape_string($_POST['email']);
                $address = mysql_real_escape_string($_POST['address']);
                $contact_flag = mysql_real_escape_string($_POST['contact_flag']);

// form validation
                        if(strlen(mysql_real_escape_string($sname))<1)
                        {
                            $errors[]='Your surname is too short!';
                        }

                        if(strlen(mysql_real_escape_string($fname))<1)
                        {
                            $errors[]='Please insert you full first name';
                        }

                        if(filter_var($email, FILTER_VALIDATE_EMAIL)===FALSE)
                        {
                            $errors[]='Please insert your valid email address';
                        }
                        if(strlen(mysql_real_escape_string($address))<8)
                        {
                            $errors[]='Please insert your postal address';
                        }

                            echo'
';
                            print_r($errors);
                            echo'
';
        }

//confirmation email

    // Subject of confirmation email.
        $conf_subject = 'Registration confirmed';

    // Who should the confirmation email be from?
        $conf_sender = 'PHP Project <my@email.com>';

    $msg = $_POST['fname'] . ",\n\nThank you for registering. \n\n You registered for account:".$accounttype."\n\n Your account number:".mysql_insert_id;

        mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );

   ?>

    <form name ="form0" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">

        Select the course you wish to register for:

                <select   name="accounttype">
                    <?PHP query() ?>

                </select>
                    <?PHP close() ?>

    </form>

    <form name ="form1" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">

        <Input type ="" Value = "Surname" Name = "sname">

        <Input type ="" Value = "First name" Name = "fname">

        Email: <Input type ="" Value = "" Name = "email">

        Address:

        <textarea rows="4" cols="20" Name="address">Please provide your postal address here </textarea>

        Tick to receive confinmation email: <Input type ="checkbox" Value = "1" Name = "contact_flag">

        <Input type = "Submit" Value="Submit">

    </form>

A:  <?PHP
if(isset($_POST['submit']))
{
    include_once 'includes\functions.php';
    connect();

// your rest of the code

        mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );

}

   ?>

and keep this code out of the  tag but before it

A: and if you want to stick to PHP only then one error i can see is
that you have kept the **validation code below the `INSERT`**

query which means that the insert query will be executed first which will store the data in the database first and then it will go for the validation...so keep your validation code above the INSERT statement..
 and second thing use exit() method  after vaidating every field if it gives you error...it will stop executing rest of the php code if any field gives the error during validation....and so it will also prevent the data from storing into the database if it finds exit method whenever an error is found eg
 if(strlen(mysql_real_escape_string($sname))<1)
                        {
                            $errors[]='Your surname is too short!';
                           echo '//whatever you want to echo';
                           exit();
                        }

                        if(strlen(mysql_real_escape_string($fname))<1)
                        {

                            $errors[]='Please insert you full first name';
                         echo '//whatever you want to echo';
                         exit();
                        }

A: At first, your query gets executed before you validate your form.
Move your SQL after your
echo'
';
print_r($errors);
echo'
';

and surround it with
if(!$errors){}

This will prevent your query from being executed if there are any errors.
(You can also delete your first assignement of your variables)
Concerning your email problem, test your connection with a simple message
mail('your@email.com', 'subject', 'message');

If you get any error, probably your mailserver isn't set up right


text:
Q: distinguish whether page was reloaded or not in Django views or in template Django question
I would like to ask whether it is  possible or not  to distinguish  in view or in template if page was reloaded or page was reached by url from the other page? If shorten it out, need to know if it is any marker that would indicate that page got reloaded by F5 or whatever?
Perhaps it is  probably possible to figure out by analyzing request.
Only 1 idea that comes to my mind is following:
request.get_full_path()# – specifies full address of the current page

request.META.get('HTTP_REFERER')# – specifies full address of previous page

So that theoretically if former == last – page is reloaded, but it doesn't work this way.
If you know any solution or hint -please communicate it.
Thank you and have a nice day!

A: you can do one thing:
use one hidden element in your template like this :
 <input type="hidden" id="anyId" name="anyName" value="">

then call a fn to assign value to this element when page reloads
<body onbeforeunload="assignValue()>
<!--put your stuff-->
<script>
function assignValue(){
document.getElementById("anyId").value="reloaded";
}
</body>

because of onbeforeunload on page load assignValue() fn will be called.
then you can check this value of input element in your backend if value is not empty i.e. "" means page is loaded


text:
Q: jQuery .animate queue does not work Dreamweaver gives an error. What's the right syntax?
After the first

.animate({left: '-=980'}, 550,

?
The real deal is: That I can only use one ".animate({left: '-=980'}, 550," in this code... There comes an error if I want to add two (or more) .animate's in the animation queue.
BTW: The "clicknr" variable and the 'disabled' CSS class - are just flags for some internal process.
$('#fwdShowroom').click(function() {
    $button = $(this);
    if ( clicknr != 1 )  {
        if( !$button.hasClass( 'disabled' ) ) {
            $button.addClass( 'disabled' );
            clicknr -= 1,
              $('#showroom ul')
                .animate({left: '-=985'}, 550,
                     Dreamweaver says: Error on this line        .animate({left: '+=5'},200,
                function() { $button.removeClass('disabled') });
        }
    }
});

The needed effect is: That the "#showroom ul" DIV smoothly moves forward and then goes smoothly some pixels back to create a nice physical motion.

A: You forgot the closing parentheses ) in the first animate call:
.animate({left: '-=985'},550)


text:
Q: mod_rewrite all non-files queries in public folder to ../index.php I have the following folder logic:
.htaccess
index.php
composer.json
(etc. with all processing files)
public/
    .htaccess
    design/
    files/
    (etc. with all static files)

With the following in both .htaccess:
(.htaccess:)
RewriteEngine on
RewriteRule   ^(.*)$ public/$1    [L]
(public/.htaccess)
RewriteEngine on
RewriteCond $1 !^(index\.php|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

The first .htaccess is useful when in development on MAMP and unrequested in production as most website directly serve the public folder.
The reason for this request as opposed to having a public/index.php file with include '../index.php'; is that, for example, Slim uses $_SERVER['PHP_SELF'] which would break routing by forcing /public into the url. One dirty way to solve this involves changing a file in the vendor/slim/slim folder, which should be a relatively big forget-it.

A: (While writing my question, I ended up discover a cozy solution which I would like to share)
(.htaccess)
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !index.php
RewriteRule   ^(.*)$ public/$1    [L]
(public/.htaccess)
RewriteEngine on
RewriteCond $1 !^(index\.php|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ ../index.php/$1 [L,QSA]

When in development,

*

*The first .htaccess redirects all calls but index.php to public/

*The second .htaccess is redirects all non files back outside public onto ../index.php,

*The first .htaccess does not do anything.

When in production, only step two and three are done.
This way, dynamic files are strictly separated from static files.


text:
Q: Spring Error: No property prod found for type Product I am new to Spring and facing some problem.
My entity has a field:
    package com.ecommercesystem.ecommerce.entities;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.sql.Blob;

@Entity
public class Product {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer ID_product;

  @NotNull
  private String prod_name;

  @NotNull
  private String prod_desc;

  @NotNull
  private float price;

  @NotNull
  private String prod_brand;

  @NotNull
  private Blob prod_image;
  private int prod_rating;

  @ManyToOne
  private Category category;

  protected Product(){}

  public Product(Integer ID_product, @NotNull String prod_name, @NotNull
    String prod_desc, @NotNull float price, @NotNull String prod_brand,
    @NotNull Blob prod_image, int prod_rating, Category category) {
    this.ID_product = ID_product;
    this.prod_name = prod_name;
    this.prod_desc = prod_desc;
    this.price = price;
    this.prod_brand = prod_brand;
    this.prod_image = prod_image;
    this.prod_rating = prod_rating;
    this.category = category;
  }

  public Integer getID_product() {
    return ID_product;
  }

  public void setID_product(Integer ID_product) {
    this.ID_product = ID_product;
  }

  public String getProd_name() {
    return prod_name;
  }

  public void setProd_name(String prod_name) {
    this.prod_name = prod_name;
  }

  public String getProd_desc() {
    return prod_desc;
  }

  public void setProd_desc(String prod_desc) {
    this.prod_desc = prod_desc;
  }

  public float getPrice() {
    return price;
  }

  public void setPrice(float price) {
    this.price = price;
  }

  public String getProd_brand() {
    return prod_brand;
  }

  public void setProd_brand(String prod_brand) {
    this.prod_brand = prod_brand;
  }

  public Blob getProd_image() {
    return prod_image;
  }

  public void setProd_image(Blob prod_image) {
    this.prod_image = prod_image;
  }

  public int getProd_rating() {
    return prod_rating;
  }

  public void setProd_rating(int prod_rating) {
    this.prod_rating = prod_rating;
  }

  public Category getCategory() {
    return category;
  }

  public void setCategory(Category category) {
    this.category = category;
  }
}

 My Product Repository is something like this:
 package com.ecommercesystem.ecommerce.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ecommercesystem.ecommerce.entities.Product;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

// This will be AUTO IMPLEMENTED by Spring into a Bean called
productRepository
// CRUD refers Create, Read, Update, Delete

@Repository
public interface ProductRepository extends JpaRepository<Product, Integer> {
  Optional<Product> findByProd_name(String prod_name);
//  Optional<Product> findByProd_brand (String prod_brand);
}

 and my Product Controller is something like this:
 package com.ecommercesystem.ecommerce.controllers;
import com.ecommercesystem.ecommerce.entities.Category;
import com.ecommercesystem.ecommerce.entities.Product;
import com.ecommercesystem.ecommerce.repositories.ProductRepository;
//import com.ecommercesystem.ecommerce.services.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Optional;

@Controller
public class ProductController {

  @Autowired
  ProductRepository productRepository;

  @GetMapping(path = "/")
  public String front() {
    return "index";
  }

  @GetMapping(path = "/search_results")
  public String search(@RequestParam(value = "search", required = false)
        String search, Model model){
    Optional<Product> productName =
         productRepository.findByProd_name(search);
    if (productName.isPresent()){
      if (search.equals(productName.get().getProd_name())){
        model.addAttribute("ID_product", productName.get().getID_product());
        model.addAttribute("price", productName.get().getPrice());
        model.addAttribute("prodName", productName.get().getProd_name());
        model.addAttribute("category_name",
          productName.get().getCategory().getCategory_name());
//        model.addAttribute("prodDesc", productName.get().getProd_desc());
//        model.addAttribute("prodImage", productName.get().getProd_image());
//        model.addAttribute("prodBrand", productName.get().getProd_brand());
      }
    }
    return "search_results";
  }
}

 But when i run the program i got this Error Message:
 Error Log:

[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 10.277 s <<< FAILURE! - in com.ecommercesystem.ecommerce.EcommerceApplicationTests
[ERROR] contextLoads(com.ecommercesystem.ecommerce.EcommerceApplicationTests)  Time elapsed: 0.017 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'productRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.ecommercesystem.ecommerce.repositories.ProductRepository.findByProd_name(java.lang.String)! No property prod found for type Product!
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.ecommercesystem.ecommerce.repositories.ProductRepository.findByProd_name(java.lang.String)! No property prod found for type Product!
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.ecommercesystem.ecommerce.repositories.ProductRepository.findByProd_name(java.lang.String)! No property prod found for type Product!
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property prod found for type Product!

 Any help is highly appreciated. Thank You!

A: Spring Data uses camelCase convention when searching for method names
  public void setProdName(String prodName) {
     this.prodName = prodName;
  }

  public String getProdName() {
    return prodName;
  }


text:
Q: powermail should update a `pages`-field I want to use powermail (7.4.0) to give special page visitors the option to modify a field in the current pages record.
my setting so far:
plugin.tx_powermail.settings.setup {
    dbEntry {
        1 {
            _enable = TEXT
            _enable.value = 1

            _table = TEXT
            _table.value = pages

            uid = TEXT
            uid.data = TSFE:id

            description = TEXT
            description.field = abnahmestatus
        }
    }
    prefill {
        abnahmestatus = TEXT
        abnahmestatus.data = TSFE:description
    }
}

How can I get powermail to update the record (instead of inserting)?
How can I prefill the input field with the current value from the pages field?

A: Answer 1: update instead of insert:
I missed the line
_ifUnique.uid = update

from the manual example.

Answer 2:
I inserted {abnahemstatus} which was not helpfull as it overwrote the typoscript prefill. so:

*

*no value in prefill_value of the field definition

*the correct definition is abnahmestatus.data = page:description (TSFE is obsolete)


text:
Q: Fail2ban ufw action does not run when monitoring, but works for manual ban I'm using fail2ban 0.9.3 on Ubuntu 16.04. My jail.local looks like this:
[DEFAULT]

banaction = ufw

[apache-post]
enabled = true
filter = apache-post
port = http,https
logpath  = /var/log/apache2/other_vhosts_access.log
maxretry = 20
bantime = 3600

I'm running fail2ban 0.9.3 on ubuntu 16.04.
I have a custom ufw action defined as follows:
[Definition]
actionstart =
actionstop =
actioncheck =
actionban = ufw insert 1 deny from <ip>
actionunban = ufw delete deny from <ip>

(This is different from the one that comes with fail2ban in that is just blocks the IP on all ports).
The action works - if I do fail2ban-client set apache-post banip 10.0.0.1 and then check ufw status, the IP is banned:
To                         Action      From
--                         ------      ----
Anywhere                   DENY        10.0.0.1

But when the server is then restarted and running, there is a problem. fail2ban is correctly monitoring the logs and initiating bans, but the IPs are not being banned in ufw. Here is a log sample:
2018-10-09 14:00:57,679 fail2ban.actions        [31576]: NOTICE  [apache-post] Ban 10.0.5.2
2018-10-09 14:01:02,897 fail2ban.actions        [31576]: NOTICE  [apache-post] 10.0.5.2 already banned
2018-10-09 14:01:07,903 fail2ban.actions        [31576]: NOTICE  [apache-post] 10.0.5.2 already banned
2018-10-09 14:01:12,908 fail2ban.actions        [31576]: NOTICE  [apache-post] 10.0.5.2 already banned
2018-10-09 14:01:17,914 fail2ban.actions        [31576]: NOTICE  [apache-post] 10.0.5.2 already banned

If I check ufw status then the IP has not been banned - so clearly the action hasn't actually been executed, but fail2ban thinks it has.
If I restart the fail2ban server at this point, then it will check the recent logs and successfully ban the IP - i.e., when it performs actions on restart, the ufw action is correctly executed. Similarly if I manually run a banip command then the IP is correctly banned. But the bans from monitoring of logs don't work.
I'm stumped as to why it works manually, but not in normal operation. How do I debug this?
UFW is running:
> sudo ufw status
Status: active

And checking the status of the jail shows that it is active, and it thinks it has banned the IPs:
Status for the jail: apache-post
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     643
|  `- File list:        /var/log/apache2/other_vhosts_access.log
`- Actions
   |- Currently banned: 9
   |- Total banned:     11
   `- Banned IP list:   10.0.5.2 (and more)

A: Have you confirmed that ufw is in fact running?  E.g. on my Ubuntu installations, that requires setting 'enabled=YES' in /etc/ufw/ufw.conf in order to get ufw to start at boot.  On Ubuntu 16.04 it's off by default.
I gather you're saying that you replaced the default /etc/fail2ban/action.d/ufw.conf?  Why?  Does your recipe work with the original version?
What does fail2ban status <JAIL> show you?