text:
Q: Touchpad track speed increases in dual monitor setup I have a Dell E6530 with an Alps touchpad, NVIDIA NVS 5200 with proprietary nvidia-319.32 video driver installed.
I am using xfce4 although I do not know if this makes a difference, as it seems to be a configuration unrelated to the DE/WM.
The touchpad driver in 3.11.0-12-generic works flawlessly on the laptop by itself. nvidia-319 works flawlessly and significantly better than noveau.
However when I plug in an external display and extend to that monitor, my touchpad track speed increases dramatically, and it becomes very hard to make precise mouse movements, especially when moving the cursor relatively long distances, due to the cursor acceleration. It seems to increase the speed proportional to the net increase in total resolution available in the dual monitor setup.  Which would seem that the track speed is based on some sort of display resolution percentage, not number of pixels like I had expected.
Does anyone know if this is indeed how the touchpad configuration works? And if there is a way to prevent this, or do I need to go in and decrease my track speed by about half every time I plug in an external monitor?

A: You're not the only one to experience this and unfortunately there is no fix. Users have reported this behaviour since 2010 and it has been an open bug since 2011.
Having explored the various suggestions in those links, until this bug is fixed, I think the only way is to adjust the speed manually each time


text:
Q: How to remove Tailwind from Docker & Laravel9 with Breeze I was just curious about removing Tailwind from Docker & Laravel (9.38.0) with Breeze installed as follows:
$ curl -s "https://laravel.build/test" | bash
$ cd test/
$ composer require laravel/breeze --dev
$ php artisan breeze:install
$ php artisan migrate
$ composer install
$ npm install

I remove tailwind and alpine from resources/css/App.css and resources/js/App.js and sail up, however they were there as if nothing happened... How are they included?
Additionally, I tested to install without Docker as below. Tailwind and Alpine.js were not included as I expected.
$ composer create-project laravel/laravel test2
$ cd test2/
$ composer require laravel/breeze --dev
$ php artisan breeze:install
$ php artisan migrate
$ composer install
$ npm install

What cause the difference?
Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: tiki-wiki: How to batch import categorized articles from a CSV file Importing categories as a CSV file is OK in tiki-wiki, But how to import categorized articles to the system. Tiki supports media wiki and word press importing, While my data base has another format.

*

*Is there any module for CSV upload/import?

*Is there any flexible migration-like script to import articles?

In case that both of answers are NO, would you please give me a clue to write down the proper code to import articles directly to data base.
I went through understanding database, But I think accessing to database directly should be my last choice!

A: For custom import jobs, you can use Tiki's profiles. The profiles are a YAML-based format. While it is not the primary use for them, it might be the easiest way to perform what you want to do.
Normally, you need to place the profile in a repository to execute it, but there is a developer option to load content from a textarea. You can simply prepare your YAML definition and paste it in there.
Categorizing elements through the database could be harder than it seems as many tables are involved.


text:
Q: In Microsoft Outlook, Is it possible to create a rule to set a specific colour to a meeting invite where I'm in CC? I would like to set  specific colour to all meeting invites in Outlook where I'm in cc. Is it possible ?

A: You need to use conditional formatting and in the "Advanced" tab set the following rules:
Organizer is not empty
Cc contains Gillieaux, Luc
Cc contains luc.gillieaux@company.com
To doesn't contain Gillieaux, Luc
To doesn't contain luc.gillieaux@company.com

In some organisations (and combinations of Outlook and Exchange) I've found I've needed to add two further rules to cover all eventualities:
To doesn't contain Luc Gillieaux
Cc contains Luc Gillieaux


text:
Q: How to exclude a folder on Drupal site so that Drupal does not recognise it its own? I am running a site xyz.org in Drupal.
Now I want to install some other modules such as PHPBB forum and Coppermine gallery. When I install these, and try to access the link xyz.org/gallery, it gives me drupal error.

"Page not found"

What settings I need to change in order to let drupal know that /gallery is not a drupal node?

A: Take a look at your current .htaccess config. If might have the following lines:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Those contain most of the URL rewriting that matters. The first three conditions say that all URLs will be rewritten except for existing files, directories and a request for /favicon.ico
You can add your own favourite conditions there. For example, to avoid rewriting for urls of the form /gallery/.*:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} !^/gallery/.*$
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]


text:
Q: Does readability of code justify nested try-catch blocks for flow control? This code retrieves lines of a log file and tries to find a date in one of delimited fields. Which char is the delimiter can vary and also in what field the date can be found varies. It can also be written in different date formats or as elapsed milliseconds from Unix epoch time. It starts from the bottom of the list and if not found moves it's way up recursively until there are no more lines to read.
So the most easiest and the most readable way to do this (in my opinion) is by using nested try-catch blocks, but given that it's also a recursive method should in theory give lower performance?
Is this a bad code?
I can use bunch of if-else blocks together with DateTime.TryParse with additional variables for result, but that would make my eyes bleed. Does readability of code justify nested try-catch blocks for flow control?
static DateTime? Search(List<string> lines)
{
    if (lines.Count == 0)
    {
        return null;
    }

    DateTime? date = null;
    string dateField;

    try
    {
        dateField = lines.Last().Split(';')[18].Trim('\'').Trim();
        date = DateTime.ParseExact(dateField, "MM'/'dd'/'yy HH:mm:ss", null, DateTimeStyles.AllowWhiteSpaces);
    }
    catch (Exception)
    {
        try
        {
            dateField = lines.Last().Split(';')[19].Trim('\'').Trim();
            date = DateTime.ParseExact(dateField, "MM'/'dd'/'yy HH:mm:ss", null, DateTimeStyles.AllowWhiteSpaces);
        }
        catch (Exception)
        {
            try
            {
                dateField = lines.Last().Split(':')[9].Split('=')[1].Trim();
                date = FromUnixEpochTime(long.Parse(dateField));
            }
            catch (Exception)
            {
                try
                {
                    dateField = lines.Last().Split(':')[12].Split('=')[1].Trim();
                    date = FromUnixEpochTime(long.Parse(dateField));
                }
                catch (Exception)
                {
                    try
                    {
                        dateField = lines.Last().Split(':')[19].Trim('\'').Trim();
                        date = DateTime.ParseExact(dateField, "MM'/'dd'/'yy HH", null, DateTimeStyles.AllowWhiteSpaces);
                    }
                    catch (Exception)
                    {
                        lines.RemoveAt(lines.Count - 1);
                        date = Search(lines);
                    }
                }
            }
        }
    }

    return date;
}

A: You should never throw exceptions when you are intending to handle the code in the same section.  This makes debugging with exceptions turned on a nightmare.  My suggestion would be to have a main method that calls sub methods to try each type - and if the value is not what you expect - move to the next one.
    public DateTime? GetValue()
    {
        DateTime? value = null;

        // Regular way
        value = GetValueImpl1();

        if (value != null)
            return value;

        // Fall back 1
        value = GetValueImpl2();
        if (value != null)
            return value;

        // Fall back 2
        value = GetValueImpl3();
        if (value != null)
            return value;
        return null;
    }
    private DateTime? GetValueImpl1()
    {
        return new DateTime();
    }
    private DateTime? GetValueImpl2()
    {
        return new DateTime();
    }
    private DateTime? GetValueImpl3()
    {
        return new DateTime();
    }

A: I know you'd ruled them out, but I'd go with
TryParse

and
TryParseExact

(although AFAIK internally they just use try-catch.. but your code becomes much more readable)
I'd borrow the idea behind TryParse etc. and do something along the lines of .. (see below)
I think this style separates out each strategy and makes it more maintainable as there is less 'noise' (i.e. the exception catching) around each strategy
(I've allowed duplication in the example strategies but some of that could be re-factored out as well)
cheers
Stu
static DateTime? Search(List<string> lines)
{
    if (lines.Count == 0)
    {
        return null;
    }

    DateTime parsedDate;

    // the first successful strategy will 'short circuit' the rest so they don't run
    if(TryGetDateStrategy1(lines, out parsedDate)
        || TryGetDateStrategy2(lines, out parsedDate)
        || etc. etc.)
    {
        return parsedDate;
    }
    return null;
}

private static bool TryGetDateStrategy1(List<string> lines, out DateTime? date)
{
    var dateField = lines.Last().Split(';')[19].Trim('\'').Trim();
    DateTime parsedDate;
    if (DateTime.TryParseExact(dateField, "MM'/'dd'/'yy HH:mm:ss", null, DateTimeStyles.AllowWhiteSpaces,out date))
    {
        date = parsedDate;
        return true;
    }
    return false;
}
private static bool  TryGetDateStrategy2(List<string> lines, out DateTime? date)
{
    var dateField = lines.Last().Split(';')[18].Trim('\'').Trim();
    DateTime parsedDate;
    if (DateTime.TryParseExact(dateField, "MM'/'dd'/'yy HH:mm:ss", null, DateTimeStyles.AllowWhiteSpaces, out date))
    {
        date = parsedDate;
        return true;
    }
    return null;
}

A: Exceptions are meant for "exceptional" cases. They have bad performance times since they are handled differently than normal code. There are a lot of explanations on-line which explain why exceptions slow down the code.
using the tryParse method to check if your data is a date and then using if then else statements would be more efficient and arguably more concise and readable.
Also use string constants instead of typing the date format again. This produces code which is harder to maintain.
As an after thought you can use just if statements :
if (tryParse(...)){
   return Parse(...);
}

if (tryParse(...)){
   return Parse(...);
}

return null;

This would be the most readable without nesting and can be commented in a more readable manner


text:
Q: Regex for SQL Injection patterns in a JSP source code in Notepad++ I'm trying to create a regex to look for SQL Injection patterns in a JSP source code. I'm using the Notepad++ Find in Files functionality and I want to find a pattern across hundreds of files. Pattern would look something like this:
1) First part the file must contain any of these:

*

*doGet

*doPost

*doPut

*doDelete

*doCopy

*doOptions

2) Secondly the file must contain (note this can be String or Integer):
String foo = request.getParameter("bar");
3)Thirdly the file must also contain
select...where...+...foo...
Notice in the third part the SQL Statement is using the parameter set on the second part.
Another important note is that, there may be N amount of characters, new lines, returns, lines of code, or what have you, between each part.
Using https://regexr.com/ I came up with the following regex:
^.*doGet.*[\r\n]*.*String\s(.*)\s\=\srequest.getParameter.*[\r\n]*.*select.*where.*\+.*\1
Which matches the for example:
doGet();

String foo = request.getParameter('bar');

String qry = "select * from test where id =" + foo;

However it does not match:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
code = code.code;
test = test.test;
donothing();
}

String foo = request.getParameter('bar');

if(foo){
String qry = "select * from test where id =" + foo;
}

A: I came up with
(?=.*do(?:Get|Post|Put|Delete|Copy|Options)).*(?:String|Integer)\s*([a-zA-Z0-9_]+)\s*=\s*request\.getParameter\(\s*(["'])(?:\\.|(?!\2)[^\\])*\2\s*\)\s*;.*select.*where.*\+.*\1

make shure to activae the '. matches newline' checkbox.

A: It's pretty complicated, yet maybe you might want to design an expression, close to:
(?i).*\bdoGet\b[\s\S]*?String\s+(\S+)\s*=\s*request\.getParameter\(['"]bar['"]\)\s*;[\s\S]*?\bselect\s+.*\bfrom\b.*\bwhere\s+.*(\1)\s*;(?:[\r\n]*\})?

which would likely fail in some instances, by the way.

The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.

A: Thank you to @Code Maniac
^.*?doGet[\w\W]+?String ([^=]+) = request\.getParameter[\w\W]+?select.*where[^+]+\+ \1
Seems like it was the best answer that produced the least amount of false positives.


text:
Q: How to not disable triggers during deployment in SQL Server When deploying SQL Server Database projects (using either the SSDT Publish wizard or DACPAC deployment), the automated SQL scripts starts by disabling all triggers.
How do I avoid this?
And what are the side effects of not disabling triggers?
PRINT N'Disabling all DDL triggers...'
GO
DISABLE TRIGGER ALL ON DATABASE
GO
<ALL DB CHANGES>
GO
PRINT N'Reenabling DDL triggers...'
GO
ENABLE TRIGGER [LogSchemaChanges] ON DATABASE
GO
PRINT N'Update complete.';

Why would I do this? We have a trigger that logs all schema changes to an audit log.
...and Isn't it ironic, don't you think...

A: For manual Publish Wizard deployment, change the behaviour under:

*

*Advanced Publish Settings > General > Advanced Deployment Options.

*Deselect the "Disable and reenable DDL triggers".

For automated DACPAC deployment via SQLPackage, set the following publish property:
/p:DisableAndReenableDdlTriggers=False

Specifies whether Data Definition Language (DDL) triggers are disabled at the beginning of the publish process and re-enabled at the end of the publish action.


text:
Q: Find contours error: external component has thrown an exception using SharpCV, i want get contours list but get errror System.Runtime.InteropServices.SEHException: "External component has thrown an exception."
        var image = cv2.imread("b8ddbd62baa067f41dd8e821141ad835.jpg");
        var gray = cv2.cvtColor(image, ColorConversionCodes.COLOR_BGR2GRAY);
        var (ret, thresh) = cv2.threshold(gray, 127, 255, ThresholdTypes.THRESH_OTSU);
        var (contours, hierarchy) = cv2.findContours(thresh, RetrievalModes.RETR_EXTERNAL, ContourApproximationModes.CHAIN_APPROX_SIMPLE);

what i doing wrong ?


text:
Q: How can I bind my view model to a jqGrid? Using MVC2 and EF framework. Most references/blog posts I've found so far pertain to binding a single table and its data (sometimes hierarchical) to a jqGrid with editing capabilities. I don't need this. I don't even need to edit the data--just display. I need to display and page the data. Sorting is a plus, searching a bonus I guess.
jqGrid's documentation shows the data source being bound as follows:
return gridModel.OrdersGrid.DataBind(northWindModel.Orders);

But, I only have my Entities context without a reference to the view model. Could I create an Entity set here? Not very familiar with this.
All my view models contain data from several different tables. What can I do to bind the view model properties to a jqGrid? I'm playing with Trirand's 30-day trial of jqGrid for MVC. Again, I just need to display and page the data, but I'm not sure how to hook up the view models to the jqGrid data source.
Edit
public ActionResult test()
    {
        var gridModel = new testmodel();
        var viewModel = gridModel.testgrid;
        SetupTestGrid(viewModel);
        return View(gridModel);
    }

    private void SetupTestGrid(JQGrid viewModel)
    {
        viewModel.ID = "TestGrid";
        viewModel.DataUrl = Url.Action("SearchTestGridDataRequested");
        viewModel.ToolBarSettings.ShowEditButton = false;
        viewModel.ToolBarSettings.ShowAddButton = false;
        viewModel.ToolBarSettings.ShowDeleteButton = false;
    }

    public JsonResult SearchTestGridDataRequested(string sidx, string sord, int page, int rows)
    {
        var gridModel = new testmodel(sidx, sord, page, rows);
        SetupTestGrid(gridModel.testgrid);
        return Json(gridModel.datasource);
    }

In testmodel and testmodel(parameters), I create an anonymous type (named datasource) containing Phil Haack's parameters; total, page, records and rows. This property is JSON'ified in the last statement of SearchTestGridDataRequested.

A: I don't really know the commercial version of the jqGrid, but the product use internally the Open Source jqGrid and so I could explain how it should work together with ASP.NET MVC.
In general to use jqGrid in MVC you can have a page (a View) with two elements <table> and a <div> used for the pager. Both (<table> and <div>) must have and id attribute. No other complex View binding to the Model is required.
Now you can place in the header of the page loading of all JavaScripts needed: jQuery, jqGrid and you page specific JavaScript which define jqGrid which you want to display, for example column model and different jqGrid parameters. The most important parameter which you need to bind the grid to the data are url parameter. If you define for example in the Home controller the action GetData then the url could be "Home/GetData" or '<%= Url.Content("~/Home/GetData")%>'. This is enough of have "data binding". No usage of Model data is required.
The action GetData could be defined as following:
JsonResult GetData(string sidx, string sord, int page, int rows)

if you want support only data sorting and paging but don't need any searching (filtering) support.
In case of the searching support you need to add an additional parameters. If you want to use Advanced Searching or Toolbar Searching with stringResult:true parameter you should add one additional parameter string filter:
JsonResult GetData (string sidx, string sord, int page, int rows, string filter)

In case of implementing Single Field Searching in your grid it should be
JsonResult GetData (string sidx, string sord, int page, int rows,
                    string searchField, string searchString, string searchOper)

You can also make an universal action:
JsonResult GetData (string sidx, string sord, int page, int rows, string _search
                    string searchField, string searchString, string searchOper,
                    string filter)

So in all cases you have to do almost the same, but you will receive additional parameters in a little other form.
Now you should decide in which form you want provide the data for jqGrid from the controller action. jqGrid is very flexible and you can either get back data in the standard format
{
  "total": "xxx",   // the total number of pages
  "page": "yyy",    // the current page number of the data returned
  "records": "zzz", // the total number of records
  "rows" : [
    {"id" :"1", "cell" :["cell11", "cell12", ...,  "cell1n"]},
    {"id" :"2", "cell":["cell21", "cell22", ..., "cell2n"]},
      ...
  ]
}

or in another (more readable, but more long) format. In the last case you will have to define a small parameter jsonReader which describe how the data should be read (see documentation).
If you look inside of some old answers like this, this, this or this you will find enough code fragments of full working MVC projects which you can modify for your propose. The first reference from the list should gives hopefully the answer on you main question how to prepare data from EF source or any other IQueryable<T> source the data which jqGrid need.
In another my old answer where I describe the general schema how jqGrid can be used in MVC environment more detailed, but for people who tested already different implementation ways.


text:
Q: How to keep leading/prefix zeros when export to Excel/csv by SQL query statement? I use Oracle and I would like to know how to keep leading/prefix zeros when export to Excel/csv by below SQL query statement?
Supposed B.h(string type) maybe have the values of 00068573 and 098235
SELECT A.e,
       A.f,
       A.g,
       B.h
FROM A
JOIN C ON C.e=A.e
JOIN B ON C.j=B.j;

and I export data in Python, partial code as below:
for row_data in cursor:
    output.writerow(row_data)

Thank you so much for any advice.

A: set heading off
set termout OFF
SET FEEDBACK OFF
SET TAB OFF
set pause off
set verify off
SET UNDERLINE OFF
set trimspool on
set timing off
set echo off
set linesize 1000
set pagesize 0
COLUMN CODE2 FORMAT 09999999
SET COLSEP ';'
spool test.csv

SELECT A.e,
       A.f,
       A.g,
       B.h as code2
FROM A
JOIN C ON C.e=A.e
JOIN B ON C.j=B.j;
spool off
exit;

or use     to_char(B.h, '09999999')
set heading off
    set termout OFF
    SET FEEDBACK OFF
    SET TAB OFF
    set pause off
    set verify off
    SET UNDERLINE OFF
    set trimspool on
    set timing off
    set echo off
    set linesize 1000
    set pagesize 0
    SET COLSEP ';'
    spool test.csv

    SELECT A.e,
           A.f,
           A.g,
           to_char(B.h, '09999999')
    FROM A
    JOIN C ON C.e=A.e
    JOIN B ON C.j=B.j;
    spool off
    exit;

if the field is character then you need to use the lpad function.
 SELECT A.e,
           A.f,
           A.g,
           LPAD(B.h, 9, '0')
    FROM A
    JOIN C ON C.e=A.e
    JOIN B ON C.j=B.j;

A: You must have done export in csv format. From the Oracle export you will get actual value including leading zero. Open the .csv file in the text editor and check the values. There is nothing to do with sql if you are getting export by using any of IDE (i.e. SQL developer)

A: Above said is Absolutely right, will add:-

*

*opening csv by double clicking opens it in excel which won't show trailing zeroes.

*You can open in text to confirm that you will have zeroes.

*Now to use in excel, simply open a new excel >> Go to "Data" TAB >> "GET DATA">> From a File  and choose csv/txt. This way it will load properly without removing trailing zeroes also you will have some options like changing encoding.


text:
Q: Why do I have so many errors from the BaseGameUtils library? I am following this link
https://developers.google.com/games/services/android/init
With trying to add leaderboards to an android app but after I follow step 1 and it is added it throws up over 100 errors and a Jar mismatch! Fix your dependencieserror, that I understand why.
I have added the google play library no problem and gotten adverts to work by following Google's documentation but the leaderboard documentation seems to be sending me all over the place and not helping at all.
Could someone please shed some light on this, thanks!

A: Ok because I am still new to Android and Eclipse I had added the reference to the BaseGameUtils in the properties for the project but you have to add the Google play services as a reference for the BaseGameUtils by right clicking and selecting properties then add it as you did for the main project.


text:
Q: Node js post request body in Joi Validation Package Recently I am working with node js and Joi a validation package for node. I send post data through postman using the body, no params. But in node js application the request body shows undefined. Here are the snips:
const express = require('express');
const Joi = require('joi');
const app = express();

app.listen(3000, () => 'Server is listening on 3000');

app.post('/users', (request, response) => {
    const schema = Joi.object().keys({
        username: Joi.string()
            .alphanum()
            .min(3)
            .max(30)
            .required()
    });

    const result = Joi.validate(request.body, schema);
    response.send(result);
});

A: I think you forgot body-parser
u can use the body-parser package
npm I body-parser

so u can use it, like this
const bp = require('body-parser')
app.use(bp.json())

or u can use from express to
app.use(express.json())

A: use this example

const express = require('express');
const bodyParser = require('body-parser');
const Joi = require('joi');
const expressJoi = require('express-joi-validator');
var app = express();

app.use(bodyParser.json());

const schema = {
    query: {
        name: Joi.string().required()
    },
    body: {
        age: Joi.number().required(),
        company: Joi.object({
            name: Joi.string().required(),
            role: Joi.string().required().valid('HR', 'Technical') //enum style validation
        }).required()
    },
    params: {
        id: Joi.number().required()
    }
}

app.post('/testapi/:id', expressJoi(schema), function(req, res){
    res.send('validated');
});

//error handler
app.use(function (err, req, res, next) {
    if (err.isBoom) {
         return res.status(err.output.statusCode).json(err.output.payload);
    }
});

app.listen('3000',  ()=>{
    console.log(`listening to 3000`);
});


text:
Q: Custom route to handle authorized users? I would like to create a custom express route that would allow to determine if a user has the right to access a page or not.
So far I got it working by using something like that :
import React from 'react';
import { Route } from 'react-router-dom';

import { AuthenticationContext } from '../../contexts/authentication/context';

import Unauthorized from '../Unauthorized';

import axios from 'axios';

const ProtectedRoute = ({ component: Component, redirect: Redirect, contextProvider: ContextProvider, path, ...routeProps }) => {

  const { authenticationState: {isAuthenticated, isFetchingTheUser, currentUser} } = React.useContext(AuthenticationContext)

  const [authorized, setAuthorized] = React.useState([]);
  const [isFetchingAuthorizations, setIsFetchingAuthorizations] = React.useState(false);

  React.useEffect(() => {

    setIsFetchingAuthorizations(true);
    axios.get(`${global.REST_API_ADDR}/api/pages/${encodeURIComponent(path)}`)
    .then((response) => {
      setAuthorized(response.data.authorized);
      setIsFetchingAuthorizations(false);
    })
    .catch((error) => {
      setIsFetchingAuthorizations(false);

      // console.log("Protected route use Effect error : ", error);
    })
  }, [path])

  return (
    <Route {...routeProps}
      render={ props => {

        if(isFetchingTheUser || isFetchingAuthorizations) return
Chargement...

        if(isAuthenticated && authorized.includes(currentUser.rank)){
          return ContextProvider ? <ContextProvider><Component {...props} /></ContextProvider> : <Component {...props} />
        }else if(isAuthenticated && !authorized.includes(currentUser.rank)) {
          return <Unauthorized {...props} />;
        }
        else{
          return <Redirect {...props}/>;
        }
    }}/>
  );

};

export default ProtectedRoute;

The problem here is that if the user changes routes a second time, the component will keep the previous authorized array for a few milliseconds, render the component and if the component has any kind of
useEffect with some API calls it will throw an error in the console. I would like to know if there is any way to prevent this ?
Like maybe emptying the state after the route renders the component ?
Thanks in advance,
EDIT 1 : from the user's point of view there are no visual bugs or latency but as a developer I have a hard time leaving an error message in the console if there is any way to avoid it


text:
Q: OpenCart Breadcrumb in header.tpl Can someone tell me how can I have the breadcrumb nav within the header.tpl and not in the product.tpl of opencart?

A: I've just had to figure this out for a new site we're building and I've come up with the following; use at your own risk (I'll report back if I run into any major problems, but I can't foresee any... famous last words)
Basically the breadcrumbs are built in the controllers and we need the resulting $breadcrumbs array in the header controller. Modify system/engine/controller.php as follows:
[...snip...]
protected function render() {
    foreach ($this->children as $child) {
        $this->data[basename($child)] = $this->getChild($child,array('parent_data'=>&$this->data));
}
[...snip...]

This will send all the data in the parent controller, before render() was called, to every controller/method of the $children. Then we just need to pick this up in the header controller as follows:
<?php
class ControllerCommonHeader extends Controller {
    protected function index($args=array()) {
        // parent data
        $this->data['parent_data'] = $args['parent_data'];
[...snip...]

And we can access everything in the template with $parent_data['whatever']. In this case, $parent_data['breadcrumbs'] will be the array of breadcrumbs that I can loop over with the code I've removed from each page.tpl and added to my header.tpl.

A: Due to the way 1.5.X is coded, you'll need to rewrite every controller and add a method back to the document class to allow passing from the product controller to the header controller. Is there any particular reason you want to do so?

A: if all else fails just hack the css, something like
.breadcrumb {
   margin-left: -270px;
   margin-top: -65px;
}

will move the breadcrumb up and to the left.


text:
Q: Java version of MVVM? My partner and I decided to go with JSP, JAVA as our model for a social networking site.  At first, I was a bit afraid it would become a mess, but now it is still working fine and adding new features is not very hard.
However I still do have the bad feeling that we are going the wrong way. as far as I understand the main paradigam today is MVVM.  I was wondering

*

*Does JAVA have any framework to support this?

*is it worth migrating to SilverLight? ASP.NET?

A: Start asking these questions:

*

*What is the most familiar to you and your team? (If you're all Java programmers, then find a good Java framework.)

*What frameworks have a solid reputation for handling increasing complexity without becoming overly resistant to change? (Hint: Not PHP, at least not without a framework.)

*What frameworks are proven scalable in production?

*What frameworks are easiest to support in production?

*What frameworks offer deployment flexibility (if that's a concern)?

*How heavily will you use AJAX? Just a bit of PPR here and there or pure AJAX?

A: Have a look at Silk, Microsoft Patterns and Practices Team guidance for developing web applications.
The back-end is MVC3 C# but you'll easily find a Java implementation for that.
Interesting is the front end.  It uses MVVM in JavaScript (Knockout.js)
Worthwile a visit!!
So I would say, go for a good Java MVC framework for the backend and use this guidance for the client-side.

A: Well you can choose between Java, ASP.NET depending on the programmer's expertise you have. You also have a choice for Ruby and PHP too.

*

*For Java, I would suggest to go for a Seam Framework which encompasses JSF, Richfaces, Ajax and others . View Seam Framework.

*For ASP.NET you can go for MVC 3, even the site you are viewing is built on ASP.NET MVC 3. Visit MVC framework and MVC 3.

*For Ruby, you can go for Ruby on Rails which was one of the first to make an impact over the MVC framework way of development. View Ruby on Rails.

*For PHP you can go for CakePHP or CodeIgniter for MVC framework.

Specific Links for MVVM Framework:
Quick Tour of existing MVVM Frameworks
MVVM light toolkit for WPF and Silverlight
WPF Model-View-ViewModel Toolkit
Caliburn
Silverlight.FX

A: If you are thinking about Java Web Ajax Programming, ZK Ajax framework supports MVVM design pattern seamlessly.
Following is some articles you might feel interested:

*

*MVVM in ZK6 - Design your first MVVM page

*MVVM in ZK6 - Design CRUD page by MVVM_pattern
Its data binding system for MVVM design pattern utilizes EL 2.2 expression syntax, so it is quite flexible.

A: Have a look of this slides about Presentation Patterns. It is about which design pattern fit most to your application; not about which pattern is the best one.
http://www.slideshare.net/simbo1905/design-patterns-in-zk-java-mvvm-as-modelviewbinder


text:
Q: Doubt regarding proof from Milnor's notes I was reading Milnor's 1958 notes in differential topology and came across the following theorem

Theorem: Let $U$ be an open set in $\mathbb{R}^n$ and let $f;U \to \mathbb{R}^p$ be differentiable, where $p \geq 2n$. Given $\epsilon$ >
  $0$, there is a $p \times n$ matrix $A = (a^i_j)$ with each $|a^i_j| <$
  $\epsilon$, such that $g(x) = f(x) + Ax$ is an immersion.
Proof: $Dg = Df+A$; we would like to choose $A$ in such a way that $Dg(x)$ has rank $n$ for all $x$. i.e. $A$ should be of the form
  $Q-Df$, where $Q$ has rank $n$.
Define $F_k:\mathcal{M}(p,n;k) \times U \to \mathcal{M}(p,n)$ by the
  equation $$F_k(Q,x) = Q-Df(x)$$  $\mathcal{M}(p,n;k)$ is a submanifold
  of $\mathcal{M}(p,n)$ of dimension $k(p+n-k)$. $F_k$ is
  differentiable, and the domain of $F_k$ has dimension $k(p+n-k)+n$. As
  long as $k<n$, this expression is monotonic in $k$. Hence the domain
  of $F_k$ has dimension not greater than
  $$(n-1)(p+n-(n-1))+n=(2n-p)+pn-1$$ for $k<n$. Since $p\geq 2n$, this
  dimension is strictly less than $pn=$ dim($\mathcal{M}(p,n)$). Hence
  the image of $F_k$ has measure zero in $\mathcal{M}(p,n)$, so that
  there is an element $A$ of $\mathcal{M}(p,n)$, arbitrarily close to
  the zero matrix, which is not in the image of $F_k$ for $k=0, \dots$ ,
  $n-1$. Then $A + Df(x)$ has rank $n$ for each $x$.

I dont understand the last part of the proof. i.e. How he concludes that $A+Df$ has rank $n$? Is it because $F_k$ is surjective and hence the chosen $A$ arbitrarily close to the origin satisfies $A=Q-Df(x)$ for some $x$ and $Q$ of rank $n$ and hence $A+Df(x)=Q$ has rank $n$ everywhere ? Please help. Thanks.

A: If $A+Df(x)=Q$ has rank $k<n$ for some $x \in U$,  then $A=Q-Df(x)$ so that $A$ is in the image of $F_k$.  This contradicts the fact that $A$ was chosen to be outside the image of $F_k$ for all $k<n$.


text:
Q: Enterprise Architect set positions of elements and associated complex types I have to determine the position of XML elements in a sequence model group. I use the "position" tagged value (starting from 1) to achieve that. It works, if the XSDcomplexType only contains elements with the XSDelement stereotype or if it has only associations to other XSDcomplexTyp classes (with the tagged value "position" on the "Connector Source").
If I try to sort the sequence of complex types, which have XSDelements and associations to other XSDcomplexTyp classes, the defined sequence will be ignored. I noticed that in this case, the associated elements will be added at first.
I use the Enterprise Architect in version 15.1.1526.
Is there any way to fix the order of the elements defined in the XSDcomplexType and the elements, which will be generated by the association, to other XSDcomplexType classes?


text:
Q: Entity Framework Track Changes of Entity Property? Appreciate your help and guidance, please.
I have an Entity Candidate which I am able to track changes, however, the Entity itself shows Unchanged even though I have updated the Property FirstName of the Entity Candidate. The ChangeTracker.DebugView.LongView shows 'AVS' Originally 'AVS123'
So what I am doing wrong here? why the status of the Candidate {Id: 13} still shows Unchanged.
private void txtFirstName_Leave(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(txtCandidateId.Text);
        Candidate candidate = _dbContext.Candidates.FirstOrDefault(t => t.Id == id);

        candidate.FirstName = txtFirstName.Text;

        Debug.WriteLine(_dbContext.ChangeTracker.DebugView.LongView);
    }

Output:
Candidate {Id: 13} Unchanged
  Id: 13 PK
  DateOfBirth: '7/15/2022 12:00:00 AM'
  Email: '1234@gmail.com'
  ExpectedJoinDate: <null>
  FirstName: 'AVS' Originally 'AVS123'
  Gender: 'Male'
  LastName: 'Dev'


text:
Q: Get the default Firefox profile directory from bash I'm trying to get the profile directory of the default firefox profile (the one that opens automatically) from Bash. How could I proceed? I can't find any useful options issuing firefox --help

A: Your default profile directory is stored under home directory.
cd ~/.mozilla/firefox

Here you will find something like xxxxxxxx.default. This is the location where all your personal data is stored.
You can run the command firefox -P to show the profiles available and select one from the list.

A: Try grep 'Path=' ~/.mozilla/firefox/profiles.ini | sed s/^Path=//. Default profile folder name is stored in profiles.ini. This will work fine while you've got single profile.
If you have more than one Firefox profile then the file format changes, so extracting the folder name becomes more tricky. Here's the script to do that:
#!/bin/bash

cd ~/.mozilla/firefox/
if [[ $(grep '\[Profile[^0]\]' profiles.ini) ]]
then PROFPATH=$(grep -E '^\[Profile|^Path|^Default' profiles.ini | grep -1 '^Default=1' | grep '^Path' | cut -c6-)
else PROFPATH=$(grep 'Path=' profiles.ini | sed 's/^Path=//')
fi

echo $PROFPATH

This script will work in both cases, it selects the appropriate method depending on the amount of profiles. Works in OSX, too.

A: I know that this a little older, but in case someone else also needs this information, here is how I set the default profile variable in a wrapper script for firefox:
def_Pfile=`cat "$HOME/.mozilla/firefox/profiles.ini" | sed -n -e 's/^.*Path=//p' | head -n 1`

Hope this helps, as it works for me.

A: It works like a charm on linux.
My profile.ini
cat "$HOME/.mozilla/firefox/profiles.ini"
[Install4F96D1932A9F858E]
Default=4hthy81n.default-release
Locked=1

[Profile1]
Name=default
IsRelative=1
Path=t6kac19e.default
Default=1

[Profile0]
Name=default-release
IsRelative=1
Path=4hthy81n.default-release

[General]
StartWithLastProfile=1
Version=2

So run this command:
grep "Default=.*\.default*" "$HOME/.mozilla/firefox/profiles.ini" | cut -d"=" -f2

about:profiles:


text:
Q: Draggable UI in jQuery I am currently working on a project where I need to go for draggable elements. There will be list of options e.g. Sunday, Monday, Tuesday... Saturday. Here user will be selecting any of them, say Sunday, Wednesday, Saturday. I need to display them in such a way the user can realign them in any Order.
E.g
Sunday
Saturday
Wednesday

or
Sunday
Wednesday
Saturday

And I need to get the display order in my Client/ Server side
I have decided to provided asp checkboxs for the parent list. When user checks any of the option, I need to populate it in another UI which would later helps me to realign the selected options. I have gone through few samples of draggable jQuery UI but not sure which will suit my requirement.
Can any one suggest the BEST?

A: I think this should be enough for you:
http://jqueryui.com/demos/draggable/#sortable
Also, I would suggest not using the checkboxes but adding another draggable component that marks the limit between used and unused days, like:
> Saturday
> Sunday
> **Below are ignored**
> ...

I think it may be more usable.

A: I think this project helps you
http://arshaw.com/fullcalendar/
Also you can find samples on these links
http://www.webresourcesdepot.com/wp-content/uploads/file/jquerydragdrop/
http://net.tutsplus.com/tutorials/javascript-ajax/drag-to-share/
http://tutorialzine.com/2009/09/shopping-cart-php-jquery/
http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/


text:
Q: Stop Mapbox GL JS Zoom Event I have a zoom listener in my mapbox gl (1.10) application
this.map.on('zoom' e => {
  if (suchAndSuch()) {
    stopTheZoomFromHappening(e);
  }
})

I have tried e.originalEvent.preventDefault(), and e.originalEvent.stopPropagation(). I have also tried listening to the zoomstart event. The zoom is not cancelled.
I know there is disableScrollZoom, and other disable<type>Zoom, but it seems cumbersome to disable, enable in this way.
Is there a way to stop a single zoom event from having an effect on the map?


text:
Q: Proof (or reference) about $\lambda_i(A+\epsilon e_je_j^*) = \lambda_i(A) + \epsilon |v_{i,j}|^2 + O(\epsilon^2).$ I'm looking for a proof (or a reference in a textbook) about the fact that
$$
\lambda_i(A+\epsilon e_je_j^*) =_{\epsilon \to 0} \lambda_i(A) + \epsilon |v_{i,j}|^2 + O(\epsilon^2),
$$
where $A$ is a hermitian matrix (having distinct eigenvalues), $\lambda_i(A)$ is an eigenvalue of $A$, $e_j \in \bf{R}^n$ is defined by $(e_j)_i = \delta_{i,j}$, $v_{i,j}$ is the $j-$th component of a unit eigenvector of $\lambda_i(A)$.
This theorem is from perturbation theory, a field I'm not very familiar with.
This is used in : Peter B. Denton, Stephen J. Parke, Terence Tao and Xining Zhang. $\textit{Eigenvectors from eigenvalues: A survey of a basic identity in linear algebra}, 2021;$
arXiv:1908.03795 (page $13$).

A: This is  first order perturbation theory: a perturbation $\delta A$ to a Hermitian matrix $A$ gives to first order a correction $\delta \lambda$ to an eigenvalue $\lambda$ (with corresponding eigenvector $v$) equal to
$$\delta\lambda=\sum_{n,m}\delta A_{nm}\bar{v}_nv_m.$$
In this case $\delta A_{nm}=\epsilon\delta_{nj}\delta_{mj}$, hence
$$\delta\lambda=\epsilon|v_j|^2+{\cal O}(\epsilon^2).$$
The link I gave above is to the derivation in Wikipedia, if you prefer a textbook, see chapter 7 of Introduction to Quantum Mechanics by Griffiths.

A: I think I found what I was looking for:

*

*First, I found a proof using the implicit function theorem showing that if $A(\epsilon) = A + \epsilon e_j e_j^*$ is $\mathscr{C}^1$ (which is the case) and the eigenvalues of $A$ are distinct, then for $\epsilon$ small enough $\epsilon \mapsto \lambda_i(A(\epsilon))$ is $\mathscr{C}^1$ and we can pick an eigenvector $v_i(\epsilon)$ such that $\epsilon \mapsto v_i(\epsilon)$ is also $\mathscr{C}^1$ (see here).

*Thanks to @JeanMarie (see here) I saw that what I was looking for is equation $(5)$ in this article (the above justifies taking the derivative in the article), so I get $\dot{{\lambda}_i}(0) = |v_{i,j}|^2$ $-$ where $\lambda_i(\epsilon) = \lambda_i(A(\epsilon))$ $-$ ie. $\lambda_i(\epsilon)=\lambda_i(A + \epsilon e_j e_j^*)=_{\epsilon \to 0} \lambda_i(A) + \epsilon |v_{i,j}|^2 + o(\epsilon)$.


text:
Q: WPF Datagrid Style not working for DataGrid with a DataTable as the ItemSource I have a DataGrid and its ItemSource is set to the DefaultView of a DataTable as follows
TestGrid.ItemsSource = custTable.DefaultView;

It works fine, What i really want to do is that if the DataGrid contains a cell having the value "0" i want that cell to be coloured yellow no matter where ever the cell is located in the DataGrid. for that i did the following in the XAML part....
<Grid>
    <DataGrid Name="TestGrid" Height="auto" Width="auto" >
        <DataGrid.Columns>
            <DataGridTextColumn>
                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="{x:Type TextBlock}">
                        <Style.Triggers>
                            <Trigger Property="Text" Value="0">
                                <Setter Property="Background" Value="Yellow"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

But this is not working.. How can i solve this?


text:
Q: Why do i get Exception User-unhandled System.Data.sqlException: 'Conversion failed when converting the nvarchar value '400,000' to datatype int.' I am developing a business app using ASP.NET and C#, when I input data and click the save button, it throws that error:

Exception User-unhandled
System.Data.sqlException: 'Conversion failed when converting the nvarchar value '400,000' to datatype int.'

<%@ Page Title="" Language="C#" MasterPageFile="~/SMS.Master" AutoEventWireup="true" CodeBehind="CoursePage.aspx.cs" Inherits="Student_Management_System.CoursePage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

Course Page

            Course Name:

                <asp:TextBox ID="TxtCourseName" runat="server"></asp:TextBox>

            Course Fee:

                <asp:TextBox ID="TxtCourseFee" runat="server"></asp:TextBox>

            Course Duration:

                <asp:DropDownList ID="DropDownList1" runat="server">
                            <asp:ListItem Text="-- SELECT --" Value="select"
Selected="True"></asp:ListItem>
                            <asp:ListItem Text="3 Months" Value="3 Months"></asp:ListItem>
                            <asp:ListItem Text="6 Months" Value="6 Months"></asp:ListItem>
                            <asp:ListItem Text="9 Months" Value="9 Months"></asp:ListItem>
                            <asp:ListItem Text="1 Year" Value="1 Year"></asp:ListItem>
                            <asp:ListItem Text="2 Years" Value="2 Years"></asp:ListItem>
                </asp:DropDownList>

                <asp:Button ID="ButCourse" runat="server" Text="Save"
OnClick="ButCourse_Click" />

</asp:Content>

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Student_Management_System
{
    public partial class CoursePage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void ButCourse_Click(object sender, EventArgs e)
        {
            string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;

            SqlConnection sqlconn = new SqlConnection(mainconn);

            string sqlquery = "Insert into [dbo].[Course] (CourseName, CourseFee, CourseDuration) values (@CourseName, @CourseFee, @CourseDuration)";

            SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);

            sqlconn.Open();

            sqlcomm.Parameters.AddWithValue("@CourseName", TxtCourseName.Text);
            sqlcomm.Parameters.AddWithValue("@CourseFee", TxtCourseFee.Text);
            sqlcomm.Parameters.AddWithValue("@CourseDuration", DropDownList1.Text);

            sqlcomm.ExecuteNonQuery();

            Response.Write("");

            TxtCourseName.Text = "";
            TxtCourseFee.Text = "";

            sqlconn.Close();
        }
    }
}


text:
Q: inserting timestamp in mysql table in python bid, best_bid_quantity are floats, target_date is set as timestamp in my db.
get timestamp
target_date_time_ms = (k.lastRestRequestTimestamp)

base_datetime = datetime.datetime( 1970, 1, 1 )

delta = datetime.timedelta( 0, 0, 0, target_date_time_ms )

target_date = base_datetime + delta

timestamp = target_date
db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                         user="root",         # your username
                         passwd="lolilol",  # your password
                         db="test")        # name of the data base

cur = db.cursor()

try:

   cur.execute("""INSERT INTO test1 (heure, prix, quantite) VALUES ({},{},{})""".format(target_date, bid, best_bid_quantity))
   db.commit()

except:
    print('did not insert')
    db.rollback()

db.close()

error --> it goes to except when I add the target_date

A: Try using time.strftime():
time.strftime('%Y-%m-%d %H:%M:%S', target_date.timetuple())

The .timetuple() method is required to convert the datetime.datetime object of target_date into a time_struct struct, which can then be used in the call to time.strftime.


text:
Q: command output > sed replace after a particular string Hello I am trying to insert the output of command output > sed replace after a particular string in a file as part of user data on machine boot up
[centos@ip-192-168-2-22 scylla]$ sudo sed -i.bak 's/broadcast_rpc_address: : /broadcast_rpc_address:\/$hostname -i | awk '{print $2}'/' /etc/scylla/scylla.yaml

file is currently
broadcast_rpc_address:

replace with
broadcast_rpc_address: (the ip of the machine)

A: Something like this should work:
sed -i.bak "s/broadcast_rpc_address:/broadcast_rpc_address: $(hostname -i)/" /etc/scylla/scylla.yaml

This will replace broadcast_rpc_address: by broadcast_rpc_address: $(hostname -i). Now, because this string is in double quotes - not single quotes - this tells the shell to interpret some magic sequences inside the string. In particular $(somecommand) means to run somecommand and insert its output into the string. Of course, change "hostname -i" in the command I gave above to anything else you want (it can even be an entire pipeline.
Your original attempt used something that started with $hostname. This syntax, $hostname, doesn't run the command hostname, but rather looks for a variable called hostname, which isn't what you wanted. You need the $(...) syntax instead. Your original attempt also had problems with nested quotes, which don't work.


text:
Q: How to remove file when over quota without root permissions and truncate, dd, mv, cp, and rm fail? I'm working on a file system where I don't have root permissions and all of the above have failed to allow me to delete a file with the same errors:
$ >file1
$ -bash: file1: Disk quota exceeded

$ dd count=1 if=/dev/random of=file1
$ dd: opening `file1': Disk quota exceeded

$ rm file1
$ rm: cannot remove 'file1': Disk quota exceeded

$ cat /dev/null > file1
$ -bash: file1: Disk quota exceeded

Also tried this on a buch of files:
$ mv file1 f
$ mv: cannot move `file1` to `f`: Disk quota exceeded

edit
have now also tried:
$ cp /dev/null file1
$ cp: cannot create regular file 'file1': Disk quota exceeded

to no avail (same error msg received)
there are a lot of other files I that just give me a permission denied error but I think for some of those it's because I don't have root permissions. Anyways, there are plenty of files for which I do have write permissions so I really just need a way to force those files to be erased. Is there any workaround I can use?
Output of df -s for this filesystem:
Filesystem            Size  Used Avail Use% Mounted on
zfs1.local:/volatile  699G  699G     0 100% /nfs/volatile

A: In my case, none of the above worked when the quota was 100% full. Fortunately the /tmp was not full so I did:
rsync --remove-source-files -azv file1 /tmp

and it solved the problem.

A: I have recovered the system using the command 'wipe'. Execute wipe on some big file and then try to use the command 'rm'. it will work.


text:
Q: Issue with Fancybox in modal mode Given this link within the FancyBox framework:
Update

If I click this link physically, The FancyBox modal window pops up and displays the contents of the User Update page. The window is in modal mode and the only way to close the window is via the Close / X. Clicking outside of the modal does nothing. So far so good.
However, if I try and trigger the window like this:
$("#userLink").fancybox().trigger('click');

The User Update page pops up in a modal as required, BUT clicking outside the modal now triggers the close event and the window is closed.
Any ideas why this is happening???
Ultimately what I would like is for the modal's behaviour to be consistent. But if no solution can be found for this, is there not perhaps a way to override the click event causing the modal to close and disable it?
Thanks, anyone?

A: You need to specify the modal behavior when you call fancybox() like that. You're likely overwriting the settings you provided the other way when you call it in that fashion. So in order to retain your settings, do this:
$("#userLink").fancybox({modal:true}).trigger('click');

But I would recommend you try: $("#userLink").click(); which will trigger the click event and should use your existing settings.

A: You can also use the fancybox api

*

*hideOnContentClick:false

*hideOnOverlayClick:false

Hope this will help

A: Just add parent: "form:first" to .fancybox({ }); function.
example:
$(".various").fancybox({
                maxWidth: 800,
                maxHeight: 600,
                fitToView: false,
                width: '50%',
                height: '50%',
                autoSize: false,
                closeClick: false,
                openEffect: 'none',
                closeEffect: 'none',
                parent: "form:first"
            });


text:
Q: django HttpResponse Location redirect I am trying to redirect to another page when http response is True I have added response['Location'] = 'login.html' but it's not working, I am getting a page with True written but not the login page. Can you help me I am new to django.
I have written this code
if user_obj:
    response = HttpResponse(True)
    response['Location'] = 'login.html'
    return response
else:
    return HttpResponse(False)

A: from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))

A: You can simple use Django core redirect function.
if user_obj:
    // Do something
    return redirect('some_url')

A: This will not work because you do not use a response in the 300-399 range, which are used for redirection, for example the HTTP 302 Found [wiki]. You furthermore do not need to do this yourself, you can make use of Django's HttpResponseRedirect(…) [Django-doc]:
if user_obj:
    return HttpResponseRedirect('login.html')

else:
    return HttpResponse(False)
You can also specify content, but normally if the browser makes the redirect, this will not show up for long:
if user_obj:
    return HttpResponseRedirect('login.html', content='True')

else:
    return HttpResponse(False)
Using .html however is (at least by Django) considered "ugly". It is also better to make use of reverse, or redirect to resolve the URL for a given view.


text:
Q: The force causing galaxies to accelerate away from each other? The galaxies in the universe appear to be accelerating away from each other according to the Doppler shift that is present in the light we receive from other galaxies.
According to Newtonian mechanics for something to accelerate, a force must be applied to it, and if the accleration is constant, then the force must be constantly applied.
If this is the case, then what force or forces is (or are) causing galaxies to accelerate?

A: Newtonian mechanics does not explain the dynamics of the universe.
The expansion of space is apparently "caused" by an innate property of the vacuum.
The name we give to this property is dark energy.
In the absence of any gravitating matter, the dark energy content of the universe causes space to expand as a natural consequence of solving the dynamics of the whole universe according to the theory of General Relativity.
In GR, mass, energy and pressure all act to gravitationally decelerate any expansion. Dark energy acts like a negative pressure that causes accelerating expansion, and there is no evidence at the moment that its energy density (i.e. energy per unit volume) changes with time - so it is sometimes referred to as the cosmological constant.
It is still a matter of theoretical speculation at present as to what dark energy is.
However, before observations of the cosmic microwave background and distant type Ia supernovae revealed the need for dark energy, it was still known that the universe expanded and the equations of GR still permit an expanding (although decelerating) universe without dark energy. One idea is that the universal expansion was kicked off by cosmic inflation - a souped-up version of dark energy that caused the universe to expand exponentially for a short period of time in the first tiny fraction of a second after the big bang.

A: Dark Energy is thought to be responsible for an ever expanding Universe. And we cannot understand this phenomenon based on Newtonian Mechanics as it is not applicable in cosmological scales. You can think of this energy as a negative pressure due to vacuum. But we truly don't know anything else about its nature and characteristics. However, DES survey is under way to understand more of it in the coming decade.


text:
Q: A safety relay systems circuit Can someone help explain the operation of a safety relay system. I know that they can be connected to e-stops for emergency stops but I don't understand the relays and how they operate.

A: In general , safety relay contacts are mechanically linked or "force guided". in other words and i quote phoenixcontact " Forced guidance means that the N/O and N/C contacts of an elementary relay are linked to one another mechanically. This prevents N/O and N/C contacts from closing at the same time. When used together with a suitable circuit, failure to open is reliably detected. This is the most reliable way of ensuring maximum safety for both person and machine "
Offcourse addition circuits and interlocks are added to a safety relay module for diagnostics
EDIT after the new image you posted: In the figure K1 and K2 are 2 separate contacts connected in series , the horizontal line with 4 dots near letter K1 and K2 means the contacts are mechanically linked
13-23-33 are connected to 14-24-34 when the relay is energized through A1-A2 . while 41 to 42 will be open. Y32 is not clear what it does , it should be mensioned in the data sheet. S34 appears to be a reset pin if fault occuered.
for more details check this answer : Safety Relay Symbol

A: A 'safety relay' is a dual-redundant safety device meant to shut down a machine even in the event of failures like

*

*An E-stop mushroom pushbutton switch 'NC' contact not opening.

*An E-stop relay 'NO' contact not opening.

After the shutdown the 'safety relay' is to prevent a machine restart till the fault is cleared.
For the purpose, the 'safety relay' has 2 relays monitoring each other and other machine E-stop mushroom pushbutton switches via hard-wired logic utilising the 'NO' & 'NC' of these devices.
Earlier this safety function was hardwired in machine controls (especially in cam-operated and hydraulic presses).
Later it became mandatory to incorporate exclusive stand-alone safety relay units, certified by international occupational safety and health monitoring agencies.


text:
Q: htc android 2.2 obtaining cellID wcdma its my first 'helloWorld' type app on android, and also in java so please be patient :)
I want to obtain cell ID in W-CDMA, so i make that app:
    package helloWorld.w;

//package com.eepyaj.cellID;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class w extends Activity {

   CdmaCellLocation location;
   int cellID, lac;
   private Context context;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      context = (Context) this;
      TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      location = (CdmaCellLocation) tm.getCellLocation();
      cellID = location.getBaseStationId();

      String tx;
      tx = String.valueOf(cellID);
      TextView tv = new TextView(this);
      tv.setText("Cell ID " + tx);
      setContentView(tv);

   }
}

Unfortunately application exits with message:
"Application helloWorld (process helloWorld.w) has stopped unexpectedly. Please try again" (both on HTC and on emulator)
I made that app under eclpise, typcial 'hello World' works (on htc and on emulator), so i think that problem is in obtaining that 'cellID'
thx in advance for any help

A: You can use CellIdentityWcdma:
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
for (CellInfo cellInfo : tm.getAllCellInfo()) {
    if (cellInfo instanceof CellInfoWcdma)
        cid = ((CellInfoWcdma) cellInfo).getCellIdentity().getCid();
}


text:
Q: react-router does not navigate to desired the route after an async operation I was working on a project when it turned out that when I dispatched an action and tried to navigate to the /home route after making an async call to my api and using the await keyword to wait for my response , it was not functioning.
I reproduce the problem in a simple react app codesandbox link
The issue with the following code is that it does not navigate to the home route when isLogged is true.
app.js
import "./styles.css";
import { useSelector } from "react-redux";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate
} from "react-router-dom";
import Home from "./component/Home";
import Login from "./component/Login";

export default function App() {
  const { isLogged } = useSelector((state) => state.auth);
  console.log("rendered");
  return (

      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/home" element={isLogged ? <Home /> : <Login />} />
          <Route path="*" element={<Navigate to="/" />} />
        </Routes>
      </Router>

  );
}

Login.jsx
import { useState } from "react";
import Forms from "./Forms";

const Login = () => {
  const [openform, setOpenForm] = useState(false);
  return (

      {openform && <Forms />}
      {!openform && (
        <button onClick={() => setOpenForm(!openform)}>
          click to open Form
        </button>
      )}

  );
};

export default Login;

Forms.jsx
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { setIsLogged } from "../store/authSlice";
const Forms = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  var goToHome = () => {
    dispatch(setIsLogged(true));
    navigate("/home");
  };
  const submit = () => {
    setTimeout(() => {
      console.log("finished");
      goToHome();//It works if I call the goToHome method straight without using the timeout.
    }, 2000);
  };
  return (
    <form action="">
      <input type="text" placeholder="enter your name" />
      <button onClick={submit}>click to login</button>
    </form>
  );
};

export default Forms;

A: The code is not preventing the default form action from occurring, resulting in the page reloading and the entire React app remounting. Consume the onSubmit event object and call preventDefault on it.
Example:
const Forms = () => {
  const dispatch = useDispatch();

  const navigate = useNavigate();

  const goToHome = () => {
    dispatch(setIsLogged(true));
    navigate("/home");
  };

  const submit = (e) => { // <-- consume onSubmit event object
    e.preventDefault();   // <-- prevent default form action

    setTimeout(() => {
      goToHome();
    }, 2000);
  };

  return (
    <form action="">
      <input type="text" placeholder="enter your name" />
      <button onClick={submit}>click to login</button>
    </form>
  );
};


text:
Q: При клике по иконке расширения для Opera не выполняется вывод текста в консоли Почему?
Содержимое файла manifest.json:
{
    "manifest_version": 2,
    "name": "name",
    "version": "1.0",
    "description": "description",

    "background": {
        "scripts": ["background.js"]
    },

    "permissions": ["tabs"],

    "browser_action": {
        "default_icon": {
            "16": "icon.png"
        }
    }
}

Содержимое файла background.js:
chrome.browserAction.onClicked.addListener(function() {
    console.log('text');
});

A: Вывод отображается в отладочной консоли, которую можно открыть на странице opera://extensions:


text:
Q: Getting the count of names with date in pdf The following code is used by me to generate a pdf inorder to display the number of customer registration with the date!
  <?php
    require_once("db.php"); //database connection php script

    require("fpdf/fpdf.php");

    $sql="Select count(Name) as Names,date from datetest";
    $result=mysqli_query($db,$sql);
    $pdf=new PDF();
    $pdf->AddPage();
    $pdf->AliasNbPages();
    $pdf->SetFont('Arial','B',12);

    while($row=mysqli_fetch_array($result))
    {
        $pdf-> Cell("",20," ".$row['Names'].$row['date'],1,10);
    }

    $pdf->output();
    ?>

The final result of this code yields only a single date and the total number of names! But i want to display the number of names of users registered on each day! How can i correct this?

A: Use this query:
Select count(Name) as Names,date from datetest GROUP BY date

A: You're looking for GROUP BY.  Use this query.
SELECT COUNT(*) Names, DATE(date) date FROM datetest GROUP BY DATE(date);

This will work if your date column has the DATE, DATETIME, or  TIMESTAMP data type.


text:
Q: Mass Mailing Tool Template using Google AppScript I am creating a Mass Mailing Template for me to modify and use when I need to send similar emails to many people. The information required are in the spreadsheet, however I have missing parts in the code.
This is the MMT Template
Missing parts I need help with:

*

*Add codes for Name of the Sender, Reply-To & BCC To

*I also want to track when an email was sent (date & time) & to whom (Recipient email) & what email was sent (Subject) in another tab in the same spreadsheet (Sent Email Log).

A: SUGGESTION
Using the Advanced parameters for the sendEmail method & appendRow, you can achieve your goal.
The edited script below will do the following:

*

*Get data from your MMT Template

*Identify the sender information (Name of the Sender, Reply To, BCC To)

*Read email data to be processed from row 12 onward on the MMT Template sheet

*Iterate on each row and send email based on the email recipient information

*On every email sent, an audit log gets appended on the Sent Email Log sheet.

Tweaked Script
function onOpen() {
  var ui = SpreadsheetApp.getUi(); // Or DocumentApp or FormApp.
  ui.createMenu('Mass Email')
    .addItem('Send Email', 'processTemplateData')
    .addToUi();
}

function processTemplateData() { // Get the sheet data from the MMT Template
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MMT Template");
  var data = sheet.getDataRange().getValues(); //get all data from the sheet
  var senderName = data[5][2];
  var replyTo = data[6][2];
  var bccTo = data[7][2];

  data.forEach((getEmailData, index) => { //Get every email data from row 12 onward
    index < 11 ? null : sendEmail(getEmailData, senderName, replyTo, bccTo) //Only process data from row 12 or index #11 from the array variable "data"
  });
}

function sendEmail(emailData, senderName, replyTo, bccTo) { //Send email
  MailApp.sendEmail({
    name: senderName,
    to: emailData[1],
    subject: emailData[2],
    htmlBody: emailData[3],
    bcc: bccTo,
    replyTo: replyTo
  });
  trackSentEmail(emailData[1],emailData[2]); //Track email that was send  Sent Email Log
}

function trackSentEmail(email,subject) { //Save send email info into the
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sent Email Log");
  sheet.appendRow([new Date,email,subject]); //Append the sent email on the Sent Email Log sheet
}

Demonstration

*

*Sample Sender Data from the MMT Template sheet.

*

*After pressing the Send Email custom menu on the spreadsheet, here is the email message received by the sample recipient

*

*The Sent Email Log sheet.

References

*

*sendEmail() Advanced Parameters

*appendRow()


text:
Q: MySQL CREATE FUNCTION fails on a shared webserver I have the following function. When I try to create it on a webserver, it fails with

You do not have the SUPER privilege and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)

I never had the same problem with any other webhosting (and the exact same function), how can I fix this? (I can't change MySQL settings).
CREATE FUNCTION `has_action_access`(in_role VARCHAR(255), in_request VARCHAR(255), in_action VARCHAR(255)) RETURNS tinyint(1)
    READS SQL DATA
    DETERMINISTIC
BEGIN

    DECLARE current_role VARCHAR(255);
    DECLARE found, cont TINYINT(1) DEFAULT 0;
    SET current_role = in_role;

    findattempt: REPEAT
        SELECT COUNT(*) FROM cyp_action_access WHERE request = in_request AND action = in_action AND role = current_role INTO found;

        IF found = 0 THEN
            SELECT COUNT(*) FROM cyp_roles WHERE name = current_role INTO cont;
            IF cont = 1 THEN
                SELECT inherits FROM cyp_roles WHERE name = current_role INTO current_role;
                END IF;
            END IF;
    UNTIL (cont = 0 OR found > 0) END REPEAT;
    RETURN found;
END;

*

*MySQL server's version is 5.0.90-log.

A: Your user does not have super privilege. You will need to contact your webhosting provider and have them update this. If they will not grant you that option ask them to execute the script for you.


text:
Q: Python: ImportError: attempted relative import with no known parent package En primer lugar quiero decir que aunque esta pregunta parezca ser un duplicado de esta otra
creo que no tratan lo mismo y creo que el problema de esa otra pregunta es diferente al mío. En cualquier caso creo que una explicación más para este tipo de error sería enriquecedor para la comunidad.

import sys
sys.path.append("../CREDENTIALS")
sys.path.append("./SDK")
import consts
import client
import account_api as account
import futures_api as future
import lever_api as lever
import spot_api as spot
import swap_api as swap
import index_api as index
import option_api as option
import system_api as system
import information_api as information
import json
import datetime
import TOKENS
Estos imports están al principio de miprograma.py.
Este es es mi mensaje de error:
PS C:\RUTADEMIPROYECTO\MIPROYECTO> python .\miprograma.py
Traceback (most recent call last):
File "C:\RUTADEMIPROYECTO\MIPROYECTO\miprograma.py", line 5, in
import client
File "./SDK\client.py", line 3, in
from . import consts as c, utils, exceptions
ImportError: attempted relative import with no known parent package

A: El problema es que los imports en un subdirectorio no son tan simples en Python como otros lenguajes. Hay múltiples formas de hacer esto, en tu caso debería funcionar algo así:
Crear un archivo __init__.py vacío en el subdirectorio SDK (veo que ya está)
Y los imports los harías de la siguiente forma:
...
from SDK import client
from SDK import account_api as account
...


text:
Q: JBoss/Alfresco cannot write on slave after failover
Possible Duplicate:
JBoss don't fail over MySQL slave using datasource

I'm trying to set up an high available MySQL "cluster", using a Master / Slave Replication configuration. I want to the slave become master (e.g. not read-only but writeable) if the first node come down (like in this question : https://stackoverflow.com/questions/9409111/database-fail-over-in-jboss-data-sources or in my previous question ).
But I am unable to specify to MySQL (or JBoss) to use slave in read-write mode.
The doc says : http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-configuration-properties.html

Failover Support
MySQL Connector/J has failover support. This enables the driver to fail over to any number of slave hosts and still perform read-only queries. Failover only happens when the connection is in an autoCommit(true) state, because failover cannot happen reliably when a transaction is in progress. Most application servers and connection pools set autoCommit to true at the end of every transaction/connection use.
The failover functionality has the following behavior:
  If the URL property autoReconnect is false: Failover only happens at connection initialization, and failback occurs when the driver determines that the first host has become available again.

  If the URL property autoReconnect is true: Failover happens when the driver determines that the connection has failed (checked before every query), and falls back to the first host when it determines that the host has become available again (after queriesBeforeRetryMaster queries have been issued).

In either case, whenever you are connected to a "failed-over" server, the connection is set to read-only state, so queries that attempt to modify data will throw exceptions (the query will never be processed by the MySQL server).

So, is there any way of failing over the slave in a WRITE mode ? In all threads I have read,  this sounds possible, particularly specifying
false
But it don't seems to work :(.
Any help appreciated.
Thanks.

Datasource configuration
<datasources>

    <local-tx-datasource>
        <jndi-name>alfresco-datasource</jndi-name>
        <connection-url>jdbc:mysql://10.1.2.13,10.1.2.14:3306/alfresco
        </connection-url>
        <driver-class>com.mysql.jdbc.Driver</driver-class>
        <user-name>alfresco</user-name>
        <password>alfresco</password>
        <exception-sorter-class-name>
            org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter
        </exception-sorter-class-name>

        <!-- Infique que le failover est accessible en ecriture -->
        <connection-property name="readOnly">false
        </connection-property>
        <failOverReadOnly>false</failOverReadOnly>
        <autoReconnect>true</autoReconnect>
        <check-valid-connection-sql>SELECT 1</check-valid-connection-sql>

        <metadata>
            <type-mapping>mySQL</type-mapping>
        </metadata>
    </local-tx-datasource>

</datasources>

MySQL Configuration
Here my MySQL configuration files (in case I forgot something) :
Master (10.1.2.13)
[mysqld]
user            = s-mysql
port            = 3306
basedir         =/app/mysql/current
datadir         =/app/data/mysql
log-error       =/app/log/mysql/master
log             =/app/log/mysql/query.log

#clustering
server_id       =1
log-bin         =/app/log/mysql/log-bin/log-bin.master
innodb_flush_log_at_trx_commit=1
sync_binlog     =1
skip-slave-start
expire_logs_days=10

binlog-do-db    =alfresco

Slave (10.1.2.14)
[mysqld]
user            = s-mysql
port            = 3306
basedir         =/app/mysql/current
datadir         =/app/data/mysql
log-error       =/app/log/mysql/slave
log             =/app/log/mysql/query.log

# Clustering
server_id       =2
log-bin         =/app/log/mysql/log-bin/log-bin.slave
expire_logs_days=10
skip-slave-start
relay-log-index =/app/log/mysql/log-relay/relay-log.slave.index
relay-log       =/app/log/mysql/log-relay/relay-log.slave

binlog-do-db    =alfresco
replicate-do-db =alfresco

Slave privileges
SHOW GRANTS for 'alfresco'@'10.1.2.11';
+-----------------------------------------------------------------------------------------------------------------+
| Grants for alfresco@10.1.2.11                                                                                |
+-----------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'alfresco'@'10.1.2.11' IDENTIFIED BY PASSWORD     '*F9F457310EF9364D42AABE6D8C24A21712C000B5' |
| GRANT ALL PRIVILEGES ON `alfresco`.* TO 'alfresco'@'10.1.2.11' WITH GRANT OPTION                                    |
+-----------------------------------------------------------------------------------------------------------------+

Tests and results
In order to test my configuration, I just stop the first instance :
service mysql stop

But I'm facing what I was fearing :
### Cause: java.sql.SQLException: Connection is read-only. Queries leading to data modification are not allowed
; SQL []; Connection is read-only. Queries leading to data modification are not allowed; nested exception is java.sql.SQLException: Connection is read-only. Queries leading to data modification are not allowed
    at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:107)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:71)
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:346)

Could someone give me hints, for solving this issue please ?


text:
Q: SqlDataReader isn't working, it skips the part where it checks the username I am working on a project that has 1 client and 1 server. I created also a Class library in which I put the code and than ad this class library as Reference at the Server and at the Client. And so I call methods from the Client by creating an object of the class.
And it is working very good... until now!
In the class library i have method called Check(), which checks if the Username already exist (when trying to register, and some other stuff. But the problem is the step in which it checks the username from the database is Skipped!! I don't know why, it doesn't show me an error why. The only error that comes up is the error that appears when trying to insert the same username into the database due to that skipped step.
Here is the Class library code:
    bool busy = false;
    bool empty = false;
    bool notSame = false;
    bool completed = false;

public void Check(string a1, string b2, string c3, string d4, string e5, string f6)
    {
        SqlConnection con = new SqlConnection(@"Data Source=TALY-PC;Initial Catalog=TicTacToe;Integrated Security=True");

        SqlCommand cmd = new SqlCommand("SELECT * FROM tblUsers", con);

        if (con.State.Equals(ConnectionState.Open))
        {
            return;
        }
        else
        {
            con.Open();
        }

        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {

            if (dr["Username"].ToString() == d4)
            {
                busy = true;
            }
            else if (a1 == "" || b2 == "" || c3 == "" || d4 == "" || e5 == "" || f6 == "")
            {

                empty = true;

            }
            else if (e5 != f6)
            {
                notSame = true;
                return;
            }
            else
            {
                dr.Close();
                SqlCommand cmd1 = new SqlCommand("INSERT INTO tblUsers (Name, LastName, email, Username, Password) VALUES ('" + a1 + "', '" + b2 + "', '" + c3 + "', '" + d4 + "', '" + e5 + "')", con);

                cmd1.ExecuteNonQuery();

                completed = true;
            }
        }

And the skipped part is this part:
if (dr["Username"].ToString() == d4)
            {
                busy = true;
            }

I don't know why it doesn't check this part??
Here is the code from the Client:
HttpChannel chan = new HttpChannel();

    Tic obj = (Tic)Activator.GetObject(typeof(Tic), "http://127.0.0.1:9050/MyMathServer");

private void RegisterForm_Load(object sender, EventArgs e)
    {
        ChannelServices.RegisterChannel(chan);
    }

 private void Button1_Click(object sender, EventArgs e)
   {
 obj.Check(textBoxX1.Text, textBoxX2.Text, textBoxX3.Text, textBoxX4.Text, textBoxX5.Text, textBoxX6.Text);
        label8.Text = obj.getUseri();
        if (obj.getBusy() == true)
        {
            MessageBox.Show("This username is already Taken, please choose another username");

            obj.setBusy();

        }
        else if (obj.getEmpty() == true)
        {
            MessageBox.Show("Please fill all the fields!");
            obj.setEmpty();
        }
        else if (obj.getNotSame() == true)
        {
            MessageBox.Show("Passwords don't match!!");
            textBoxX5.Text = "";
            textBoxX6.Text = "";
            obj.setNotSame();
        }
        else if (obj.getCompleted() == true)
        {
            MessageBox.Show("Registration was completed successfully. Please close the window and Log Int ");
            textBoxX1.Text = "";
            textBoxX2.Text = "";
            textBoxX3.Text = "";
            textBoxX4.Text = "";
            textBoxX5.Text = "";
            textBoxX6.Text = "";
            obj.setCompleted();

        }
  }

Can someone please tell me why isn't it checking the username?

A: I do not exactly understand your code. I can make some simple observations:

*

*First of all: use using of your connection and datareader. Whatever happens (exceptions, etc.), using will close them.

*Use better names for your variables. a1 till f6 mean nothing. Giving them meaningfull names makes it easier for us to read... so... If realy have no idea why e5 must be equal to f6.

*Same thing goes for your textboxes.

*The statement if (a1 == "" || b2 == "" || c3 == "" || d4 == "" || e5 == "" || f6 == """) is inside the while-loop, but since those values never change, your might consider moving them out of the loop.

*The same thing goes for the line if (e5 != f6).

*You check if the connection is open. But this connection has just been created. How can it be open? And if it would be open... it would simply return without doing anything?

*If you reach condition (e5 != f6) and the condition is true, your return. But you do so without closing the connection.

*If all parameters are "", but there are no records in the database, empty will not be set. Is this by design?

Try this code:
public enum Result
{
    Busy,
    Empty,
    NotSame,
    Completed
}

public Result Check(string name, string lastName, string eMail, string userName, string password1, string password2)
{
    // You should check with String.IsNullOrEmpty(...), not just an empty string.
    if (name == "" || lastName == "" || eMail == "" || userName == "" || password1 == "" || password2 == "")
        return Result.Empty;

    if (password1 != password2)
        return Result.NotSame;

    using(SqlConnection con = new SqlConnection(@"Data Source=TALY-PC;Initial Catalog=TicTacToe;Integrated Security=True"))
    {
        SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tblUsers WHERE UserName=@0", con);
        cmd.Parameters.AddWithValue("@0", userName);
        int count = (int)cmd.ExecuteScalar();
        if (count > 0)
            return Result.Busy;

        // I must admit, also the insert values should be done with SqlParameters.
        cmd = new SqlCommand("INSERT INTO tblUsers (Name, LastName, email, Username, Password) VALUES ('" + name + "', '" + lastName + "', '" + eMail + "', '" + userName + "', '" + password1 + "')", con);
        cmd.ExecuteNonQuery();
        return Result.Completed;
    }
}


text:
Q: Understanding an example in Israel Gohberg pg.54. Here is the example:

My questions are:
1-I did not understand the last two paragraphs, could anyone explain them for me, please? do they mean that the identity operator is unbounded in that kind of operators?
2-Does the last paragraph means that so the proof just before the two paragraphs is valid even if we do not have condition (1)?


text:
Q: How to run a mysqldump automated with SAFELY stored mysql credentials? I'm looking for a way to SAFELY run daily backups using mysqldump. Safely means not storing username/password in a text file or any other unencoded format.
I know there is (apparently it isn't) a way to safely run MySQL queries: storing the credentials in an ODBC datasource within the OS.
Is there a way to force mysqldump utility to use that predefined datasource?
I guess a PHP script with odbc_connect() won't do, because I can't pass the connection link to mysqldump.exe...
Or is there any other way to store username/password for use in an automated script?

I'm running Windows Server 2008 R2, MySQL 5.6

A: There is no such way. Passwords must be stored in cleartext or reversible encoded format - client must authorize itself somehow and mysql doesn't support any other methods (unlike pgsql for example, which can use practically anything with its utilities) - it wants password.


text:
Q: java android textViews aleatorios Hola Estoy escribiendo esto en android studio y estoy atascado aqui:
Tengo los siguientes 3 arreglos
String [] palabras = {"papa","mama", "casa", "mapa", "masa"};
String [][] silabasCorrectas= {{"pa","pa"},{"ma","ma"},{"ca","sa"},{"ma","pa"},{"ma","sa"}};
String[] silabas = {"pa","ma","ca","sa"};

Y por otro lado tengo un arreglo más con 4 TextViews.
Luego genero un número aleatorio (llamado carta actual) para seleccionar una palabra aleatoria (del primer array declarado ahí arriba) y su correspondiente array de silabas correctas (segundo array).
He colocado cada silaba correcta de esa palabra aleatoria en uno de esos TextViews de manera aleatoria.
Asi:
  //para cada silaba correcta
    for (int silaba_i=0; silaba_i < silabasCorrectas[cartaActual].length; silaba_i++){

        //escoger un text view aleatorio
        tv_Aleatorio = (int)(Math.random()*textViewCount);

        //si ese textview aleatorio se encuentra vacío:
        if (textView[tv_Aleatorio].getText().toString().equals("")){

           //colocar la silaba correcta en el textView
           textView[tv_Aleatorio].setText(silabasCorrectas[cartaActual][silaba_i]);
        }
        else {
            //volver a hacer lo mismo con la misma silaba correcta
            silaba_i--;
        }

    }

Hasta ahí, el programa funciona bien.
Luego quiero completar los Textviews faltantes con silabas "incorrectas"
Estoy intentando de la siguiente manera:
//para cada TextView[t]
    for (int k =0; k< textViewCount; k++) {

        //si el TextView está vacío:
        if (textView[k].getText().toString().equals("")) {

            int silabaAleatoria = (int) (Math.random() * silabas.length);

            do {
                //para cada silabaCorrecta[silaba_i]:
                for (int silaba_i = 0; silaba_i < silabasCorrectas[cartaActual].length; silaba_i++) {

                    //si la silaba correcta[silaba_i] es igual a silaba aleatoria:
                    if (silabasCorrectas[cartaActual][silaba_i].equals(silabas[silabaAleatoria])) {
                        sonIguales = true;
                    }
                }
            }
            while (!sonIguales);

            //Una vez que ya comparó la sílaba aleatoria con todas las silabas correctas

            //Si NO SON IGUALES
            if (!sonIguales){
                //guardar silaba aleatoria en textView[k]
                textView[k].setText(silabas[silabaAleatoria]);

            } else { //Si la sílaba aleatoria es igual a alguna de las silabas correctas
                k--;
            }
        }
    }

Agregando esa parte, la app directamente no muestra nada de nada. Ni siquiera muestra la parte gráfica con los TextViews vacíos o con errores.
¿Me podrían indicar el/los error/es que vean?
Lo único que conseguí hacer es rellenar los TextViews faltantes con sílabas aleatorias, pero se me desmadra cada vez que quiero comprobar si ésas sílabas aleatorias son correctas o no (yo quiero que no lo sean, porque a las correctas ya las coloqué).

A: No estoy 100% seguro, pero me parece que la condición de salida del ciclo do..while va a ocasionar que la variable sonIguales salga del ciclo con el valor "true" siempre.
En ese caso, la línea
        textView[k].setText(silabas[silabaAleatoria]);

nunca se va a ejecutar

A: Intenta ponerlo de esta forma. Ya que como ya comprobaste que el texview esta vacío solo deberías iterar la silaba. Ese k-- del else es muy raro
//para cada TextView[t]
    for (int k =0; k< textViewCount; k++) {

        //si el TextView está vacío:
        if (textView[k].getText().toString().equals("")) {

            do {
            int silabaAleatoria = (int) (Math.random() * silabas.length);

                //para cada silabaCorrecta[silaba_i]:
                for (int silaba_i = 0; silaba_i < silabasCorrectas[cartaActual].length; silaba_i++) {

                    //si la silaba correcta[silaba_i] es igual a silaba aleatoria:
                    if (silabasCorrectas[cartaActual][silaba_i].equals(silabas[silabaAleatoria])) {
                        sonIguales = true;
                    }
                }

                //Una vez que ya comparó la sílaba aleatoria con todas las silabas correctas

               //Si NO SON IGUALES
               if (!sonIguales){
                   //guardar silaba aleatoria en textView[k]
                   textView[k].setText(silabas[silabaAleatoria]);

               }
            }
            while (!sonIguales);
        }
    }


text:
Q: Swift mac os - Re-enable a segmented control cell I'm trying to create a UI in which the user can select/deselect multiple items.
I choose to use an segemented control to do such a thing and it's perfect for that use.
The behavior I want it to have is
1) an item must be set to disabled when clicked on
2) an item must be set to enabled when clicked on
I implemented step 1 but can't do step 2 as when the cell is set to disabled it won't send any event
Here's the code
    @IBOutlet weak var segBtnStrings: NSSegmentedControl!

    @IBAction func setStringState(sender: AnyObject) {
        var segment = sender.selectedSegment
        var enable = segBtnStrings.isEnabledForSegment(segment)

        segBtnStrings.setEnabled(!enable, forSegment: segment)
    }


text:
Q: Pass parameter to p:remoteCommand from JavaScript - not working? although this question has been asked multiple times, somehow the solutions suggested did not work for me.
therefore i try to ask again.
I'm using primefaces in version 6.2 and tested using primefaces extensions in 6.2.10
My current code is:
What i don't understand is how the remoteCommand and javaScript interact and sent the "result" (resultx) value to the bean methods...
i tried even other constelations, but everytime the log was null, whilist the java script printed always the expected result.
XHTML:
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:H="http://java.sun.com/jsf/html"
xmlns:pe="http://primefaces.org/ui/extensions"
>

<f:facet name="element">

    <h:outputText id="questName" value="#{el.questName}" style="display:block; margin-top:1em;"/>

</f:facet>

<pe:remoteCommand name="execAssignment" action="#{questChart.setResult}">
    <pe:methodSignature parameters="java.lang.String" />
    <pe:methodParam name="resultx" />
</pe:remoteCommand>

</ui:composition>

bean:
public void setResult() {
    FacesContext context = FacesContext.getCurrentInstance();
    Map<String, String> map = context.getExternalContext().getRequestParameterMap();
    log.info("done... : " + map.get("resultx"));
}

public void setResult2(String resultx) {

    log.info("done...2 : " + resultx);
}

LOG:
01:32:47.986 [http-nio-8080-exec-3] INFO  com.wolfo.beans.QuestChart - done... : null
01:32:48.047 [http-nio-8080-exec-6] INFO  com.wolfo.beans.QuestChart - done...2 : javax.faces.event.ActionEvent[source=org.primefaces.component.remotecommand.RemoteCommand@3b30fbb2]

browser console:
Quest Element 0

A: Okay. This was not so obvious, but I've managed to fix it.
Instead of using pe:remoteCommand action=""....  the change to actionListener="" gave the solution.
<pe:remoteCommand name="execAssignment" actionListener="#{questChart.setResult2}">
    <pe:methodSignature parameters="java.lang.String" />
    <pe:methodParam name="resultx" />
</pe:remoteCommand>

worked.
full answer:
xhtml part with panel:

<f:facet name="element">

<h:outputText id="questName" value="#{el.questName}" style="display:block; margin-top:1em;"/>

</f:facet>

<pe:remoteCommand name="execAssignment" actionListener="#{questChart.setResult2}">
<pe:methodSignature parameters="java.lang.String" />
<pe:methodParam name="resultx" />
</pe:remoteCommand>

bean:
public void setResult2(String resultx) {
 log.info("done...2 : " + resultx);
}


text:
Q: Upload file avoiding HTTP OPTIONS I have an OpenuI5 webapp with a backand developed with Delphi Datasnap technology.
I use Upload Collection component to manage a list of fields https://openui5.hana.ondemand.com/explored.html#/entity/sap.m.UploadCollection/properties
The component, when I want upload the file, send an Http OPTIONS call to retrieve a list of http methods callable from server.
The problem is that the Datasnap server does non handle http options and returns 501 error code http://docwiki.embarcadero.com/RADStudio/Seattle/en/DataSnap_REST
I'm trying to realize one of these solution:

*

*Send http POST by the component without send the http OPTIONS before

*Manage the http POST call by server Datasnap

*Send my docs with Base64 encoding using a POST but inhibiting the auto send OPTIONS call by the component

What is the solution?

A: There may be a bit confusion about what is actually happening here. UI5 is not explicitly behind the OPTIONS call that you're seeing, but your browser is. The browser is instructed to GET the $metadata from your server to introspect the OData service and see which entities and functions it supports. It seems that your OData server is not the same server as your web application, so the browser decides to run a pre-flight, to check if it is okay to execute this GET request.
The browser is executing this pre-flight as an OPTIONS request, and the server is then supposed to return a bunch of headers that indicate that the service call is allowed. Once the browser has receive the OK-sign from the server the actual GET call that UI5 asked the browser to make is being made.
The issue that you're running into has to do with CORS and is very common for web-apps that have their service running on a different server than the application. The most common solution is to proxy the service on the server that's running the web-app, so that it seem as if the service is running from the same server. In that case, the browser doesn't run this pre-flight CORS check.
Alternatively, you will have to support CORS calls being made, which means that you will have to support the OPTIONS method and have to return so-called CORS headers (Access-Control-Allow-Origin etc) from the server that's running the OData service.


text:
Q: Removing Item from API / Array in reactJS I am trying my best to remove an item from my array.
I have attempted to filter it as following:
removeContact(contact) {
this.setState({
   contacts: this.state.contacts.filter((_, i) => i !== contact)
 }); }

But that doesnt seem to do the trick.
My contact is listed in an unordered list like this:

        {this.state.contacts.map(((contact, index) =>
          <li className="list-group-item" key={`${contact.contact}${index}`}>
            {contact.name} | {contact.phone} | {contact.countryId} <button  onClick={this.removeContact}>Delete</button>

          ))
        }

But by clicking remove it just throws an error:
TypeError: Cannot read property 'setState' of undefined
The list to render the contacts from the api works.

A: removeContact = (index) => () => {
  this.setState({
    contacts: this.state.contacts.filter((_, i) => i !== index)
  });
}

I guess you want this. You have to inject index to use inside event listener.
<button onClick={this.removeContact(index)}>