text:
Q: Evaluate the integral without using the Residue Theorem Without using the Residue Theorem, evaluate $$\int _C\frac{ z\, \cos(z-1) \, dz}{z^4+z^2-20} $$
where $C$ is given by $x^2 + y^2 = 3$.  Assume that C has positive orientation.
I know that $C$ is a simple, closed contour and that the integrand is continuous and continuously differentiable everywhere except at $z=2,$ $z=-2$, $z=i{\sqrt 5}$, and $z=-i{\sqrt 5}$.
I don't think I can apply the Cauchy-Goursat Theorem here since the integrand is not continuous or continuously differentiable everywhere. Perhaps one of Cauchy's other integral formulas would work, but I'm not sure which one to use or how to apply it to this problem.
Any help or suggestions would be greatly appreciated. Thank you!
EDIT: After thinking about this problem more carefully, I realized that $z=i\sqrt 5$ and $z=-i\sqrt5$ lie outside of the contour $C$, so I don't think I need to worry about those.
As for $z=2$ and $z=-2$, I think I can use the Cauchy-Goursat Theorem to break the integral up into two separate line integrals along contours that form small circles around $z=2$ and $z=-2$ and then find these integrals' sum.
For $z=2$ along contour $C_1$, I have $$\int _{C_1}\frac{ z\, \cos(z-1) \, dz}{(z^2+5)(z+2)} $$ $$= (2\pi i) \frac{z\, \cos(z-1) \, dz}{(z^2+5)(z+2)}$$
Evaluating the above expression at $z=2$, we have:
$$= (2\pi i) \frac{(2)\,\cos((2)-1) \, dz}{(2^2+5)(2+2)}$$
$$=\frac{\pi i\, \cos(1)}{9}$$
For $z=-2$ along contour $C_2$, I have $$\int _{C_1}\frac{ z\, \cos(z-1) \, dz}{(z^2+5)(z-2)} $$ $$= (2\pi i) \frac{z\, \cos(z-1) \, dz}{(z^2+5)(z-2)}$$
Evaluating the above expression at $z=-2$, we have:
$$= (2\pi i) \frac{(-2)\,\cos((-2)-1) \, dz}{((-2)^2+5)(-2+2)}$$
$$=\frac{\pi i\, \cos(-3)}{9}$$
So, when we sum the two together, we obtain:
$$\frac{(\pi i)[ \cos(-3) + \cos(1)]}{9}$$
Is this right, or am I way off?


text:
Q: numerical values of the column of a matrix getting modified when converting into data.frame Running on R 2.13, I want to have a data.frame of several column, the first one being of numeric type, the others of character type. When I am creating my object, the values of the first column are getting transformed in a way that I don't expect or understand. Please see the code below.

tmp <- cbind(1:10,rep("aa",10))
tmp

  [,1] [,2]
[1,] "1"  "aa"
[2,] "2"  "aa"
[3,] "3"  "aa"
[4,] "4"  "aa"
[5,] "5"  "aa"
[6,] "6"  "aa"
[7,] "7"  "aa"
[8,] "8"  "aa"
[9,] "9"  "aa"
[10,] "10" "aa"

tmp <- data.frame(tmp)
tmp

   X1 X2
1   1 aa
2   2 aa
3   3 aa
4   4 aa
5   5 aa
6   6 aa
7   7 aa
8   8 aa
9   9 aa
10 10 aa

tmp[,1] <- as.numeric(tmp[,1])
tmp

   X1 X2
1   1 aa
2   3 aa
3   4 aa
4   5 aa
5   6 aa
6   7 aa
7   8 aa
8   9 aa
9  10 aa
10  2 aa

For some reason, the values of the first column are getting changed. I must be doing something obviously wrong here, can someone point me a workaround?

A: > tmp <- data.frame(cbind(1:10,rep("aa",10)))
> str(tmp)
'data.frame':   10 obs. of  2 variables:
 $ X1: Factor w/ 10 levels "1","10","2","3",..: 1 3 4 5 6 7 8 9 10 2
 $ X2: Factor w/ 1 level "aa": 1 1 1 1 1 1 1 1 1 1

As you can see above, tmp$X1 got converted into a factor, which is what's causing the behaviour you're seeing.
Try:
tmp[,1] <- as.numeric(as.character(tmp[,1]))

A: @aix's answer is a correct diagnosis.  However, probably what you want to do is to create a data frame directly:
data.frame(1:10,rep("aa",10))

Rather than cbinding first (which makes a matrix) and then converting to a data frame.
You might want to give your variables sensible names rather than the weird ones they will end up with via the data.frame command above (X1.10 and rep..aa...10.):
data.frame(var1=1:10,var2=rep("aa",10))

Since data.frame replicates its arguments, you can shorten this even a bit more:
data.frame(var1=1:10,var2="aa")

And if you really want a character vector rather than a factor for the second column, you can use stringsAsFactors=FALSE or wrap var2 in I() (i.e. var2=I("aa"))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Variants of Lipschitzness For $X$, $Y$ Banach spaces and an open $U \subseteq X$, say that a function $f : U\to Y$ is:

*

*uniformly Lipschitz in $U$ if
$$
  \sup_{\substack{\mathstrut x,y\in U \\ x\neq y}} \frac{\lVert f(y)-f(x)\rVert}{\lVert y-x\rVert} <\infty\,,
$$

*P-Lipschitz at $a\in U$ if
$$
  \limsup_{\substack{\mathstrut x,y\to a \\ x\neq y}} \frac{\lVert f(y)-f(x)\rVert}{\lVert y-x\rVert} <\infty\,\text{, and}
$$

*F-Lipschitz at $a\in U$ if
$$
  \limsup_{x\to a} \frac{\lVert f(x)-f(a)\rVert}{\lVert x-a \rVert} < \infty\,.
$$

The relationships among these seem to be like this: $f$ is

*

*Uniformly continuously differentiable in $U$ only if uniformly Lipschitz in $U$;

*Peano (= strictly, strongly) differentiable at $a$ only if P-Lipschitz at $a$;

*Fréchet differentiable at $a$ only if F-Lipschitz at $a$;

*P-Lipschitz at $a$ only if F-Lipschitz at $a$;

*F-Lipschitz at $a$ only if continuous at $a$;

*uniformly Lipschitz in $U$ only if P-Lipschitz at every point of $U$;

*P-Lipschitz at $a$ only if (and thus iff) uniformly Lipschitz in a neighbourhood of $a$;

*F-Lipschitz at every point of $U$ iff uniformly Lipschitz on every compact $K\subset U$;

*F-Lipschitz at every point of $U$ only if (and thus iff) P-Lipschitz at every point of $U$, provided $X$ is finite-dimensional, but not otherwise.

Are there conventional names, or references, for these three notions of Lipschitzness? Uniform Lipschitz is usually just Lipschitz, but locally Lipschitz seems to be used to refer both to F- and P-Lipschitz, probably because of the last point above in the finite-dimensional setting. Or am I missing some easy equivalence here?


text:
Q: What is the most efficient solution to paginate a JSP application without heavy coding? I'm looking for the easiest solution to create pagination for a JSP app without too much hassle. Is it even possible to create pagination on client-side with dynamic mysql content? Using JSP, I tried taglib which never worked... I found JSP pagination tutorials on opentutorials.com but... Nothing I could really wrap my head around quite easily... So far what I found over the web just don't quite work or other solutions like open tutorials are too bulky and required heavy coding... I'm looking for something light weight... I tried Displaytag but I do not want to use tables to display product listings. I prefer divs. I don't mind using javascript or jquery... I have no clue how to paginate my app... :/
I`m trying to paginate the category page below.

 ${selectedCategory.name}

                <c:forEach var="product" items="${categoryProducts}" varStatus="iter">

${product.name}

$${product.price}

<form id="wishlistForm" action="addToWishlist" method="post">
              <input name="productId" value="${product.id}" type="hidden">

              <input id="submit_list" class="submit" value="<fmt:message key='AddToWishlist'/>" type="submit">
            </form>

<form id="cartForm" action="addToCart" method="post">

              <input name="productId" value="${product.id}" type="hidden">
              <input id="submit_cart" class="submit" value="<fmt:message key='AddToCart'/>" type="submit">

                        </form>

              </c:forEach>

A: I don't see anything wrong with using tables if you are going to use them to show tabulated data and not to style your web up (using them to align, etc).
A very simple and useful library is DataTables: https://www.datatables.net/.
It supports AJAX querying, pagination, filtering you can set any style you want and it is simple to use.


text:
Q: Symfony 2 Doctrine find by ordered array of id I'm looking for a way to use Doctrine in Symfony 2 to find items using an ordered array of id.
I have a Card entity with id (primary key) and title.
I have a ListCards entity with id (primary key) and a listCards (an array of ids encoded : ["16", "2", "84"])
I first fetch the list and then I need to find cards with those ids in that order.
I try something like :
$idsArray = ["16", "2", "84"];
$cardRepository->findby($idsArray);

but Doctrine fetch my cards in ASC order.
ORDER BY FIEDS sql method doesn't seem to be supported by doctrine.
Is there any simple solution for that kind of sorting ?
Thank you (and sorry for my bad english).

A: You can use it like:
$cardRepository->findBy( array('id' => $idsArray), array('id' => 'DESC') );

Check also the official doctrine documentation for more details on how to use ordering, limit and offset as second to fourth parameters in the findBy method.

A: You can create a helper table, where you store ordered group elements, having the following data: (group_id, card_id, order)
You search by group_id, order by order and read the card_id.


text:
Q: Number of entries in DB PHP I am creating a function to show how many users are online now. This is based on who has opened a page within the last 5 min. Each page load is saved to my DB, below:

At the moment I have the following code
$query = mysql_query("SELECT user_id, timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
        $onlineUsers = mysql_num_rows($query);

This is simply totalling the number of rows, how can I do this so it only counts a user_id once? (so in the above database snippet it should be 2 not 5)

A: use DISTINCT keyword
 $query = mysql_query("SELECT DISTINCT(user_id), timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
$onlineUsers = mysql_num_rows($query);

A: You may use group by, e.g
SELECT user_id, timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute) group by user_id;

A: Since mysql_* is deprecated (php 5 onward) and removed in (php 7). So a mysqli_* example is here:-
<?php

error_reporting(E_ALL);
ini_set('display_errors',1);

$conn = mysqli_connect('localhost','username','password','db name');//change credentials here
$online_users = array();
if($conn){

    $query = mysqli_query($conn,"SELECT DISTINCT(user_id), timestamp,page FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");

    if($query){
        while($row = mysqli_fetch_assoc($query)){
            $online_users[] = $row;
        }
    }else{
        echo "query error:-".mysqli_error($conn);
    }
}else{
    echo "db connection error:-".mysqli_connect_error();
}

?>

        User Id
        timestamp>
        Page Visited

    <?php foreach($online_users as $online_user){?<

                <?php echo $online_user['user_id'];?>
                <?php echo $online_user['timestamp'];?>
                <?php echo $online_user['page'];?>

    <?php }?>

Note:-  If you want to show online user name also then you have to do JOIN query.
change table code accordingly.
It's a sample code. modify it accordingly.


text:
Q: Autoloader for Propel 1.5.6 doesn't seem to fully work I have installed Propel 1.5.6 onto my Mac, running PHP 5.12.14 via MacPorts. I've created a schema, generated a model, run the sql generation and insertion tasks, and am moving onto the runtime stuff now.
I've got the following code to work fine (it creates a row and then counts the number of rows):
<?php

// Set up some paths & schema info
$projectPath = realpath( dirname( __FILE__ ) . DIRECTORY_SEPARATOR . '..' );
$schemaName = 'database';
$modelPath = $projectPath . "/${schemaName}/build/classes";

// Init propel
require_once $projectPath . '/lib/propel-1.5/runtime/lib/Propel.php';
Propel::init($projectPath . "/${schemaName}/build/conf/${schemaName}-conf.php");

// Add the generated 'classes' directory to the include path
set_include_path($modelPath . PATH_SEPARATOR . get_include_path());

// This seems to be sufficient to get the autoloader working ***
require_once $modelPath . '/database/NodePeer.php';

$node = new Node();
$node->setName('My Node');
$node->setHash(sha1($node->getName()));
$node->save();

$nodes = NodePeer::doSelect(new Criteria());
echo 'Node count: ' . count($nodes) . "\n";
?>

However, if I remove the line with the starred comment, I would expect it still to work - I think the autoloader should kick in and load all the necessary model classes for me. However, I get this:

Fatal error: Undefined class constant
  'NAME' in
  (project)/database/build/classes/database/om/BaseNode.php
  on line 211

I've hacked the autoloader to echo the classes it loads, and found that it does indeed load some classes:

Autoload: Node
Autoload: BaseNode

However, when it loads BaseNode, it struggles on a static reference to the Peer class. I find that this is the case if BaseNode is manually required as well.

*

*Is PHP struggling on my configuration to autoload statically called methods/constants?

*Or could there be a problem to do with the order in which the Propel autoloader loads things?

For the time being, I'll carry on as I am - it is no major issue to include the peer - but I'd like to know if I can get away without it. One less thing to think about!

A: The autoloader wasn't working in this case because my model generated a class that clashed with an interface provided by the Propel core. Renaming this would have worked, as would using the namespace system (though of course the latter is dependent on using PHP 5.3.+).


text:
Q: Calculate distance between two lat+lng coordinates in React Native? I've got an object containing the lat and lng of my companys facilities. I've also got an object containing the lat and lng of the user's current location. What I'd like to do is iterate through the object with the location data of the sites, and calculate the closest one to the user's location. I'd like to get the kilometers between the two as well as the time it would take to drive the distance.
I've been looking at Google's Geometry API but can not figure out how to use this in React Native, if it's possible.
My question is what I should do to best achieve this? Can I somehow use the Google Geometry API?
Edit: I don't have to do this in the app, preferably I'd like to do so, but if it's not possible I could simply make a fetch to my PHP API if there is a better solution for PHP.

A: The npm package geolib https://github.com/manuelbieh/geolib has several methods that can help you do this; getDistance, findNearest, and orderByDistance.

A: calculateDistance(lattitude1, longittude1,lattitude2,longittude2)
{

const toRadian = n => (n * Math.PI) / 180

    let lat2 = lattitude2
    let lon2 = longittude2
    let lat1 = lattitude1
    let lon1 = longittude1

    console.log(lat1, lon1+"==="+lat2, lon2)
    let R = 6371  // km
    let x1 = lat2 - lat1
    let dLat = toRadian(x1)
    let x2 = lon2 - lon1
    let dLon = toRadian(x2)
    let a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(toRadian(lat1)) * Math.cos(toRadian(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
    let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
    let d = R * c
    console.log("distance==?",d)
    return d
      }

calculateDistance(25.3773009 68.3034496,25.3947972 68.3312881);

A: Try out this updated working code!
import {getDistance} from 'geolib';
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";

export default class Locations extends Component
{
    state = {
        destinationLat: 31.6200,
        destinationLong: 74.8765,
        distance:null,
        startLat:52.528308,
        startLong:1.3817765
    };
    async componentDidMount(){
        let location = await Location.getCurrentPositionAsync({
            enableHighAccuracy: true,
        });
        this.setState({
            startLat: location.coords.latitude,
            startLong: location.coords.longitude,
          });
        var dis = getDistance(
            {latitude: location.coords.latitude, longitude: location.coords.longitude},
            {latitude: this.state.destinationLat, longitude: this.state.destinationLong},
          );
          this.setState({
            distance: dis/1000,
          });
    };
    render(){
        return(
            <Text>{this.state.distance} KMs</Text>
        );
    }
}

A: This is an example of calculating the distance between two points, using ts
This is not 100% accurate, if you need a more accurate calculation please go and check here
If you need more calculation then you can use this lib

Note: I created these methods based on the lib and while searching, I
did not want to install the complete library because all I need is
distance calculation.

type UseDistanceTypes = {
  from: { latitude: number; longitude: number };
  to: { latitude: number; longitude: number };
};

const earthRadius = 6378137;
const toRadius = (value: number): number => (value * Math.PI) / 180;

export const useDistance = ({ from, to }: UseDistanceTypes): number => {
  const distance =
    Math.acos(
      Math.sin(toRadius(to.latitude)) * Math.sin(toRadius(from.latitude)) +
        Math.cos(toRadius(to.latitude)) * Math.cos(toRadius(from.latitude)) * Math.cos(toRadius(from.longitude) - toRadius(to.longitude)),
    ) * earthRadius;

  return Math.round(convertDistance(distance, 'km'));
};

// Convert to a different unit

const convertDistance = (meters: number, targetUnit: keyof typeof distanceConversion = 'm'): number => {
   return distanceConversion[targetUnit] * meters;
};

const distanceConversion = {
  m: 1,
  mi: 1 / 1609.344,
  km: 0.001,
  cm: 100,
  mm: 1000
};

You can put it inside a memo, but I do not see any benefits in my case because the lat and long props will always change.
I am using here just javascript (typescript) so it can be used in react too, btw i am using this method in my React native app.


text:
Q: DataReader does not return value? I wrote a program in C# where I wanted to get a value from a MySQL Database.
My code is:
MySqlCommand queryReqYear =
      new MySqlCommand(@"SELECT req_year FROM subjects_offered
                         WHERE subj_code= @subj", connectToDB.connection);

queryReqYear.Parameters.AddWithValue("@subj", viewStudents_subj.SelectedValue);

Then I use DataReader
MySqlDataReader reader;
reader = queryReqYear.ExecuteReader();

And then I try to get the value:
while (reader.Read())
    { MessageBox.Show(reader.GetString(0)); }

The field I'm trying to get has a value of 3. I'm trying to display that value but when I execute the event, nothing happens.
EDIT
Okay, I solved the problem by changing SelectedValue to SelectedItem

A: try Text property:
queryReqYear.Parameters.AddWithValue("@subj", viewStudents_subj.Text);

A: Try putting single quotes around blah in your sql statement.
MySqlCommand queryReqYear =
  new MySqlCommand(@"SELECT req_year FROM subjects_offered
                     WHERE subj_code= 'blah'", connectToDB.connection);

A: You don't get any exceptions, just not result?
You may want to test out putting this into a variable, then making a code break, something like:
string testValue = reader.GetString(0);
Console.WriteLine(testValue);

Also, you should test your SQL code in a SQL client to see if you get the proper results there.  I suspect your SQL is the problem, not the c# code.

A: Okay, I solved the problem by changing SelectedValue to SelectedItem


text:
Q: Como faço para abrir um link enviado por e-mail ao logar? Estou enviando um link para um usuário, só que como ele não está logado ele direciona para a pagina de login, só que quando ele coloca usuário e senha ele vai para a pagina principal do sistema php, como eu faço para que ao digitar o usuário e senha ele abre o link e não seja redirecionado para pagina principal?
Abaixo o código que valida o login
 <?php
$session_start();
$usuariot = $_POST['usuario'];
$senhat = $_POST['senha'];
include_once("conexao.php");
$result = $conn->query("SELECT * FROM proj_usuarios WHERE user_nome='$usuariot' AND user_senha='$senhat' LIMIT 1");
$resultado = mysqli_fetch_assoc($result);
if(empty($resultado)){
echo"<script language='javascript' type='text/javascript'>alert('Login e/ou senha incorretos');window.location.href='../login_giga.php';</script>";
die();
}else{
$_SESSION['usuarioID'] = $resultado['user_id'];
$_SESSION['usuarioNome'] = $resultado['user_nome'];
$_SESSION['usuarioSenha'] = $resultado['user_senha'];
$_SESSION['usuarioNivel'] = $resultado['user_nivel'];
$_SESSION['usuarionick'] = $resultado['nickname'];

if($_SESSION['usuarioNivel'] == 1){
header("Location:../paginas/layout/dashboard.php");
}}
?>

Obrigado


text:
Q: Hangfire: too many connections opened We are using Hangfire in production and turns out that we literally reach the database connections max limitation.
We have about 45 connections for just hangfire which seems a bit too much for just maintaining some long task running jobs.
I am wondering whether there is anything that can be done to change the number of connections, however, I can't find anything in the configuration providing such configuration.

A: You could try to reduce the number of workers as it is described here:
app.UseHangfire(config =>
{
    //tell hangfire to only use 2 workers
    config.UseServer(2);
});

A: Hangfire default takes 20 workers. You can override it on your startup. I used like below:
var options = new BackgroundJobServerOptions
            {
               WorkerCount=1    //Hangfire's default worker count is 20, which opens 20 connections simultaneously.
                                // For this we are overriding the default value.
            };

            app.UseHangfireServer(options);


text:
Q: Is ODE factorisation with split-quaternions possible? In Simple complex ODE's in matrix form? we discussed how we can solve certain complex ODE's in matrix form. As an example:
$$y(x)^2+y'(x)^2=0$$
can be factored as
$$(y(x)+ iy'(x))(y(x)-iy'(x))=0$$
and if we insist we could solve the two above equations by representing each term in a matrix form, i.e.
$$y(x)\equiv \begin{pmatrix}y_r(x)&-y_i(x)\\y_i(x)& y_r(x)\end{pmatrix}\\
y'(x)\equiv \begin{pmatrix}y'_r(x)&-y'_i(x)\\y'_i(x)& y'_r(x)\end{pmatrix}\\
i \equiv  \begin{pmatrix}0&-1\\1& 0\end{pmatrix}\\ $$
Multiplying the matrices out we get a system of coupled ODE's and the solution is found.
However, I was trying to apply this technique for a different problem:
$$y(x)^2+y'(x)^2-1=0$$
This expression cannot be factored as a product of two complex numbers (except the trivial factoring of 1). However, I tried to factor it over different types of numbers and in this post we discussed, that split-quaternions allow the following factorisation:
$$(y(x)+i y'(x)+j)(y(x)-i y'(x)-j)=0$$
Just like regular complex numbers allow a representation by 2x2 real matrices, split-quaternions can be written as 2x2 complex matrices. Wikipedia. The true solution is:
$${y(x) = c_1\sin(x)}\\
 {y(x) = c_2\cos(x)}$$
and what we get from the method I developed is the following
$$y(x)= c_1 \cos(x)-c_2 \sin(x)+\\(c_1 \sin(x)+c_2 \cos(x))i+ \\(c_4 \sin(x)+c_3 \cos(x)-1)j+ \\(c_4 \cos(x)-c_3 \sin(x))k$$
So that $\mathcal{R}\{y(x)\}=c_1 \cos(x)-c_2 \sin(x)$ and the results agree.
My question is: when can I use this technique? Is it legitimate or is it just a lucky coincidence?


text:
Q: Confused over wp-config.php and 'database user + database password + name' I have a domain with a subdomain.
Each of those has a different install of WordPress.
When I created the databases I made the following:
Main Domain = database called: maindomain
Sub Domain = database called: subdomain
I applied the SAME database username to both databases....
So all nice and simple....
However, why is the Database Password the same?
/** MySQL database password */
define('DB_PASSWORD', 'passwordhere');

When I reset the password for the database username (which I had forgotten) it made my main domain crash?
So I guess my question is - have I just merged two databases together? Is that even possible?
Hope thats clear!

A: The password belongs to the user, not the database. You have multiple databases, but just one user.
You can also have multiple installs share the same database, you just need a unique $table_prefix for each install.

A: The credentials you enter in your wp-config files are the credentials you need to require to access WordPress database. Wordpress need 4 things to check the tables that are made for any particular WordPress installation.
1. DB name
2. DB Username
3. DB Password.
4 DB Prefix.
Here in the above table the username and passwords are the database user and database prefix is the unique prefix that is attached to all the tables in WordPress installation. I hope this clears your query.

A:
I applied the SAME database username to both databases
Why is the Database password the same?
When I reset the password for the database username it made my main domain crash?

It sounds like you created a single MySQL user which is allowed to access both maindomain and subdomain databases. When you change the MySQL user password, you need to update the password in any wp-config.php files where that user is set.

Have I just merged two databases together? Is that even possible?

Based on your description, it sounds like you just need to update the password in the wp-config.php on your maindomain site. It is possible to make your maindomain and subdomain sites point to the same database but you would do that by setting the DB_NAME define and $table_prefix variable exactly the same.


text:
Q: Browserlink error on Chrome with VS2017 .NET Core App Web Essentials 2017 is already installed as part of Visual Studio 2017, but when I run an ASP.NET Core app in the Chrome Dev Tools console window I get the following error message

"Browser Link: Failed to invoke return value callback: TypeError:
  Cannot read property 'files' of null"

On the same console window, I also see the following error message related to Browserlink:

Synchronous XMLHttpRequest on the main thread is deprecated because of
  its detrimental effects to the end user's experience. For more help,
  check https://xhr.spec.whatwg.org/.

Second question, I've noticed with Chrome, making CSS changes in my solution and just refreshing the page doesn't change the CSS on the browser -  I have to close out of Chrome and re-run. Is this normal? Looks like CSS changes also don't always reflect the code on each re-run unless I browse with an Incognito Chrome Browser. Could be a caching issue.


text:
Q: What is the difference between various MSBuild version properties, such as Version, VersionPrefix, and VersionSuffix? Building projects with MSBuild 15 and Microsoft.NET.Sdk allows users to specify half a dozen version properties. What is the difference between each of these and what is the right way to use them?

*

*Version

*VersionPrefix

*VersionSuffix

*AssemblyVersion

*FileVersion

*PackageVersion

And to be clear, I'm talking about "properties" as MSBuild properties that are defined in the file (as below)
<PropertyGroup>
   <Version>1.2.0</Version>
</PropertyGroup>

...or on command line as msbuild.exe /p:Version=1.2.0

A: Also, setting these values explicitly will override the defaults.
VersionPrefix
Format: major.minor.patch
Examples: 14.2.4, 0.1.0, 99.99.99
Meaning: The normal part of the semver version number. This is used to determine the beginning of the Version value.
Default: "1.0.0"
VersionSuffix
Format: [0-9A-Za-z-.]* (arbitrary string)
Examples: alpha, beta, build0123, rc4-build201701, rc.1, rc-1
Meaning: The pre-release label of the version number. Used to determine the ending of a Version value.
Default: (empty)
Version
Format: major.minor.patch[-prerelease]
Examples: 5.3.9-beta, 0.0.1-alpha-01, 0.0.1-alpha.1, 2.0.0
Meaning: This property is the most commonly used property in user projects. Other version properties look to this value as a default. It is also used to generate the value of System.Reflection.AssemblyInformationalVersionAttribute. The preprelease value is optional.
Default: VersionPrefix if VersionSuffix is empty. VersionPrefix-VersionSuffix if VersionSuffix is not empty.
Note: setting Version explicitly will override any VersionPrefix or VersionSuffix settings.
Also, this typically follows SemVer rules. See http://semver.org/ for details
PackageVersion
Format: major.minor.patch[-prerelease]
Meaning: Used to generate the package version when producing a NuGet package from an MSBuild project.
Default: matches Version
AssemblyVersion
Format: major.minor.patch.revision
Examples: 4.5.6.2, 1.0.0.0
Meaning: Used to generate the value of System.Reflection.AssemblyVersionAttribute. The compiler uses this to determine the final AssemblyVersion value, an essential part of assembly identity. See https://msdn.microsoft.com/en-us/library/51ket42z(v=vs.110).aspx#Anchor_0
Default: matches Version without the prerelease label.
FileVersion
Format major.minor.patch.buildnumber
Examples: 1.0.0.43952, 0.1.0.0
Meaning: Used to generate the value of System.Reflection.AssemblyFileVersionAttribute. This is not required to match AssemblyVersion. It is common to add a build number to this version.
Default: matches AssemblyVersion
InformationalVersion
Format: any
Meaning: Used to generate the value of System.Reflection.AssemblyInformationalVersionAttribute. This attribute can contain any additional version information.
Default: matches Version

A: I would like to expand on the answer which was already given above to Visual Studio.  If you got here because you were wondering how this all works in Visual Studio 2022 (and earlier), this is a short explanation as I could not find any official docs on the matter.
If you create a .net core Console app, and go to Project Properties, you will see a section "Package --> General" that covers versioning.  It is populated with default values which are shown beneath each element.
Here is a screenshot of one of the elements with it's default value.  So what is "$(VersionPrefix)"?  As discussed above, it is one of the properties that can be set. But note there is no place in the UI to set this, but you can set it directly in the project file by editing it.

So let's do that now:

After saving the file, you now see the following:

But that's not really very useful for a version number.  So lets add a Suffix to the project file.
<VersionSuffix>5-beta</VersionSuffix>
But now the version looks like this:

But that's not really what we want, so lets add a version number to the center:

And this give us this in the file explorer:

So, to recap:  The UI is just writing to the Project File.  No magic there.  But how does it get consumed from the project file?  Well, actually, there is a  file being created in the background called .AssemblyInfo.cs. It looks like this:
[assembly: System.Reflection.AssemblyCompanyAttribute("ConsoleApp2")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("2.3.5.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("2.3.5-beta")]
[assembly: System.Reflection.AssemblyProductAttribute("ConsoleApp2")]
[assembly: System.Reflection.AssemblyTitleAttribute("ConsoleApp2")]
[assembly: System.Reflection.AssemblyVersionAttribute("2.3.5.0")]

And that file is being consumed by the compiler when the project is compiled.
If you wanted to, you could skip all of the UI and project files, and just create the AssemblyInfoFile directly. But when you do that, you lose the VersionPrefix and VersionSuffix functionality and you have to do it manually.


text:
Q: using $_POST with foreach loop i'm trying to create a form to insert students marks in a college .. i have a list with all students id's and a form with marks .. this is my form :
<input type="hidden" name="id[]" value="{$student.id}" />
<input type="text" name="mark[]" size="5" />

of course the field is repeated in the form , but the problem is when i'm trying to print the results , this is my code
foreach ($_POST as $student){
            echo $student['id'].$student['mark'];
        }

but i get this when i submit the form :
Undefined index: id
Undefined index: mark
What's the problem with my code, PLZ ?

A: If $student.id is unique perhaps you should consider something like:
<input type="text" name="mark[{$student.id}]" size="5" />

This will give you a result in the php side similar to
Array
(
    [mark] => Array
        (
            [studentID1] => 14
            [studentID2] => 60
            [studentID3] => 89
        )

)

Therefore in the php you can do this:
foreach($_POST['mark'] as $studentID => $mark){
    echo "The student". $studentID ." achieved mark: ". $mark;
}

A: foreach ($_POST['id'] as $key => $studentId){
    echo $student['id'][$key].$student['mark'][$key];
}

You are working on a Array when you are declaring name="id[]".
If you have two name"id[]" on form before post, it will be posted as:
array(
    'id' => array(
         '0' => '',
         '1' => '',
     );
);

Then you should use
foreach ($array['id'] as $key => $value) {
    echo $array['id'][$key]; //got value
    echo $array['name'][$key]; //got custom value
}

A: Given you form you want something like this:
foreach ($_POST['id'] as $key => $id){
     echo $id. $_POST['mark'][$key];
}


text:
Q: How can I download a file using JQuery Ajax and custom headers? I am using Laravel Excel to Generate and download files. This is my code on the back end:
        $userExports = new UsersExport($filters);
        return $userExports->download();

I can download the file using postman but I am facing issues with jquery because I cannot make the browser start the download to the user.
This is my jquery code:
    url = Settings.AppSettings.Api + "users/export" + queryString;

    var settings = {
      "async": true,
      "url": url,
      "method": "GET",
      "headers": {
        "Authorization": "Bearer " + Session.AuthKey ,
        "cache-control": "no-cache",
      },
      "processData": false,
    }

    $.ajax(settings).done(function (response) {

        // I don't know what to code here.

    }).fail(function (response) {
        $(".Preloader").fadeOut();
        Materialize.toast(response.responseJSON.message, 3000);
        if (response.responseJSON.code == 401) {
            Session.Logout();
        }
    });

This is part of the response or file I am getting
PK �yOG�D�X�[Content_Types].xml��MN�0���"�%nY ��vAa   �(0����ؖg�w{&i�@�nbE�{��y��d۸l m�����X�(���)���F��;@1_�����c)j�x/%��E��y� �QĿi!��K�y3�J<���Z1�0?Y�L%zV c��Ib7�����a/l٥P1:�q�r��j��j0A����u�""���(� ���W�M��)Tj�({ܲ�>�O��,X٭���>B��~׭���Ӥ6�J=�oBZ����t��X4���Cg�,���QgmrL�ٯc�e��t��    Z�?����hPv��±��u�j���R������}�Cv��PK �yO�78�K_rels/.rels���j�0��{ �{���1F�^ʠ�2��l�$���-}

A: This is what you need ,
$.ajax(settings).done(function (response) {
    var url = window.URL.createObjectURL(new Blob([response.data]));
    var link = document.createElement('a');
    var filename = "YourFileName.xls";
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();

})

Note : In your ajax setting add response data type as

dataType : 'blob',

A: Mainly, what it worked was add
"xhrFields":{
    responseType: 'blob'
},
I think the problem was that JQuery seems to have TEXT as a default response Type.
    url = Settings.AppSettings.Api + "users/export" + queryString;

    var settings = {
        "async": true,
        "url": url,
        "method": "GET",
        "headers": {
            "Authorization": "Bearer " + Session.AuthKey ,
            "cache-control": "no-cache",
        },
        "processData": false,
        "xhrFields":{
            responseType: 'blob'
        },
    }

    $.ajax(settings).done(function (data, textStatus, jqXHR) {

        var url = window.URL.createObjectURL(data);
        var link = document.createElement('a');
        var filename = "Usuarios.xlsx";
        link.href = url;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();

    });


text:
Q: How can I do Dependency Injection without "new'ing" a class instance and providing the parameters myself? I have a client that is created from an OpenApi definition that is generated using NSwagStudio.  The code that is generated has an interface and a class.  It takes an HttpClient in the constructor.  I set this up for the DI engine like this.
services.AddScoped<IConsumerAdapterClient, ConsumerAdapterClient>(sp =>
{
    var httpClientFactory = sp.GetRequiredService<IHttpClientFactory>();
    var baseUrl = Configuration.GetSection("ConsumerAdapterConfig:EndpointBase").Value;
    return new ConsumerAdapterClient(baseUrl,httpClientFactory.CreateClient());
});

But this doesn't seem quite right to me.  After doing some searching, I found this article.  Now that same code looks like this.
services.AddHttpClient<IConsumerAdapterClient, ConsumerAdapterClient>(client =>
{
    var baseUrl = Configuration.GetSection("ConsumerAdapterConfig:EndpointBase").Value;
    client.BaseAddress = new Uri(baseUrl);
});

Ok, that's better.  But now I have to add security to the mix.  To do that, I have a class called ClientCredentialProvider which does the work of getting an access token using client credential flow.  I didn't want to modify the generated code (that's just asking for maintenance problems) so instead, I can take advantage of the fact that NSwagStudio generates classes as a partial class.  This means I can create a new constructor and inject the security element into the class where I can then use it in the prepare method hooks.
public partial class ConsumerAdapterClient
{
    private readonly IClientCredentialProvider _clientCredentialProvider;

    public ConsumerAdapterClient(HttpClient httpClient, IClientCredentialProvider clientCredentialProvider)
    {
        _httpClient = httpClient;
        _clientCredentialProvider = clientCredentialProvider;
        _settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(CreateSerializerSettings);
    }

    protected async Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, StringBuilder url)
    {
        await PrepareRequestAsync(client, request, url.ToString());
    }

    protected async Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, string url)
    {
        if (_clientCredentialProvider != null)
        {
            var accessToken = await _clientCredentialProvider.GetAccessToken();
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        }
    }

#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
    protected async Task ProcessResponseAsync(HttpClient client, HttpResponseMessage response, CancellationToken cancellationToken)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
    {
        // nothing to do here.
    }
}

That created a new problem in that it now complains about multiple constructors and it doesn't know which one to pick.  After deleting the constructor from the generated code, it worked as expected.
So there were three problems here.

*

*One was I had to remove the constructor from the generated code.  This will create a maintenance issue but it's not a horrible one and trying to run a test will quickly reveal it.

*Second, because I had to remove the constructor from the generated code, I had to move the initialization for _settings and copy it to the constructor in the partial class.  That's a one-time thing so I can live with it.

*The third is that I did this using a partial class.  While that in and of itself is not a big deal, I have a lot of these client classes and would need to create the same thing over and over for each one.
So how can I achieve implementing this class without creating boilerplate code over and over again?
I took the partial class and turned it into a base class.  I then told NSwagStudio about my base class so when the code got generated it would use the base class.  The only problem I had now was that I couldn't overload the constructer.  Now instead of injecting the ClientCredentialProvider, I was back to doing things the way I started but setting a property for the ClientCredentialProvider.
public class ClientServicesBase
{
    private IClientCredentialProvider _clientCredentialProvider;

    public IClientCredentialProvider ClientCredentialProvider
    {
        set => _clientCredentialProvider = value;
    }
// The rest of the code is the same as above.
}

So to set it up, it looks like this.
services.AddScoped<IConsumerAdapterClient, ConsumerAdapterClient>(sp =>
{
    var httpClientFactory = sp.GetRequiredService<IHttpClientFactory>();
    var clientCredentialProvider = sp.GetRequiredService<IClientCredentialProvider>();
    var baseUrl = Configuration.GetSection("ConsumerAdapterConfig:EndpointBase").Value;
    return new ConsumerAdapterClient(baseUrl,httpClientFactory.CreateClient())
    {
        ClientCredentialProvider = clientCredentialProvider
    };
});

So this works and it does what I want it to do but it's not done in a way that represents Microsoft's recommended solution.
How do I:
Add the security element using the DI engine without having to extract the parameters from the service container and new'ing up a new instance of the class?

A: Based on Jeremy's comment on my question, I created a new class that I derive from the generated one.  It doesn't add any new functionality but it does add a constructor with strongly typed parameters.  I still use the base class that handles the security part for me but now I use the DI engine in a way that is recommended by Microsoft.
public class ConsumerAdapterClientExtension : ConsumerAdapterClient, IConsumerAdapterClient
{
    public ConsumerAdapterClientExtension(HttpClient httpClient, IClientCredentialProvider clientCredentialProvider) : base(httpClient)
    {
        ClientCredentialProvider = clientCredentialProvider;
    }
}

Then when I wire it up in the start-up class, it looks like this.
services.AddHttpClient<IConsumerAdapterClient, ConsumerAdapterClientExtension>(client =>
{
    var baseUrl = Configuration.GetSection("ConsumerAdapterConfig:EndpointBase").Value;
    client.BaseAddress = new Uri(baseUrl);
});


text:
Q: Function Triggers Incorrectly Essentially, I am trying to develop a makeshift BlackJack game while learning C++. I have declared an array that holds my card values, but I have a value, that will hold two at one time. Whenever I run the application I notice it runs my Ace() function first, but I do not want it to do that. I want it to ask when the the random generator picks the Ace() function.
int main()
{
random_device rd;
mt19937 eng(rd());
uniform_int_distribution<> distr(0, 11);

int x = 12;
int K = 10;
int Q = 10;
int J = 10;
int Ace();

int dealer = rand() % 11 + 1;
std::vector<int> Cards = { Ace(),K,Q,J,10,9,8,7,6,5,4,3,2 };
int value;

do {
    std::vector<int> dh = { };
    do
    {
        int i = dh.size();
        dh.insert(dh.begin() + (i), Cards[distr(eng)]);

    } while (dh.size() < 2); {

        if (dh[0] + dh[1] < 21)
        {
            int ph = dh[0] + dh[1];
            string input;
            cout << dh[0] << "," << dh[1] << "\n";
            cout << "Your total is " << ph << "\n" << "Do you want to hit or stay? ";
            cin >> input;

        }
        else
        {

        }

    }

} while (Cards[distr(eng)] < 1000);
{
    puts("STOP!");
    return 0;
}

}
int Ace() {
  int x;
  cout << "You drew an Ace! " << "\n" << "Do you want to make it 11 or 1?";
  cin >> x;
  return x;
}


text:
Q: How do I resolve "git pull" merge conflicts onto one of my previous commits? This is what my git tree looks like:
A   B   C   D   E
o---o---o---o---o master
         \
          o---o---o---o my_branch
          C1  C2  C3  C4

I am trying to rebase my_branch with master, and for my tree to look like this in the end, however, I have merge conflicts, which I want to be resolved as part of my commit C2 (or earlier commit) instead of top of head (C4).
A   B   C   D   E
o---o---o---o---o master
                 \
                  o---o---o---o my_branch
                  C1  C2* C3  C4
                       |
                      includes merge conflict resolution with master

Tried: Git rebase & resolve conflict + commit
git pull --rebase master This causes merge conflict.
I can resolve the conflict and do git commit, but, I do not wish to create a new commit, C5. I would rather the conflict changes be made as part of an older commit, say, C2.
Alternatively, I tried git rebase to C2 followed by git pull
git rebase -i C1 Mark C2 as "edit". I hoped to do git pull --rebase master on this, and resolve conflicts + commit + git rebase --continue so the conflict resolution becomes part of C2, but this did not work.
Can you suggest a way I can do this? Anything short of reverting my changes and re-applying them after git rebase?

A: You're already replacing all of your commits
Commit C1 says that its parent commit is C.  You need a new and different commit—you might call it E1, for instance—that says that its parent is E.
This new and different commit will have a new and different hash ID.  In the end, though, you'll still have four commits—they will just be E1 through E4.  Your name my_branch will identify new commit E4; commit C4 will be forgotten, and will eventually go away, unless someone or something else has hold of it and won't let go:
                  E1  E2  E3  E4
                  o---o---o---o   <-- my_branch
A   B   C   D   E/
o---o---o---o---o   <-- master
         \
          o---o---o---o   [abandoned]
          C1  C2  C3  C4

When git rebase hits a conflict, it stops in the middle of the rebase
Rebase works by copying each commit, one at a time, turning the snapshot in C1 into a change-set against commit C—its parent—and applying that change-set to commit E.  Git does this using Git's internal merge engine, i.e., Git also compares C vs E to determine how to apply C vs C1.
In this case, that comparison and copy went well, and Git built commit E1 successfully.  Then Git went on to attempt to build E2 by comparing C2 to C1, to turn it into a change-set, then merging that with the changes from C1 to E1.  This is where the conflict occurred.  So at this point, you have:
                  E1
                  o   <-- HEAD
A   B   C   D   E/
o---o---o---o---o   <-- master
         \
          o---o---o---o   <-- my_branch
          C1  C2  C3  C4

Commit E2 is in progress, but does not exist yet.  You must resolve the conflict, git add the resolved files, and run git rebase --continue to cause Git to make new commit E2:
                  E1  E2
                  o---o   <-- HEAD
A   B   C   D   E/
o---o---o---o---o   <-- master
         \
          o---o---o---o   <-- my_branch
          C1  C2  C3  C4

At this point Git will be able to attempt to copy C3.  If that goes well, Git will make E3 on its own.  Otherwise it will stop to get your help again, and you go through the same process and eventually use git rebase --continue to make Git go on to copy C4 to E4.
Once E4 is successfully made, there are no copies left to perform, and git rebase does its last trick: it moves the name my_branch so that it points to E4 instead of C4, re-attaching the special name HEAD to the name my_branch.


text:
Q: Sharing SSL Certificate I want to buy a wildcard SSL certificate to be used by multiple web servers. Is this possible? If so, what is the configuration?
DNS design for [www/nas].example.com:
A Record   | @   | Shared Web Host
A Record   | www | Shared Web Host
DNS Record | nas | Local NAS Server
1. Is it possible for two external servers to share separate sub-domains (i.e. nas.example.com for my NAS Server and *.example.com for my Shared Web Host)?
2. SSL providers give me a CA bundle. Do I install this CA to both servers?
3. Will Whoisguard protect both servers?

A:

*

*Is it possible for two external servers to share separate sub-domain...

There is no technical reason against installing the same certificate on multiple systems if the domains on the system are covered by the certificate. There might be usage restrictions by the CA which you need to check. And since all systems with the same certificate need to use the same private key the change of compromising the key gets larger.

*SSL providers give me a CA bundle. Do I install this CA to both servers?

Of course.

*

*Will Whoisguard protect both servers?

Whoisguard is about hiding the real owner of a domain from the publicly accessible whois information and has nothing to do with SSL certificates or on how many servers you use the domain.


text: Q: How would one disable the creation of multiple users on Ubuntu 17.10? I am currently using Ubuntu 17.10 and I am looking for a way to disable the ability to create any more users on my system. I have several people who use this computer, but I would like for them to only use this "user". Is there any way to do this?


text:
Q: AngularJs center and resize icon I try to create a grid menu and it looks like below.
My Problem is, that I dont know how to resize the icons, so that they fit, with AngularJs, not with jQuery!
Also I dont know how I can center the icons.
Thanks for your help :)

menu.html
<ion-content id="my_page">

</ion-content>

css
.my_container{
    position: absolute;
    top:0;
    right:0;
    left:0;
    bottom:0;
}

.my_row{
    height:49.95%;
    left:0;
    right:0;
    background-color:#ffffff;
    clear:both;
}

.my_item{
    height:100%;
    width:49.95%;
    background-color:#c0b5b5;
    border: 1px solid #ffffff;
    float: left;
    vertical-align: middle;  //dont work :(
    text-align: center;
}

i.menu_icon {
   font-size: xx-large; //Here i want it to fit, not a final size, but   dynamicly
}

A: Try giving:
i.menu_icon {
   font-size: 250%;
}

Here the 250% is relative to the em size and not the height of the parent container. To make them vertically centered, you need to use:
i.menu_icon {
  font-size: 250%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

And finally don't forget to give the parent, position: relative:
.my_row {
  height:49.95%;
  left:0;
  right:0;
  background-color:#ffffff;
  clear:both;
  position: relative;
}

A: Are you sure you need angular code for this? I think its better to use css instead.
To resize your icons you can use width and height properties for example, or do it with padding. To align your icons you can also use paddings, or margins. Another way is to set position: relative to icon and get it appropriate top value


text:
Q: Subtypes of Arrays If I have class A { and class B extends A { will
B[] b = new B[1];
b[0] = new B();
System.out.println(b instanceof A[]);

print out true or false?

A: The JLS states that if B is assignable to A, then yes, B[] is assignable to A[].
This opens the door to serious implications though, demonstrated by this code:
class A {}
class B extends A {}
class C extends A {}

//...
B[] bs = new B[2];
A[] as = bs;
as[0] = new C(); //runtime error
B b = bs[0];

This code compiles but fails at runtime.  We call that a lack of type safety.

A: // A.java
public class A {}

// B.java
public class B extends A {}

// Test.java
public class Test {
    public static void main(String[] args) {
        B[] b = new B[1];
        b[0] = new B();
        System.out.println(b instanceof A[]);
    }
}

When run:
> javac *.java && java Test
true

A: It will print true.

A: false.
Arrays don't follow the same rules as normal Objects.


text:
Q: jQuery slider with hover navigation and pause - not using plugin In my later days of writing jQuery as raw as possible, and not having loads of jQuery plugins stacking up and slowing my page down - I'm trying to create my own slider.
I have created a fiddle of how far I have got so far.
My HTML markup is not dynamic - and the slide animate process is positional only.

The complications I'm having is the animations have to fully run before the next animation can begin which makes my animations begin to queue up if you hover the menu lots.
I need an animation to stop half way though if the hover changes, and automatically run to the next animate position. Hope this makes sense, you will see what I mean in the fiddle.
Also, I want the animation to automatically run through each slide and 2000ms - and if the slide itself is hovered, I would like it to pause.
I know I'm pretty much asking for someone to write me a custom slider script, but it would so helpful and intuitive to see how a raw one is written with out a plugin.
I need my slider to be lightweight, hence not generating extra markup. Like all the plugins I've tried just are to heavy and too much. I like plain jquery.

Any help would be sooo appreciated. Thanks

Please see my miniature fiddle example using the latest jQuery.
http://jsfiddle.net/EYDtF/

A: Sloppy but may help get you get started
var banners = $('.banner-slides'),
controls = $('.banner-menu'),
cycle = true,
current = 0;

doCycle();

controls.find('li').hover(function() {

    controls.children().removeClass('hover');
    $(this).addClass('hover');

    animate($(this).index());

    cycle = false;
}, function() {

    cycle = true;
});

function doCycle() {

    if (cycle) {

        if (controls.find('.hover').length > 0) {

            if (controls.find('.hover').next().length > 0) {

                var next = controls.find('.hover').next();

                controls.children().removeClass('hover');
                next.addClass('hover');

                animate(current);
            }
            else {

                controls.children().removeClass('hover');
                controls.children().first().addClass('hover');

                animate(0);
            }
        }
        else {

            controls.children().first().addClass('hover');

            animate(0);
        }
    }

    setTimeout(doCycle, 2000);
}

function animate(pos) {

    banners.stop().animate({top: pos * -200});

    current = pos + 1;
}

http://jsfiddle.net/imoda/EYDtF/5/

A: You need to look at how these plugins that you don't like work. At the moment you hover function targets an id - if you target a class you immediately reduce the amount of code e.g.
$('.hover').hover(function(){

$bannerSlide.animate({
        'top' : var
    });

});

Then you can work out a way of passing the position (var) to it you reduced you code.


text:
Q: Filter bright dots from the gradient of the image I am wondering how to filter out bright dots in the picture, which are caused by background noise.

A: We could do with ground truth data to assess the result. Is this acceptable as a first step?
Manipulate[
    HighlightImage[
         i,
         result = Binarize[TopHatTransform[i, radius], thr]],
    {{radius, 4}, 1, 10, 1}, {{thr, .015}, 0, .2}]


text:
Q: remix-auth-socials - http 400 {"message": "Missing state on session."} on production, on localhost its working I am trying to make work Google auth on my first remix.run js FW via https://www.npmjs.com/package/remix-auth-socials
On localhost, it works nicely, however on production server its crashing on redirect callback:

*

*URL: [my correct redirect URI]

*response http code: 400 Bad request

*response body: {message: "Missing state on session."}

My configuration is based on readme in npm package:
// ~/services/session.server
export const sessionStorage = createCookieSessionStorage({
    cookie: {
        ...
        secure: true
    },
});

...

I found in FW code that its crashing with this message if it fails to read session from remix sessionStorage.
Does anybody knows what can cause this?

A: https://github.com/sergiodxa/remix-auth/discussions/156#discussioncomment-2536785
This is a common issue if you're coming from one of the remix templates where the cookie's maxAge is set to 0 (useful for implementing a 'remember me' feature). However what this means is the browser immediately sees the cookie as stale. Either remove that property or update it to be a longer time frame. I use maxAge: 60 * 60 * 24 * 30, // 30 days

A: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
Secure Optional
Indicates that the cookie is sent to the server only when a request is made with the https: scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.

This was it, i am not running on https, so solution was to set:
cookie.secure: false


text:
Q: Template class extending from non-template base class and overriding function parameters I am trying to create a non-template base class for the PacketDecoder so I can store Base* in a std::map. The decode function is being overridden properly. The encode function is giving me this error "'encode' is not virtual and cannot be declared pure". I might be thinking about this problem wrong coming from a Java background. Is there a more idiomatic c++ approach to this problem?
class Base {
public:
    virtual Packet* decode(folly::io::Cursor& cursor) = 0;
    virtual void encode(Packet* packet) = 0;
};

template<typename T, typename std::enable_if<std::is_base_of<Packet, T>::value>::type* = nullptr>
class PacketDecoder : public Base {
public:
    virtual T* decode(folly::io::Cursor& cursor) = 0;
    virtual void encode(T *packet) = 0;
};

Example usage:
class TestDecoder : public PacketDecoder<ProxyJoinPacket> {
public:
    ProxyJoinPacket *decode(folly::io::Cursor &cursor) override {
        uint32_t stringLength;
        if (!cursor.tryReadBE<uint32_t>(stringLength)) {
            throw std::runtime_error("Failed to read string length");
        }

        if (cursor.length() < stringLength) {
            throw std::runtime_error("Too few bytes for string");
        }

        auto uuid = cursor.readFixedString(stringLength);
        return new ProxyJoinPacket(uuid);
    }

    void encode(ProxyJoinPacket *packet) override {

    }

};

std::vector<Base*> decoders;
void a() {
    decoders.insert(new TestDecoder()); // error "Allocating an object of abstract class type 'TestDecoder'"
}

A: The issue is that your original class has this virtual function:
virtual void encode(Packet* packet) = 0;

Then your inherited class has this:
virtual void encode(T *packet) = 0;

That's two different virtual functions.
So when you do:
void encode(ProxyJoinPacket *packet) override {

You only override the method int he inherited class, not in Base, which is still missing.
So change your inherited class to use Packet
virtual void encode(Packet* packet) = 0;

You can also change your inherited class and add something like:
void encode(Packet* packet) final {
    encode(dynamic_cast<T*> packet);
}

Don't forget the virtual destructors as well...


text:
Q: Class constructor Rectangle cannot be invoked without 'new' when importing from node_modules I'm using webpack for my project, and I'm importing a class from another package. However, when I extend this class, my code breaks with Class constructor Rectangle cannot be invoked without 'new'. If I copy the class definition from the node_module to my project it works however:
Other package:
This package is compiled by tsc with "target": "ESNext".
export class Rectangle {
  // ...
}

My package: This package is compiled using webpack.
import { Rectangle } from 'other-package'

class A {
}
class B extends A {
}
class C extends Rectangle {
}

console.log(Rectangle)
// outputs: class Rectangle { ... }

console.log(A)
// outputs: ƒ A() { ... }

console.log(B)
// outputs: ƒ B() { ... }

console.log(C)
// outputs: ƒ C() { ... }

console.log(new Rectangle())
// outputs: Rectangle {top: 0, bottom: 0, left: 0, right: 0}

console.log(new A())
// outputs: A {}

console.log(new B())
// outputs: B {}

console.log(new C())
// Uncaught TypeError: Class constructor Rectangle cannot be invoked without 'new'


text:
Q: Multiple Explode I have a column from excel with the following sample text coming in, and I want to explode it in delimiter. Here is the sample
'ABC 11.0x17 / 1x4 / 2x4 XYZ'
'ABC 12.1x18 / 2x4 3x4 XYZ'
'ABC DEF 12.1x19 / 3x4 4x4 XYZ'
'ABC DEF GHI A1 13x20 / 3x4 / 4x4 XYZ'

and I need it to be exploded with x and I need only number that is after 1st x which would be 17, 18, 19 or 20 from the above.   I did like the following:
$text   = explode('x', $row[6]);
echo $text[1];

It gives me 17 / 1, 18 / 2 and so on but I just need 17 or 18 in this case
If anybody have a good solution please write here.

A: You can use preg_match to extract the digits after the first x:
$strings = array(
    'ABC 11.0x17 / 1x4 2x4 XYZ',
    'ABC 12.1x18 / 2x4 3x4 XYZ',
    'ABC DEF 12.1x19 / 3x4 4x4 XYZ',
    'ABC DEF GHI A1 13x20 / 3x4 4x4 XYZ'
);

foreach ($strings as $str) {
    preg_match('/^[^x]+x(\d+)/', $str, $matches);
    echo $matches[1] . "\n";
}

Output:
17
18
19
20

Demo on 3v4l.org
If you want to use only explode, just explode on space after exploding on x and take the first value:
foreach ($strings as $str) {
    $text = explode('x', $str, 2);
    $text = explode(' ', $text[1]);
    echo "$text[0]\n";
}

Demo on 3v4l.org


text:
Q: Starting MySQL 5.1 with different datadir I do regularly change the data directory from the default /var/lib/mysql to something else like /var/lib/mysql1
It works wihtout any issues on 5.0
On 5.1 version of Mysql, it fails to start once I change the datadir with the following message...
Starting MySQL.Manager of pid-file quit without updating file.[FAILED]
I have already created the new directory and changed it's permission. Anything else must be going wrong and I can not figure it out.
Update:
There are 2 error messages in the error log.
[ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
[ERROR] Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

A: Have you moved all the files and directories from old location to new one? If no - that is what you have to do now.


text:
Q: Expectation of KL between Categorical and samples from a Dirichlet Is there a nice closed form expression for $\mathbb{E}_{\theta' \sim Dir(\alpha)} KL (Cat(x; \theta)|| Cat(x;\theta')$, where $Dir(\alpha)$ is the Dirichlet distribution with concentration parameters $\alpha$ and $Cat(x;\theta)$ is the discrete distribution with (log-)parameters $\theta$?

A: It turns out I can answer this myself with some more effort. Write the inner KL expectation out explicitly, and it turns into the (negative) entropy of the categorical plus the cross-entropy between the categorical and the expectation of the log-Dirichlet. There's a nice closed form for the latter:
$\mathbb{E}_{X \sim Dir(\alpha)}[\log(X_i)] = \psi(\alpha_i) - \psi(\alpha_0)$ (from wikipedia).
Mafipulate a few terms and Bob's your uncle.


text:
Q: OnSwipeTouchListener and OnTouchListener doesn't work, when they're both in the code I'm making an android-app where I have to click on a picture, but also swipe left/right.
But when I have these two code snippets in my code at the same time, only OnSwipeTouchListener work. The listeners are both on the same ImageView.
Code 1:
     pic.setOnTouchListener(new OnSwipeTouchListener(this) {
            @Override
          public void onSwipeLeft() {

                Toast.makeText(MainActivity.this, "LEFT", Toast.LENGTH_LONG).show();
         }
             public void onSwipeRight() {

            Toast.makeText(MainActivity.this, "RIGHT", Toast.LENGTH_LONG).show();
            }
        });

Code 2:
  pic.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            Toast.makeText(MainActivity.this, "CLICK WORKS", Toast.LENGTH_LONG).show();
            return true;
        }
    });

But when I have only "Code 2", the OnTouchListener code works perfectly.
How come?
Thanks in advance.

A: I'm not entirely sure what OnSwipeTouchListener is. But a view can only have only one OnTouchListener. Calling pic.setOnTouchListener() a second time also removes the first listener, so it's logical that both cannot be working at the same time.
What you want to do is create a single object that implements View.OnTouchListener and handles both swipes and single taps. See http://developer.android.com/reference/android/view/GestureDetector.html for a good starting point.

A: I ended up implementing a Viewpager with a ImageView fragment for this purpose. The swipe functionally is already integrated that way.


text:
Q: Libcurl how to not show all this information How to not show all this info?
All I do is using little edited FTP example and i dont want that info to be shown.
edit: added full code from main.c
image in link: http://www.mediafire.com/convkey/71e9/oyhctzcdjxakzxzfg.jpg
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>

struct FtpFile {
 const char *filename;
 FILE *stream;
};
static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
  struct FtpFile *out=(struct FtpFile *)stream;
  if(out && !out->stream) {
  /* open file for writing */
  out->stream=fopen(out->filename, "wb");
  if(!out->stream)
  return -1; /* failure, can't open file to write */
}
return fwrite(buffer, size, nmemb, out->stream);
}

int main()
{
CURL *curl;
CURLcode res;
struct FtpFile version={"version.txt", /* name to store the file as if succesful */NULL};

curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();

FILE *file_verzija;
int trenutna_verzija;
int nova_verzija;
char pitanje_za_update;

file_verzija=fopen("version.txt","r");

fscanf(file_verzija,"%i",&trenutna_verzija);

fclose(file_verzija);

printf("Current version %i",trenutna_verzija);

printf("\nChecking for updates...\n");

if(curl)
{
    /*You better replace the URL with one that works!*/curl_easy_setopt(curl, CURLOPT_URL,"http://elektro-srb.com/site/muffin_finder_files/version.txt");
    /* Define our callback to get called when there's data to be written */
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
    /* Set a pointer to our struct to pass to the callback */
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &version);
    /* Switch on full protocol/debug output */
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    res = curl_easy_perform(curl);
    /* always cleanup */
    curl_easy_cleanup(curl);
    if(CURLE_OK != res)
    {
        /* we failed */
        printf("\nerror");
    }
}

if(version.stream)
    fclose(version.stream); /* close the local file */

file_verzija=fopen("version.txt","r");

fscanf(file_verzija,"%i",&nova_verzija);

fclose(file_verzija);

if(trenutna_verzija != nova_verzija)
{
    printf("\nUpdate found! New version is %i",nova_verzija);
}
else
{
    printf("You are running latest version of Muffin Finder!");
}

if(trenutna_verzija != nova_verzija)
{
    printf("\nUpdate? y/n");
    scanf("\n%c",&pitanje_za_update);
    if((pitanje_za_update == 'y') || (pitanje_za_update == 'Y'))
    {
        //UPDATE
    }
    else if((pitanje_za_update == 'n') || (pitanje_za_update == 'N'))
    {
        //pokretanje stare
    }
}

curl_global_cleanup();

return 0;
}

A: You should construct a WRITEFUNCTION option, to prevent it from using stdout for printing.
See here: http://curl.haxx.se/libcurl/c/curl_easy_setopt.html.
Search for "WRITEFUNCTION". You should implement the function (and I assume you would like to leave it empty).
EDIT: As the manual states, you should do the following:
Implement a function to replace the default stdout:
size_t outputFunction(char *ptr, size_t size, size_t nmemb, void *userdata) {}
When you initialize the CURL structure, use this option:
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, outputFunction);

A: comment following line:
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);


text:
Q: Can't import the named export 'PublicKey' from non EcmaScript module (only default export is available) Describe the bug
Hi, I'm trying using Metaplex to upload the assets and verify the collection, I am now moving towards "Minting Website": https://docs.metaplex.com/candy-machine-v2/mint-frontend
run rpm start inside the folder ~/metaplex/js/packages/candy-machine-ui to test the mint button, it doesn't load the localhost and it shows me the following error on the terminal:
Failed to compile.

./node_modules/@solana/buffer-layout-utils/lib/esm/web3.mjs
Can't import the named export 'PublicKey' from non EcmaScript module (only default export is available)

Anyone know how to solve this? thanks
I'm using Visual Studio on Windows, node 14.15.
Update:
It seems I'm not alone:
https://github.com/solana-labs/buffer-layout-utils/issues/6
Solved it:
How to downgrade the version of Solana to 1.9.1

A: For some reason yarn install wasn't doing it for me like in the docs.
I deleted node_module, package-lock.json and yarn.lock then installed with npm instead
npm install && npm start

that worked for me


text:
Q: How to make a rest call in kie workbench I am a newbie to kie workbench, I am using drools 6.3.0 and want to write a code in kie workbench for making a rest call.
With extensions tab, I made a angular page and now I want to make a rest call.
But i am not getting how to use Rest Api in kie workbench.
Can anyone please help me in this.

A: Simplest way : User default REST task.
Programmatic way : You need to create Java Handler. Use Apache HttpClient to implement programmatic REST call in "executeWorkItem" of your "WorkItemHandler", upload the jar in KIE Workbench. Then configure your "Task" to use this handler.


text:
Q: How to make overflow: hidden really hide content? Please, look at this example. I intend making horizontal layout with pure html/css, don't bother of old browsers. I made it with display: table technique. But displaying main text containers (light-yellow) became a problem. Each of this has overflow: hidden to prevent vertical scroll. Later, I intend adding some shadow effect at the bottom. Now, I want to make in, for example, 80% height with 10% margin top and bottom. But what I get is container with larger text stretching all parents container (light-green), so 80% of it became too much.
Is there any way to avoid it without javascript?
Maybe I can get text container any height, but with some margin at the bottom. I will appreciate any solution.

A: Do not use table layouts, table cell divs have a problem setting their width/height and thus will not be able to follow overflow rules.
update the following css properties in your layout.css, this will get you started:
#content{
    display:block;
    height:90%;
    overflow:hidden;
    vertical-align:top;
}

#content-inner{
    display:block;
    height:100%;
    vertical-align:top;
}

.article{
    display:inline-block;
}

A: It's still not clear what you want; maybe post a quick sketch?
Anyway, I'd want to avoid the horizontal scrollbar. To do that set #content {
    width: 61%;} (based on the rest of the CSS).  Currently, in layout.css, #content width is set to 305%.
RE:

@Brock Adam, I mean I want to make div.article-content 80% of screen, not 80% of parent container. I believe this can be achieved by forcing parent div#content be exactly 100% of screen, not more. But I don't know how.

div.article-content currently appears 5 times in the page.  Setting it to 80% of the screen will give a page that's at least 400% wider than what the user can see.
Questions:

*

*The first div is ID'd as "header", but it's floated left and only 39% wide.  Is this a header (bar at top of of page) or a left, side-bar?

*Are the articles supposed to be in 5 tiny columns, on the same row, or are they supposed to be one after another, scrolling down the page?

Again, statements and the semantics of the example page are unclear.  Posting a quick sketch of the desired layout will help us help you.


text:
Q: MySQL Query to CSV Is there an easy way to run a MySQL query from the linux command line and output the results in csv format?
Here's what I'm doing now:
mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/        /,/g' | tee
list.csv select id, concat("\"",name,"\"") as name from students EOQ

It gets messy when there are a lot of columns that need to be surrounded by quotes, or if there are quotes in the results that need to be escaped.

A: You can use "INTO OUTFILE"
I.e.
SELECT a,b,c FROM my_table INTO OUTFILE '/ca.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';

This will create a file "ca.csv" with a comma between each line. There are a few other options like escaping field values, but that should be enough to get you started.
The whole thing:
mysql -u uid -ppwd -D dbname -e "SELECT a,b,c FROM my_table INTO OUTFILE '/ca.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';"
EDIT :- A link for you to look at: SELECT INTO
To escape the fields, you would need to add FIELDS ESCAPED BY '"' - This would add double quotes


text:
Q: How do I write this for-loop in functional style? I have a function with a for-loop:
fun List<Int>.customSum(sumFunction: (Int) -> Boolean): Int {
    var sum = 0
    for (item in this) {
        if (sumFunction(item))
            sum += item
    }
    return sum
}

I want to know how I can write the above in functional style. I know that I have to use this.reduce(), but don't know exactly how to implement it.

A: return filter(sumFunction).sum()

Should be self-explanatory.
You can't use reduce because it doesn't let you reject the first element.
With fold it would be:
return fold(0) { a, b ->
    if(sumFunction(b)) a + b else a
}

A: I can think if two ways to achieve that:

*

*The first one is by using sumOf {...}:

.
fun List<Int>.customSum(sumFunction: (Int) -> Boolean): Int {
    return sumOf {
        if (sumFunction(it)) it else 0
    }
}

*The second one is by using filter {...} then sum():

.
fun List<Int>.customSum(sumFunction: (Int) -> Boolean): Int {
    return filter(sumFunction).sum()
}

A: return this.reduce { sum, n -> if (sumFunction(n)) sum + n else 0}

A: If you really want to use reduce for some reason you can - but you need to add that 0 to the head of the list as your "start state":
fun List<Int>.customSum(sumFunction: (Int) -> Boolean): Int {
    val stuff = listOf(0) + this
    return stuff.reduce { a, b -> a + if (sumFunction(b)) b else 0 }
}

You have to do that because reduce is really there to combine a bunch of items, which is why for the first iteration you get the first two items in the list. You don't get to handle them separately, which is why you need to throw that 0 in there to get past that first step, and get to a point where you can just do your checking on the second parameter and ignore the first one, treating it as an accumulator instead of another item you also need to check.
That behaviour is what fold is for - with that function you pass in an initial state (which can be a completely different type from your items, since you're not just smushing them together to create a new value like with reduce) and then on each iteration you get that state and an item.
You can handle the item as you like, and then make changes to the accumulator state depending on the result. Which is exactly the behaviour of your for loop! fold is just a functional way to write one. Tenfour04's answer is how you'd do it - it's the right tool for the job here!


text:
Q: how to upload base64 to server using formdata react native I have base64 of an image.. I want to send it to the api using formdata. How can that be achieved? I am using react native signature canvas to get the base64 of the signature.
let signature = base64signature;
const formdata = new FormData();
formdata.append('attachments', {
  uri: signature,
  name: 'logo',
  filename: 'logo',
  type: 'image/png',
});

How to convert Base64 String to javascript file object like as from file input form?
I followed this link as well but dont understand how to send it to the api as formdata.. It's constantly giving network error.
I have also tried to convert it to blob and send but that didn't work as well. Can anyone help me with this?

A: var imgBase64 = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCA..." //your bse64 image

onSubmit(){
const file = DataURIToBlob(imgBase64)
const formData = new FormData();
formData.append('upload', file, 'image.jpg')
formData.append('profile_id', this.profile_id) //other param
formData.append('path', 'temp/') //other param
}

    function DataURIToBlob(dataURI: string) {
        const splitDataURI = dataURI.split(',')
        const byteString = splitDataURI[0].indexOf('base64') >= 0 ? atob(splitDataURI[1]) : decodeURI(splitDataURI[1])
        const mimeString = splitDataURI[0].split(':')[1].split(';')[0]

        const ia = new Uint8Array(byteString.length)
        for (let i = 0; i < byteString.length; i++)
            ia[i] = byteString.charCodeAt(i)

        return new Blob([ia], { type: mimeString })
      }

A: *

*You need to install react-native-fs
import RNFS from 'react-native-fs';
import {Platform} from 'react-native';

  const createTempImage = async base64String => {
    try {

      let base64 = base64String.replace('data:image/png;base64,', '');
      const fileName = `${Date.now()}.png`;

      const path = `${RNFS.TemporaryDirectoryPath}/${fileName}`;
      await RNFS.writeFile(path, base64, 'base64');

      const image = {
        uri: Platform.OS == 'ios'? path: 'file://' + path,
        name: fileName,
        type: 'image/png',
      };

     return image
    } catch (error) {
      console.log(error);
    }
  };


text:
Q: how to make Samsung CLX-3185 scanner-part work? I have the Samsung CLX-3185 printer/scanner. The printer-part works fine using 3175 drivers found by (Xubuntu/XFCE) printer setup wizard. However it does not seem to recognize the scanner part. Xsane does not find the scanner. Is there a setup HOWTO for this anywhere that I could use?

A: Instructions how to set-up samsung CLX-3185FW.
Source: baltas125@ubuntuforums. Originally taken from:  bchemnet.
From the 1st link:
After executing instructions I have successfully installed CLX-3185FW over the network. It prints and scans over the network. I have made it on Ubuntu 11.10, 32bit.
Before installing you MUST REMOVE any other previously installed drivers for Samsung.
Step 1 (edit sources):
sudo gedit /etc/apt/sources.list

Add lines:
#samsung drivers
deb http://www.bchemnet.com/suldr/ debian extra

Step 2 (install authentication key) :
wget -O - http://www.bchemnet.com/suldr/suldr.gpg | sudo apt-key add -

Step 3 (update sources):
sudo apt-get update

Step 4 (install packages):
Open ubuntu software center and install one by one all packaged that start with samsungmfp-, excepting:

*

*first install packages which do not have the word "legacy";

*do not install packages which offer you to remove any other packages;

*Do not install samsungmfp-parallel it should only be installed if your printer is actually connected via a parallel port;

Step 5a (check if you are in lp group). Run in Terminal:
cat /etc/group | grep lp

If your account name is next to lp, everything is ok, else add yourself to lp group, e.g. execute Step 5b.
Step 5b (add yourself into lp group if needed):
sudo usermod -a -G lp USERNAME

(more information about groups here)
That's it! Now you can search for your printer in network and add it as clx-3180 series and it will work.
P.S. Previously I have made some changes to some files. But I do not know if it has any impact. If you have executed the five step above and still no luck, try making those changes:
/etc/sane.d/xerox_mfp.conf

lines added
#Samsung CLX-3170fn & CLX-3175FW
usb 0x04e8 0x342a

In ...
/etc/sane.d/xerox_mfp.conf

lines added:
#Samsung CLX-3185FW
usb 0x04e8 0x343d

In ...
/lib/udev/rules.d/40-libsane.rules

lines added:
# Samsung CLX-3185FW
ATTRS{idVendor}=="04e8", ATTRS{idProduct}=="343d", ENV{libsane_matched}="yes"

A: here's some feedback:

*

*I installed the Unified Linux Driver provided by Samsung (german manual providing useful links. The Samsung site has problems atm...). That made the printer work, but not the scanner

*I hadn't installed xsane then, so I did sudo apt-get install xsane. xsane didn't find the scanner

*I modified xerox_mfp.conf and 40-libsane.rules as described above, it should also work with the vendor and product ID of other mfp's you find using lsusb.
now the mfp works fine. thank you for the solution(s)!
btw: I'm with a CLX-3185 -> no netdiscovery required.

A: I had the "Samsung Unified Linux Driver" and "Xsane" installed already and the printer worked well. Only the scanner was not found. After adding following entry in /etc/sane.d/xerox_mfp.conf the scanner was found:

#Samsung CLX-3180
tcp 10.0.0.11 # <- insert your printer's actual IP here

PS: I got that hint from this link.

A: The model number Samsung CLX-3185.
Method 1:
You may refer to the below links and use the troubleshooters. Check if it lists and helps resolve any issues: Open the Printer troubleshooter:
http://www.samsung.com/us/support/
Method 2:
You may check if you have the latest drivers installed for the device. You may refer to the below link for getting the latest drivers and check.
Samsung CLX-3185 Driver

A: Now there is great installer in Samsungs website.
Use this installer and everything works OK!
Verify that you have permission to the same group as well and after change please logout!

A: You don't need all that stuff. Add the repo, then:
apt-get update

And install these 2 packages:
sudo apt-get install samsungmfp-scanner samsungmfp-netdiscovery

That's all you need.. at least for Ubuntu 12.04 that is all you need. I successfully printed a test page and scanned a document.


text:
Q: About toric varieties---properties of stabilizers Let P be a normal variety over an algebraically closed field k, G a torus over k acting on P, assume that the stabilizer of the generic point of P is reduced (resp. connected or both), is it ture then that the stabilizer of every point of P is reduced (resp. connected or both)? And WHY?
What will happen if we assume moreover that P has finitly many G-obits?

A: For "connected" the answer is surely no, as the following example shows.
Let $k=\mathbb{C}$, and consider the action of $\mathbb{C}^*$ on $\mathbb{C}^3-\{0\}$ defined as
$\lambda \cdot (x,y,z):=(\lambda x, \lambda y, \lambda^2 z)$.
Then the general point has trivial stabilizer, whereas the points on the line $x=y=0$ have a non-connected stabilizer isomorphic tO $\mathbb{Z}/2\mathbb{Z}$. The quotient is actually the weighted projective space $\mathbb{P}(1,1,2)$, which has a singularity of type $\frac{1}{2}(1,1)$ at the point $[0:0:1]$.
For "reduced" the answer is yes when $k$ has characteristic $0$, since every group scheme in characteristic zero is reduced.
When $k$ has characteristic $p >0$, I suspect that there are counterexamples. For instance, if $p=2$ it seems to me that, repeating the previous construction with $k$ instead of $\mathbb{C}$, the points lying on the line $x=y=0$ have stabilizer isomorphic to the non-reduced group scheme  $\mu_2:=\textrm{Spec }k[t]/(t^2-1)$.


text:
Q: Github workflow does not read variables from environments Following is my simple github workflow. It is intended to print an environment variable.
name: verify

on:
  workflow_dispatch:

jobs:
  read_env_variables:
    environment: build
    runs-on: [ self-hosted, onprem_dae, docker ]
    steps:
      - name: cat on branch file
        run: |
          echo ${{ env.SOME_VARIABLE }}

I have created an environment named "build". In this environment, I have an environment variable named SOME_VARIABLE set to xyz.
When the workflow is triggered, I expected to echo value xyz but actual value is "". Is there something missing?

A: Your issue here is related to the syntax.
To use the ${{ env.SOME_VARIABLE }} syntax, you need to set an env variable at the workflow, job or step level.
Here is an example:
name: Environment Workflow

on:
  workflow_dispatch:

env:
  WORKFLOW_VARIABLE: WORKFLOW

jobs:

  job1:
    runs-on: ubuntu-latest
    env:
      JOB_VARIABLE: JOB
    steps:
      - name: Run Commands with various variables
        if: ${{ env.WORKFLOW_VARIABLE == 'WORKFLOW' }}
        env:
          STEP_VARIABLE: STEP
        run: |
          echo "Hello World"
          echo "This is the $WORKFLOW_VARIABLE environment variable"
          echo "This is the $JOB_VARIABLE environment variable"
          echo "This is the $STEP_VARIABLE environment variable"

Now, if you want to use the environment secrets for deployment, as explained here on the Github Documentation, the syntax would be different using the job_id.environment as you are already using following this doc.
Here is an example:
  job4:
    runs-on: ubuntu-latest
    environment: build
    steps:
      - name: Show repo env secret
        run: |
          echo ${{ secrets.REPO_ENV_SECRET }}

Note that this variable is a secret, therefore you won't be able to see it through an echo command on the step (it will show ***)

Here is the workflow I used to validate all this implementation if you want to take a look:

*

*workflow yaml file

*workflow run


text:
Q: Turn an array of structs into a binary search tree So I have an array of structs which i want to turn into a binary search tree.Here is what my code looks like.
typedef struct Student{
    char name[25];
    char surname[25];
    char Id[8];
    double grade;
}Student;

struct TNode
{
    struct TNode* data;
    struct TNode* left;
    struct TNode* right;
};

struct TNode* newNode(struct TNode* data);

/* A function that constructs Balanced Binary Search Tree from a sorted array
*/
struct TNode* sortedArrayToBST(struct Student** students, int start, int end)
{
    /* Base Case */
    if (start > end)
      return NULL;

    /* Get the middle element and make it root */
    int mid = (start + end)/2;
    struct TNode *root = newNode(students[mid]);

    /* Recursively construct the left subtree and make it
       left child of root */
    root->left =  sortedArrayToBST(students, start, mid-1);

    /* Recursively construct the right subtree and make it
       right child of root */
    root->right = sortedArrayToBST(students, mid+1, end);

    return root;
}

/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct TNode* newNode(struct TNode * data)
{
    struct TNode* node = (struct TNode*)
                     malloc(sizeof(struct TNode));
    node->data = data;
    node->left = NULL;
    node->right = NULL;

    return node;
}

/* A utility function to print preorder traversal of BST */
void preOrder(struct TNode* node)
{
    if (node == NULL)
        return;
    printf("%s %s %s %.2f ", node->data);
    preOrder(node->left);
    preOrder(node->right);
}

And here is how I call the functions in my main.
struct TNode *root = sortedArrayToBST(&students, 0, n-1);

This doesn't seem to be working for some reason although the array of structs works ok inside of my main function. I always sort my array of structs inside of my main before calling the sortedArraytoBST function. Please help me.

A: I can't be sure whether this answer is complete because your code isn't complete, so I can't test it.
Still, there's one "obvious" error: You declare
struct TNode* newNode(struct TNode* data);

but you call it with
struct TNode *root = newNode(students[mid]);

where students[mid] is a struct Student *.
Pointers to different types are not compatible in C. I guess what you wanted to have is some "generic" B-Tree. There's a solution in C: The generic pointer is void *. You can't dereference it, but you can convert it implicitly from and to any other (data) pointer type.
So the least you should do is change your struct:
struct TNode
{
    void *data;
    struct TNode *left;
    struct TNode *right;
};

and your function prototype:
struct TNode* newNode(void *data);

in your preOrder function, you try to printf() a whole struct -> this isn't possible, printf() needs exactly one argument per conversion specifier! So change it e.g. to this (if you know data always points to a struct Student):
void preOrder(struct TNode* node)
{
    if (node == NULL)
        return;
    struct Student *stud = node->data;
    printf("%s %s %s %.2f ", stud->name, stud->surname, stud->id, stud->grade);
    preOrder(node->left);
    preOrder(node->right);
}


text:
Q: Jquery easing animations lag on iPad I've been developing a web app game for iOS and I've noticed a significant difference in performance on the iPhone verses the iPad. When the player starts a level there are up to 20 animations called at once using jQuery .animate() with jQuery UI easings. There's never any problem with lag or performance issues on any of the iPhones but, at least the iPad mini with retina, there seems to be a lot of lag issues.
I've read that requestanimationframe is supposed to be a better method but how can I use this and still maintain my jQuery UI easing?
Thanks!

A: Take a look at the following post
Velocity.js
Velocity.js reimplements jQuery.animate().
A sample from the link posted above
[jQuery Syntax]
$div
 /* Fade an element in while sliding it into view. */
 .animate({ opacity: 1, top: "50%" })
 /* The values below are what we originally set the element to in our  stylesheet. Animate back to them. */
 .animate({ opacity: 0, top: "-25%" });

[Velocity.js]
$div
 .velocity({ opacity: 1, top: "50%" })
 .velocity("reverse");

More info can be found at the following link pointing to the main page of Velocity.js
Velocity.js Main page
You can download Velocity.js from here


text:
Q: Visual Studio 2008: Publish two versions of the same program I have two slightly different versions of my VB applications that I would like to publish simultaneously. The differences are minimal and mostly include GUI and some internal logic. Incorporating changes into a single application is not an option right now.
I tried publishing and installing them separately but the latest installer always overwrites whatever has already been installed. For example, if I install App v1, then App v2, only App v2 will be visible. If App v1 is installed after App v2, only App v1 will be visible. What I want to have is to have them both installed.
I am using Visual Studio 2008.
Thanks,

A: Factor the common code out into one or more separate projects. Perhaps a class library project; perhaps a Windows Forms project for shared user controls.
Then create one Windows Forms project for each of the versions you want. Have these projects refer to the shared pieces they need.
It's always better to start off by going with the flow, before you try to swim against the tide. The flow in Visual Studio is "one project, one assembly". Start with that and see how far it takes you.


text:
Q: Flash: Is a function defined in a keyframe re-loaded in memory each time the frame is visited? In Flash Actionscript 3, if a function is defined in Frame 1 of a flash animation and the animation loops, does it store another version of the function in memory upon each loop.
frame 1:
function blah() {
  var n = "yes";
  return n;
}

If so, is it a best practice to check to see if it's the first time the frame has been run, by setting a variable and checking it's existence, or is it a non-issue because the compiler checks to make sure that a function has not already been defined?
frame 1:
if (!status) {
  function blah() {
    var n = "yes";
    return n;
  }

  var status = "loaded";
}

A: There is a fair chance that the flash player creates a "wrapper object" for each keyframe, and that when you play a certain keyframe, it just accesses that "instance" of the keyframe. I'm pretty sure the player doesn't store a new instance of that function in memory, it would be a waist of space, and thet fact you can call a function declared in frame one from frame 2 for example, shows that the functions from a frame are probably persistant. Plus, if you consider the fact you can't modify the code from a frame from another frame, when the timeline re-enters that frame, the content would be the same. From a little test I did, it seems as if the player just executes a frame's code everytime it enters that frame, and all the code on the frame is global to the current timeline. I didn't test much so I might be wrong, but I'm pretty sure you can remove the status variable, because it won't work since the status var would be reset to false when the frame script runs.
Hope this helps.


text:
Q: iOS App incremental release Is it possible to release new version of an ios app in an incremental way from App Store. Say release new version to 10% users and based on feedback we could decide to roll back or push new version to everyone.

A: App store has phased release concept for that.
While your app is in phased release, you can choose to pause the release for a total of 30 days, regardless of the number of pauses. If you remove your app from sale, your current phased release will stop and will not be available for that version again.
For more information, please visit link


text:
Q: HTML form data not inserting I'm struggling to insert my form data into a SQL database. When the submit button is selected I am redirected to a page that shows the source code of my process.php file.
here is the code:
the html file
<!DOCTYPE html>

    <title>Insert Open Times</title>
    <link rel="stylesheet" type="text/css" href="phpstyle.css">

    Welcome
    Please enter your opening times for this week.
    Please remember to use 24hr time format!

    <form action="process.php" method="post" class="form">
        Monday Open:
<input type="text" name="monop">

        Monday Close:
<input type="text" name="monclo">

        Tuesday Open:
<input type="text" name="tueop">

        Tuesday Close:
<input type="text" name="tueclo">

        Wednesday Open:
<input type="text" name="wedop">

        Wednesday Close:
<input type="text" name="wedclo">

        Thursday Open:
<input type="text" name="thuop">

        Thursday Close:
<input type="text" name="thuclo">

        Friday Open:
<input type="text" name="friop">

        Friday Close:
<input type="text" name="friclo">

        Saturday Open:
<input type="text" name="satop">

        Saturday Close:
<input type="text" name="satclo">

        Sunday Open:
<input type="text" name="sunop">

        Sunday Close:
<input type="text" name="sunclo">

        <input type="submit" name="submit" value="Submit">
    </form>

and the process.php file
<?php

    $con = mysqli_connect('localhost', 'root', 'root');

    if(!$con){
        echo "Not connected to server";
    }

    if (!mysqli_select_db($con,'opentimes')) {
        echo "Databse not selected";
    }

    $monop = $_POST['monop'];
    $monclo = $_POST['monclo'];
    $tueop = $_POST['tueop'];
    $tueclo = $_POST['tueclo'];
    $wedop = $_POST['wedop'];
    $wedclo = $_POST['wedclo'];
    $thuop = $_POST['thuop'];
    $thuclo = $_POST['thuclo'];
    $friop = $_POST['friop'];
    $friclo = $_POST['friclo'];
    $satop = $_POST['satop'];
    $satclo = $_POST['satclo'];
    $sunop = $_POST['sunop'];
    $sunclo = $_POST['sunclo'];

    $sql = "INSERT INTO weekdata (monop, monclo, tueop, tueclo, wedop, wedclo, thuop, thuclo, friop, friclo, satop, satclo, sunop, sunclo) VALUES ('$monop', '$monclo', '$tueop', '$tueclo', '$wedop', '$wedclo', '$thuop', '$thuclo', '$friop', '$friclo', '$satop', '$satclo', '$sunop', '$sunclo')";

    if (!mysqli_query($con,$sql)) {
        echo "Not successful";
    }

?>

I have triple checked in the SQL database and all the variables are named corrretly.
I should also note that I am very new to php so please excuse most of the mistakes that have been made.

A: Make sure that your localhost working and it executes php files, seems like XAMPP or WAMP not configured properly

A: <?php

    $con = mysqli_connect('localhost', 'root', 'root');

    if(!$con){
        echo "Not connected to server";
    }

    if (!mysqli_select_db($con,'opentimes')) {
        echo "Databse not selected";
    }

    $monop = $_POST['monop'];
    $monclo = $_POST['monclo'];
    $tueop = $_POST['tueop'];
    $tueclo = $_POST['tueclo'];
    $wedop = $_POST['wedop'];
    $wedclo = $_POST['wedclo'];
    $thuop = $_POST['thuop'];
    $thuclo = $_POST['thuclo'];
    $friop = $_POST['friop'];
    $friclo = $_POST['friclo'];
    $satop = $_POST['satop'];
    $satclo = $_POST['satclo'];
    $sunop = $_POST['sunop'];
    $sunclo = $_POST['sunclo'];

    $sql = "INSERT INTO weekdata (monop, monclo, tueop, tueclo, wedop, wedclo, thuop, thuclo, friop, friclo, satop, satclo, sunop, sunclo) VALUES ('$monop', '$monclo', '$tueop', '$tueclo', '$wedop', '$wedclo', '$thuop', '$thuclo', '$friop', '$friclo', '$satop', '$satclo', '$sunop', '$sunclo')";

$dsql = mysqli_query($con,$sql); //For Executing Your query

    if($dsql){
echo "Successful";
}else{
echo mysqli_error($con); //For Checking Error in insertion
}

?>


text:
Q: Does "whose commit message matches the given regular expression" qualify "the youngest commit" or `rev`? Git Pocket Guide says

rev^regexp

For example, HEAD^{/"fixed  pr#1234"}; this selects the youngest commit reachable from rev whose commit message matches the given regular expression.

Does "whose commit message matches the given regular expression" qualify "the youngest commit" or rev?
I am always uncertain about this and similar cases.

A: rev does. From gitrevisions...

<rev>^{/<text>}, e.g. HEAD^{/fix nasty bug}
A suffix ^ to a revision parameter, followed by a brace pair that contains a
             text led by a slash, is the same as the :/fix nasty bug syntax below except
             that it returns the youngest matching commit which is reachable from the <rev>
             before ^.

Note that it's not the youngest commit in the entire repo. It's the youngest commit reachable from the <rev>. If you want the youngest in the whole repo use :/<regexp>.

:/<text>, e.g. :/fix nasty bug
A colon, followed by a slash, followed by a text, names a commit whose commit
             message matches the specified regular expression. This name returns the youngest matching commit which is reachable from any ref, including HEAD. The
             regular expression can match any part of the commit message. To match messages
             starting with a string, one can use e.g.  :/^foo. The special sequence :/!  is
             reserved for modifiers to what is matched.  :/!-foo performs a negative match,
             while :/!!foo matches a literal !  character, followed by foo. Any other
             sequence beginning with :/!  is reserved for now. Depending on the given text,
             the shell's word splitting rules might require additional quoting.

This makes more sense if you realize Git history is not like a big stack of pancakes. It's a directed graph. Git history looks like this...
------ time -------->

              [HEAD]
A <- B <- C <- D [master]
           ^
            \
             E <- F <- G [feature]

This shows a repository with the master branch checked out. It also has a feature branch which has younger commits than master. G is the youngest commit in the repository, but D is the youngest commit reachable by master and HEAD.
HEAD^{/fix nasty bug} will search for fix nasty bug in D, then C, then B, then A. Because the connections are one-way it will not search E, F, nor G because they cannot be reached from HEAD.