text:
Q: Navigate to another scene using NavigatiorIOS in React-native I'm just a beginner when it comes to React-Native and I am a bit unsure on how to correctly use the NavigatorIOS.
So here's the thing, I have a file called index.ios.js that includes another file called walkthroughPage.js. walkthroughPage is just a walkthrough screen.
index.ios.js
'use strict';

var React = require('react-native')
var walkthroughPage = require('./components/pages/walkthroughPage')

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  NavigatorIOS,
} = React;

var blackcab = React.createClass({
  render: function() {
    return (
      <NavigatorIOS
        style={styles.wrapper}
        initialRoute={{
          component: walkthroughPage,
          title: 'Välkommen',
        }}
      />
    );
  }
});

var styles = StyleSheet.create({
  wrapper: {
    flex: 1,
  },
})

AppRegistry.registerComponent('blackcab', () => blackcab);

In this screen I can see a NavigationBar so I'm guessing it kinda works, here to the problem.
In walkthroughPage.js I have a button handler which tells an event to be fired.
'use strict';

var React = require('react-native')
var Button = require('react-native-button')
var Swiper = require('react-native-swiper')
var authenticationPage = require('./components/pages/authenticationPage')

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
} = React;

var walkthroughPage = React.createClass({

  _getStartedButtonPress: function() {
    this.props.navigator.push(authenticationPage);
  },

  render: function() {
    return (
      <Swiper style={styles.wrapper} showsButtons={false}>
        <View style={styles.slide1}>
          <Image
            style={styles.icon}
            source={require('image!F_icon.svg')}
          />
          <Text style={styles.text}>Anslut med Facebook</Text>
          <Text style={styles.paragraph}>Använd Facebook för att snabbt kunnna komma igång med Black Cab</Text>
        </View>
        <View style={styles.slide2}>
          <Image
            style={styles.icon}
            source={require('image!map')}
          />
          <Text style={styles.text}>Hitta chaufförer i närheten</Text>
          <Text style={styles.paragraph}>Aktivera platstjänster på din telefon så vi kan använda din GPS, då slipper du bokstavera på fyllan</Text>
        </View>
        <View style={styles.slide3}>
          <Image
            style={styles.money}
            source={require('image!coin')}
          />
          <Text style={styles.text}>Spara pengar</Text>
          <Text style={styles.paragraph}>Alla vet att svarttaxi är billigt, du är medveten om det va?</Text>
          <Button style={styles.skip} onPress={this._getStartedButtonPress}>
            Kom igång
          </Button>
        </View>
      </Swiper>
    );
  }
});

var styles = StyleSheet.create({
  wrapper: {
  },
  slide1: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ffffff',
  },
  slide2: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ffffff',
  },
  slide3: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ffffff',
  },
  text: {
    color: '#2A2B30',
    fontSize: 20,
    fontWeight: '500',
  },
  paragraph: {
    color: '#b7b7b7',
    marginTop: 25,
    fontSize: 18,
    textAlign: 'center',
    width: 340,
    lineHeight: 25,
  },
  skip: {
    color: '#567BEC',
    marginTop: 100,
  },
  icon: {
    marginTop: -150,
    marginBottom: 30,
    height: 100,
    width: 100,
  },
  money: {
    marginTop: -100,
    marginBottom: 30,
    height: 100,
    width: 100,
  },
})

module.exports = walkthroughPage;

authenticationPage.js
 'use strict';

var React = require('react-native')

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var authenticationPage = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

module.exports = authenticationPage;

How do I tell _getStartedButtonPress to push to the correct view, how do I include the view within the _getStartedButtonPress function?
I get this error Requiring unknown module "./components/pages/authenticationPage".
I have restarted the packager, cleaned the Xcode-project and rebuild & run. No luck, how come?

A: First things first: Make sure the path to authenticationPage is accurate. It looks like your path isn't correct.
Second, here's how you push the next route:
this.props.navigator.push({
  title: 'Web',
  component: Web,
  passProps: {url: this.state.productLink}
})

*

*title is the name you'd like on the navigation bar

*component is
the actual component you're passing

*passProps is where you pass,
well, any props to that component

A: For the unknown module issue: the path to the file is relative.  So if the walkthroughPage.js is in components/pages, the relative path to include authentication page would need to be require('./authenticationPage').
Richard Kho's response on how to use the navigator is correct.  You can't pass it just a component - you need to pass it an object that represents a route (of which "component" is one property).


text:
Q: Is it possible to create a new model in RNetLogo or change the source code of sample models? I am pretty new to the RNetLogo package in R, but so far all the examples of using RNetLogo I saw were about loading model samples and doing something with them. I did not see any examples which show that we can create our own model and write down rules according to which our agents will interact with each other (or see the code of sample models and change it). Is it possible to write these rules in R or does RNetLogo allow us to play with already implemented models (samples) only without changing the code?
For example, when we open in NetLogo Models Library-->Earth Science-->Climate Change (just random example) then we can go to the Code tab and see the code written in NetLogo prog.language:
globals [
  sky-top      ;; y coordinate of top row of sky
...

My question is: can we see this code in R and change it?

A: My answer, I do not think so :-) . You need to developpe your model in netlogo and with RNetlogo in R you can run it, play with data, send some data.frame to your model, change some variable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unbounded linear operator defined on $l^2$ Let $l^2$ be a Hilbert space of infinite sequences $(z_0, z_1, \cdots)$ with finite $\sum_{i=0}^{\infty} |z_i|^2$.
Are there any simple example of unbounded linear opearator $T: l^2 \to l^2$ with $D(T)=l^2$?

A: No there aren't any simple, or even any constructive, examples of everywhere defined unbounded operators.   The only way to obtain such a thing is to use Zorn's Lemma to extend a densely defined unbounded operator.  Densely defined unbounded operators are easy to find.
Zorn's lemma is applied as follows. Let $A$ be an operator on a domain $\mathcal D$. Consider the set $E$ of all extensions of $A$, that is the collection of operators $A'$ on domains $\mathcal D' \supset \mathcal D$ that agree with $A$ when restricted to $\mathcal D$. Then $E$ is partially ordered by inclusion on domains.  Furthermore, any linear chain has an upper bound, by taking unions of domains. So there is a maximal element by Zorn.  Finally, suppose the maximal element $A$ is defined on a domain $\mathcal D'$ that is not all of $\ell^2$.  Let $v$ be any vector in the complement of $\mathcal D'$. Define an extension of $A'$ on $\mathcal D'+\{a v\}$ by, say, mapping $v$ to zero. This contradicts maximality, so any maximal element is globally defined.


text:
Q: Testing spring boot application with embedded mongo My application has
Spring boot
Spring data
Mongo db.
I am trying to do unit test case for dao layer using embedded mongo.while searching in internet, I came across two annotations
*@springboottest
*@testsbmongo..
I am confused with this annotations usage.my question is
1.what is the difference between these annotations
2. i am getting connection refused error when I am using
@testdbmongo
3.how to use this embedded mongo for test when my original mongo server is running

A: You can also use Fongo. Its an in-memory mongoDB similar to h2 database , which we use for RDBMS dao layer test.
 <dependency>
    <groupId>com.github.fakemongo</groupId>
    <artifactId>fongo</artifactId>
    <scope>test</scope>
 </dependency>


text:
Q: How to code simple attack logic for 2D game in C#? Also, attack works, however, the main issue is that I'm supposed to make
weapon attack IN ONE DIRECTION.
Hi, I am making a turn based action game where the player can either move or attack enemies,
using a certain weapon. Enemies just use a simple attack logic of checking if the player is
nearby, then making him take damage if so. Nearby() uses Math.Abs to find absolute distance away.
Here is the old Nearby() method used for Enemy attack:
public bool Nearby(Point locationToCheck, int distance)
        {
            if (Math.Abs(location.X - locationToCheck.X) < distance &&
            (Math.Abs(location.Y - locationToCheck.Y) < distance))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

So the Enemy class, which contains the above method, passes Player location into the method,
and its own attack range as an int, then checks it against its own location, and damages the
player if return true.
However, the player attack is more complicated. His weapon must check for Nearby() distance
in a given direction first. So I need to write a new overloaded Nearby() method to work with
the Player's Weapon attack logic. I don't know how to do this. Somehow, the Player's Weapon Attack method is supposed to pass parameters into the following DamageEnemy() method:
protected bool DamageEnemy(Direction direction, int radius, int damage, Random random)
{
Point target = game.PlayerLocation;
    for (int distance = 0; distance < radius; distance++) {
        foreach (Enemy enemy in game.Enemies) {
            if (Nearby(enemy.Location, target, distance)) {
                enemy.Hit(damage, random);
                return true;
            }
        }
        target = Move(direction, target, game.Boundaries);
        }
                return false;
}

This DamageEnemy method relies on two new overloaded methods, the aforementioned Move() method, and the overloaded Nearby() method. I am doing this as a tutorial in Oreilly Headfirst C#, p. 480, by the way.
*The original inherited Move() method is simple; it just updates the location field of the object that inherits it in a direction based on the input of one of 4 directions from a Direction Enum.
I want to do this myself, but really can't figure out how the attack logic is supposed to work!
Can anyone give me some hints to point me in the right direction? I don't know what they want me to make the new Move() overloaded method for. Is the player supposed to jump to the point where he attacks? Or does it have some other functionality? Thanks!

A: for (int distance = 0; distance < radius; distance++) {
        foreach (Enemy enemy in game.Enemies) {
            if (Nearby(enemy.Location, target, distance)) {
                enemy.Hit(damage, random);
                return true;
            }

This is really bad. The 'for' routine is redundant - distance can be got from enemy.Location and target, and it would take forever to check each enemy over every distance. Plus what if there are obstacles in the way. I think 'distance' in the overrided Nearby() function should be 'direction' which would answer your question. I suggest:
    foreach (Enemy enemy in game.Enemies) {
        if (Nearby(enemy.Location, target, radius, direction)) {
            enemy.Hit(damage, random);
            return true;
        }

Also the 'move()' function is called inside the distance' loop, and so its behaviour is unpredictable.


text:
Q: Why am I getting data from an empty mongodb database? I'm doing a todo application, and in my code I'm using the ng-repeat directive to create as many todoboxes as there are in the database. But in my case even if the database is empty if get five todo boxes. It probably has something to do with my loadData function that I'm calling but I can't figure it out. Here is an image of what I get on my browser combined with the data from the debugger.. When I do a get request on localhost:3000/api/todos I get [] which is right because the database is empty. Any ideas?
Here is my part of my html file:

Things you have to do

 {{ todo.name }}

  <form>
    <input type="text" placeholder="I need to do..." ng-model="formData.newTodo" required>
    <button ng-click="addTodo(formData)">Add</button>
  </form>

Here is my controller:
var app = angular.module('myApp', ['navigationDirective']);

app.controller('MainController', ['$scope','$http', function($scope, $http){
  $scope.formData = {};

$scope.loadData = function(){
  $http.get('/api/todos')
    .then(function(data){
      console.log('Data:' + data);
      $scope.todos = data;
    });
};
//call the loadData function that returns the data from the json file
$scope.loadData();

//Add a new todo to the database
$scope.addTodo = function(){
  $scope.formData = {
    name: $scope.formData.newTodo
  };
  $http.post('/api/todos', $scope.formData)
    .then(function(data){
      console.log($scope.formData.name);
      $scope.todos = data;
      $scope.formData = {};
      console.log(data);
    });
}

}]);

and here is my server.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

//connect to database
mongoose.connect('mongodb://localhost:27017/tododbtest');

// set static files location
// used for requests that our frontend will make
app.use(express.static(__dirname + '/public'));

//app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//define our model for the todos
var Todo = mongoose.model('Todo', {
  name: String,
  //maybe change it to bool later
  //checked: boolean
});

//when I get a get request I'm going to send
//the index.html file
app.get('/', function(req, res){
  res.sendFile( __dirname + '/public/index.html');
});

//get all the todos from the database
app.get('/api/todos', function(req, res){
  Todo.find(function(err, todos){
    if(err)
      res.send(err)
    console.log(todos);
    res.json(todos);
  });
});

//create a todo
app.post('/api/todos', function(req, res){
  console.log("Req.body.name:" + req.body.name);
  Todo.create({name: req.body.name, checked: false},
  function(err, todo){
    if(err) res.send(err);
    Todo.find(function(err, todos){
      if(err) res.send(err);
      res.json(todos);
    });
  });
});

app.listen(3000);

A: The $http service returns a promise which resolves to a response object. Data is one of the five properties of the response object. Set todos to response.data.
  $http.post('/api/todos', $scope.formData)
    .then(function(response){
      console.log($scope.formData.name);
      $scope.todos = response.data;
      $scope.formData = {};
    });


text:
Q: MongoDB not that faster than MySQL? I discovered mongodb some months ago,and after reading this post, I thought mongodb was really faster than mysql, so I decided to build my own bench, the problem is that I do not have the same result than the above post's author, especially for quering the database : mongodb seems to be slower than MyISAM tables. Could you have a look to my python code, may be there is something wrong in it :
from datetime import datetime
import random
import MySQLdb
import pymongo

mysql_db=MySQLdb.connect(user="me",passwd="mypasswd",db="test_kv")
c=mysql_db.cursor()

connection = pymongo.Connection()
mongo_db = connection.test
kvtab = mongo_db.kvtab

nb=1000000
thelist=[]
for i in xrange(nb):
    thelist.append((str(random.random()),str(random.random())))
t1=datetime.now()

for k,v in thelist:
    c.execute("INSERT INTO key_val_tab (k,v) VALUES ('" + k + "','" + v + "')")

dt=datetime.now() - t1
print 'MySQL insert elapse :',dt

t1=datetime.now()
for i in xrange(nb):
    c.execute("select * FROM key_val_tab WHERE k='" + random.choice(thelist)[0] + "'")
    result=c.fetchone()

dt=datetime.now() - t1
print 'MySQL select elapse :',dt

t1=datetime.now()

for k,v in thelist:
    kvtab.insert({"key":k,"value":v})

dt=datetime.now() - t1
print 'Mongodb insert elapse :',dt
kvtab.ensure_index('key')
t1=datetime.now()
for i in xrange(nb):
    result=kvtab.find_one({"key":random.choice(thelist)[0]})

dt=datetime.now() - t1
print 'Mongodb select elapse :',dt

Notes:

*

*both MySQL and mongodb are on locahost.

*both MySQL and mongodb has the 'key' column indexed

MySQL Table:
CREATE TABLE IF NOT EXISTS `key_val_tab` (
  `k` varchar(24) NOT NULL,
  `v` varchar(24) NOT NULL,
  KEY `kindex` (`k`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Versions are:

*

*MySQL: 5.1.41

*mongodb : 1.8.3

*python : 2.6.5

*pymongo : 2.0.1

*Linux : Ubuntu 2.6.32 32Bits with PAE

*Hardware : Desktop core i7 2.93 Ghz

Results (for 1 million inserts/selects) :
MySQL insert elapse : 0:02:52.143803
MySQL select elapse : 0:04:43.675914
Mongodb insert elapse : 0:00:49.038416  -> mongodb much faster for insert
Mongodb select elapse : 0:05:10.409025  -> ...but slower for quering (thought was the opposite)

A: MySQL insert elapse : 0:02:52.143803
Mongodb insert elapse : 0:00:49.038416  -> mongodb much faster for insert

Mongodb inserts much faster because of mongodb insert all data into ram and then periodically flush data to the disc.
MySQL select elapse : 0:04:43.675914
Mongodb select elapse : 0:05:10.409025  -> ...but slower for quering (thought was

You can achieve best performance with mongodb when you will embedd/denormalize your data. In many situation mongodb allow us to avoid joins because of embedding/denormalization.
And when you just inserting data into one collection/table and reading back by index mongodb not supposed to be faster, read speed should be ~ same if compare with sql database.
BTW: In mongodb 2.0 indexes 25% faster, so i guess 2.0 will work faster then mysql.

A: Sigh. These kind of benchmarks, and I use the term loosely in this case, usually break down from the very start. MySQL isn't a "slower" database than MongoDB. One is a relational database, the other a NoSQL document store. They will/should be faster in the functional areas that they were designed to cover. In the case of MySQL (or any RDBMS) and MongoDB this overlap isn't as big as a lot of people assume it is. It's the same kind of broken apples and oranges comparison you get with Redis vs. MongoDB discussions.
There are so many variables (app functional requirements, hardware resources, concurrency, configuration, scalability, etc.) to consider that any benchmark or article that ends with "MongoDB is faster than MySQL" or vice versa is generalizing results to the point of uselessness.
If you want to do benchmark first define a strict set of functional requirements and business rules and then implement them as efficiently as possible on both persistence solutions. The result will be that one is faster than the other and in almost all cases the faster approach has some relevant downsides that might still make the slower solution more viable depending on requirements.
All this is ignoring that the benchmark above doesn't simulate any sort of real world scenario. There wont be a lot of apps doing max throughput inserts without any sort of threading/concurrency (which impacts performance on most storage solutions significantly).
Finally, comparing inserts like this is a little broken too. MongoDB can achieve amazing insert throughput with fire and forget bulk inserts or can be orders of magnitude slower with fsynced, replicated writes. The thing here is that MongoDB offers you a choice where MySQL doesn't (or less so). So here the comparison only make sense of the business requirements allow for fire and forget type writes (Which boil down to, "I hope it works, but no biggy if it didn't")
TL;DR stop doing simple throughput benchmarks. They're almost always useless.

A: It's wrong to look at python execution time and estimate database quality. Each request consist of at least 3 parts:

*

*request preparing (client side),

*request execution (server),

*response preparing (client side)

By my experience data convertion for MongoDB=>python takes much more time than for MySQL=>python.
Also you should use indexes in both databases. MongoDB works good only if you have indexes on fields that you use for queries.
Talking about MySQL, I think it's better to test performance on innoDB, MyISAM doesn't support transactions, foreign keys, triggers and as for me it's a little bit outdated.


text:
Q: salesforce: how to retrieve the data in the fields that are selected by a view, using SOAP Enterprise with PHP I have created a view in Salesforce which retrieves specified contacts and displays a limited number of fields. For example the view is called "Scotland managers" and only retrieves contacts where Location = "Scotland"
I am using the Salesforce enterprise force toolkit and PHP.
Essentially, does the view "Scotland Managers" in Salesforce use a select query?
If so, how can I get hold of that query and execute it using PHP api so I can import these contacts found by the view, into another MySQL database?


text:
Q: ¿Como puedo ponerle una licencia a mi proyecto en Github, si cuando lo cree no le puse licencia? Quiero ponerle unas licencias a mis proyectos ya creados en Github pero cuando los cree no les puse y ahora no se como ponerselas.

A: Solo debes crear el archivo de licencia y hacer un commit al repositorio.
Crea el archivo de licencia con un block de notas e ingresas el texto de la licencia.
Luego en la raiz de la carpeta local del proyecto:
git add .
git commit -m "Licencia"
git push origin master
eso es todo


text:
Q: PyTest import error while attempting to use parallel testing I'm trying to do parallel testing using PyTest. Also I am using unittest and stickng to Page Object Pattern. The error I keep running into is:
ImportError while importing test module 'C:\Users\%username%\Desktop\Automation\Test\Scripts\test_AccountCreation.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
Test\Scripts\test_ArtistAccountCreation.py:1: in <module>
    from Automation.Test.TestBase.EnvironmentSetUp import *
E   ModuleNotFoundError: No module named 'Automation'

The missing module "Automation' is the folder name in which I keep the project files.
from Automation.Test.TestBase.EnvironmentSetUp import *

This is an import line from the test script, there is a class with SetUp and tearDown modules in the file.


text:
Q: Postgres min/max per hour Hi I have a table name token which will have data of token generated like this
id     | generated_time          | token_name
461087 | 2016-10-21 09:02:53.951 |  G1
461088 | 2016-10-21 09:31:13.469 |  C1
461089 | 2016-10-21 09:31:15.711 |  C2
461090 | 2016-10-21 10:37:17.73  |  C3
461091 | 2016-10-21 10:02:53.951 |  G2
461092 | 2016-10-21 10:15:13.469 |  C4
461093 | 2016-10-21 11:22:15.611 |  C5
461094 | 2016-10-21 11:31:14.743 |  C6

and table token_queue like this which have one to one relation
serving_end_time        |  serving_start_time      | token_id
2016-10-21 09:04:45.681 |  2016-10-21 09:03:49.05  | 461087
2016-10-21 09:33:49.035 |  2016-10-21 09:32:07.996 | 461088
2016-10-21 09:34:42.431 |  2016-10-21 09:32:27.134 | 461089
2016-10-21 10:39:57.775 |  2016-10-21 10:38:37.428 | 461090
2016-10-21 10:04:49.715 |  2016-10-21 10:03:09.972 | 461091
2016-10-21 10:17:28.268 |  2016-10-21 10:16:06.946 | 461092
2016-10-21 11:23:36.036 |  2016-10-21 11:22:30.233 | 461093
2016-10-21 11:32:32.876 |  2016-10-21 11:31:27.044 | 461094

now I want to show the min/max of the whole day -24hrs (current_date) in per hour basis from token table and calculate min/max from token_queue ie
MIN(token_queue.serving_end_time - token_queue.serving_start_time)
MAX(token_queue.serving_end_time - token_queue.serving_start_time)
here is the sample output for date 2016-10-21
    hour                | min         | max
    2016-10-21 09:00:00 | 00:01:06    | 00:05:00
    2016-10-21 10:00:00 | 00:01:16    | 00:04:00
    2016-10-21 11:00:00 | 00:02:00    | 00:05:26

thank you for your any help/suggestion.

A: SELECT date_trunc('hour', t.generated_time) AS hour,
       min(tq.serving_end_time - tq.serving_start_time) AS min,
       max(tq.serving_end_time - tq.serving_start_time) AS max
FROM token t
     JOIN token_queue tq
        ON t.id = tq.token_id
GROUP BY 1
ORDER BY 1;


text:
Q: How can I share modules between the client and server using node.js if my module depends on another? Here's my Node.js situation:
I'm trying to share code between my Node.js server and the browser for a game.  Basically, I want to share the game logic.
Lets say my game has a Table, and that Table can have Players.  I want each of these to be modules that can be used by both the client and server.
I know I can do something like this:
(function(exports){

   exports.test = function(){
        return 'hello world'
    };

})(typeof exports === 'undefined'? this['Table']={}: exports);

And I can get something like this working with my Table. However, what if I need to use Players inside this Table module?  Something like:
(function(exports){

   exports.test = function(){
        var Player = require('./Player');
        var p1 = new Player();
    };

})(typeof exports === 'undefined'? this['Table']={}: exports);

While this would work in Node, it obviously wont in on the browser, since require is not defined.  And without require, it would work on the browser, but not Node.
TL;DR: I need to "include" code from one module in another module, which can be shared by both the browser (client) and server.
Thanks

A: You could use require.js to load modules in both node and the browser.
See documentation on the require.js page


text:
Q: Cross domain req in AngularJS using the $http.Get? reverse Proxy and JSONP Well i'm being confused!!
Some says to do a Cross Domain, Some others Bypass Proxy, some others recommand to use JSONP...What is the right solution?
Here's my situation:
I'm running my webservices on Apache (Eclipse) and my front is on IIS server (Visual Studio) and I need to communicate with the both servers.
Using in AngularJS using the $http.Get I want to call my web service and retrieve data. But I have the CORS origin failed.

*

*I tried to add the header header("Access-Control-Allow-Origin", "*")  to my return web service like that :
 @GET
@Produces("application/json")
public Response convertCtoF() {
        Double fahrenheit;
        Double celsius = 36.8;
        fahrenheit = ((celsius * 9) / 5) + 32;
        String test = "[{'data':'balala'}]";
        return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(test).build();
    }

and It only works with JSONP. the JSONP method with an ajax call it works but only with json webservices and i can't get it work with xml returns.

*

*For the reverse proxy I don't know how to configure it on Eclipse!!

Can anyone help .?


text:
Q: How to determine http message end? I need to write simple http caching proxy with python socket class (not using SimpleHTTPServer class). The simple scheme is:
-open socket
-get http message
-check if we have cached resource
-either provide cached resource or re-request it from remote server
-close socket

When getting a message I use synchronous recv method:
38                 message = ""
39                 BUF_SIZE = 4096
40                 while 1:
41                         chunk = connection.recv(BUF_SIZE)
42                         if None == chunk or 0 == len(chunk):
43                                 break
44                         message += chunk
45                         print "rec %i" % (len(message))

And when I connect to my proxy with a browser, the browser will hold the socket open until it either gets response or I manually cancel the wait, which is perfectly by according to how HTTP is intended to work. So, my control is stuck at recv.
-I cannot just read say 1000bytes, coz I don't know how large the actual message is? There doesn't seem to be any message end mark in http?
-the program cannot continue while having open socket, using synchronous read;
-I could use either threads or some kind of async api, to solve control blocking, but this doesn't help with the problem to understand when to stop reading request and start handling it.


text:
Q: MVC AttributeRouting Precedence I am having a bit of an issue with precendence. I've read through the documentation, but I have been unable to solve the problem.
I have the following site, "mysite.com". Within the site I have the route

[GET("{type}")]

That route lets me say "mysite.com/art", or "mysite.com/theatre".
My problem then, is that when I try to create a route for "mysite.com/venues", with the route

[GET("venues")]

It always tries to put "venues" as the parameter within the "Type" action.
I have tried adding

[GET("{type}"), ControllerPrecedence = -1]

... with no luck. I've also tried amending the RouteConfig with:

routes.MapRoute(
                  name: "venues",
                  url: "venues",
                  defaults: new { controller = "Home", action = "Venues" }
              );

... also with no luck. Lastly, I tried:

routes.MapAttributeRoutes(config =>
              {
                  config.AddRoutesFromController();
                  config.AddRoutesFromController();
                  config.UseLowercaseRoutes = true;
              });

After splitting the actions out into a new controller, but again, nothing helped.
The only thing I can think to do is to change the route to be:

[GET("p/venues")]

... but that isn't the nicest of URLs.
Do you have any suggestions of what else I can try?
Thanks a load.
Andy

A: I figured out the problem. The route that I had mainly tested with took a parameter, but I'd missed making the parameter optional, so although it would have been hitting the route, because there was no parameter it went to the next in line.


text:
Q: How to split a string in words that is tab separted in Python I have a list of lines where words in each line are separated by tab characters as follows:
 ajay   vijay   0.6
 vijay  ajay    0.7
 ravi   vijay   0.8
 swati  swapnesh    0.4

Then how I can extract words from each of the line in Python.

A: Learn split function : http://www.tutorialspoint.com/python/string_split.htm
So if your string is "A    B     C",
str = "A    B     c"
li = list(str.split("\t"))

\t is representing tabs

A: your_string.split("\t") should return you a list of words.


text:
Q: Как создать ряд форм в PyQt5? Имеется код, создающий форму, совмещающую в себе свойство кнопки (при клике выполняется функция) и одновременно можно выполнять изменение текста внутри.
Но возникает проблема расстановки множества таких форм, можно конечно создать несколько переменных и выполнять одни и те же действия с ними, но это много одного и того же повторяющегося кода.
Подскажите, пожалуйста, способ расстановки нескольких форм сразу без повторяющегося кода.
Вот сам код:

import sys
import random
from PyQt5 import QtCore, QtGui, QtWidgets

class Label(QtWidgets.QLabel):
    clicked = QtCore.pyqtSignal()
    doubleClicked = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(Label, self).__init__(parent)
        self.resize(100, 100)
        self.setText("Hello World")

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.clicked.emit()

    def mouseDoubleClickEvent(self, event):
        if event.button() == QtCore.Qt.RightButton:
            self.doubleClicked.emit()

class Test(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.resize(500, 500)
        self.setObjectName('test')

        self.label = Label(self)
        self.label.setWordWrap(True)
        self.color = QtGui.QColor(*random.sample(range(255), 3)).name()
        self.label.setStyleSheet(f"background-color: {self.color}")
        self.label.clicked.connect(self.onClicked)
        self.label.doubleClicked.connect(self.onDoubleClicked)

        self.lineEdit = QtWidgets.QLineEdit(self)
        self.lineEdit.editingFinished.connect(self.editFinished)
        self.lineEdit.setGeometry(self.label.geometry())
        self.lineEdit.hide()

    def onClicked(self):
        self.color = QtGui.QColor(*random.sample(range(255), 3)).name()
        self.label.setStyleSheet(f"background-color: {self.color}")

    def onDoubleClicked(self):
        self.lineEdit.setText(self.label.text())
        self.lineEdit.setStyleSheet(f"background-color: {self.color}")
        self.lineEdit.show()
        self.lineEdit.setFocus()

    def editFinished(self):
        self.label.setText(self.lineEdit.text())
        self.lineEdit.hide()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = Test()
    w.show()
    sys.exit(app.exec_())

И примерное фото множества таких форм:

A: Попробуйте так:
import sys
import random
from PyQt5 import QtCore, QtGui, QtWidgets

class Label(QtWidgets.QLabel):
    clicked = QtCore.pyqtSignal()
    doubleClicked = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(Label, self).__init__(parent)
        self.resize(100, 100)
        self.setText("Hello World")

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.clicked.emit()

    def mouseDoubleClickEvent(self, event):
        if event.button() == QtCore.Qt.RightButton:
            self.doubleClicked.emit()

class Widget(QtWidgets.QWidget):                                            # +++
    def __init__(self):
        super().__init__()
        self.setMinimumHeight(100)

        self.label = Label(self)
        self.label.setWordWrap(True)
        self.color = QtGui.QColor(*random.sample(range(255), 3)).name()
        self.label.setStyleSheet(f"background-color: {self.color}")
        self.label.clicked.connect(self.onClicked)
        self.label.doubleClicked.connect(self.onDoubleClicked)

        self.lineEdit = QtWidgets.QLineEdit(self)
        self.lineEdit.editingFinished.connect(self.editFinished)
        self.lineEdit.setGeometry(self.label.geometry())
        self.lineEdit.hide()

    def onClicked(self):
        self.color = QtGui.QColor(*random.sample(range(255), 3)).name()
        self.label.setStyleSheet(f"background-color: {self.color}")

    def onDoubleClicked(self):
        self.lineEdit.setText(self.label.text())
        self.lineEdit.setStyleSheet(f"background-color: {self.color}")
        self.lineEdit.show()
        self.lineEdit.setFocus()

    def editFinished(self):
        self.label.setText(self.lineEdit.text())
        self.lineEdit.hide()

class Test(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.resize(500, 500)
        self.setObjectName('test')

        widget = Widget()                                                    # +++

        btn = QtWidgets.QPushButton("Add Widget")
        btn.clicked.connect(self.onClickButton)

        self.row, self.column = 0, 0
        self.grid = QtWidgets.QGridLayout(self)
        self.grid.addWidget(widget, self.row, self.column)
        self.grid.addWidget(btn, 10, 0, 1, 4)

    def onClickButton(self):
        self.column += 1
        widget = Widget()                                                    # +++
        self.grid.addWidget(widget, self.row, self.column)

        if self.column == 3:
            self.column = -1
            self.row += 1

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = Test()
    w.show()
    sys.exit(app.exec_())


text:
Q: R summarize data by presence of a current event I was searching on the web for a solution to a problem that seems easy but gives me headaches.
I have a dataframe with several columns.
Location<-c("East","East","East","West","West","West","North","North","North")
Year<-c(2009,2009,2010,2010,2011,2011,2012,2013,2013)
Product<-c("A","A","B","A","A","A","A","B","A")
User<-c("GH","GH","AB","AB","AAB","A","G","AB","AB")
a<-data.frame(Location,Year,User,Product)

And I need to summarize its columns. I prefer to do it with ddply and for column User this looks like:
ddply(a,.(Location),summarize,
      User=sum(User=="AB")/NROW(User)
            )

However, for the column Product I need to count  the presence of any "A" in every year as 1=present,0=absent (multiple occurences are not counted individually, e.g. for West in 2011 there was Product A used therefore =1). This should then be divided by the total number of unique years for the corresponding location.
The output should look like
 Location   User     Product
1     East 0.3333333    0.5
2    North 0.6666667    1
3     West 0.3333333    1

I hope I described my problem well enough and someone could give me a hint on how to achieve this.
Thanks in advance

A: I hope this is answer you were looking for:
ddply(a,.(Location),summarise,
      User=sum(User=="AB")/NROW(User),
      Product =length(unique(Year[Product=="A"]))/length(unique(Year)))

  Location      User Product
1     East 0.3333333     0.5
2    North 0.6666667     1.0
3     West 0.3333333     1.0


text:
Q: Return cscript output to batch My batch script is performing an HTTP request by using CScript with Javascript syntax like in my example.
Using this approach (also seen here) and some help on escaping i tried the following:
@if (@This==@IsBatch) @then
@echo off
rem **** batch zone *********************************************************
    setlocal enableextensions EnableDelayedExpansion

    set OWNPATH="%~dpnx0"

    if not "%~11"=="" (
        FOR /F "usebackq tokens=*" %%r in (`cscript //E:JScript %OWNPATH%`) DO SET RESULT=%%r
        ECHO %RESULT%
    )

    exit /b

@end
// **** JScript zone *****************************************************
// Instantiate the needed component to make url queries
var http = WScript.CreateObject('Msxml2.XMLHTTP.6.0');

// perform request
var requestURL = "http://myserver/api";

// Make the request
http.open("GET", requestUrl, false);
http.send();

WScript.Echo(http.ResponseText);

// All done. Exit
WScript.Quit(0);

Unfortunately i get a message that "ECHO is off." and not the string in %RESULT%.
The script is run on a Windows 2008 R2 server.

A: Thanks to @Stephan it works when using
echo !RESULT!

due to the delayed expansion


text:
Q: React Router v6 redirects URL with query params to url without queryparams I'm using React router v6 and facing an issue where if I access any route using query params, I'm automatically redirected to whichever URL I'm on but without query params.
For example:
mywebsite.com/somePage?id=1234 --> mywebsite.com/somePage
Here's my routing component:
 <BrowserRouter>
  <NavigationLayout auth={auth} setAuth={setAuth} setIsClient={setIsClient} isClient={isClient}>
    <Routes>
      <>
        <Route
          exact
          path="/register"
          element={
            auth.email ? (
              <Navigate to="/"></Navigate>
            ) : (
              <Register auth={auth} setAuth={setAuth} />
            )
          }
        />
        <Route
          exact
          path="/login"
          element={
            auth.email ? (
              <Navigate to="/"></Navigate>
            ) : (
              <Login setIsClient={setIsClient} auth={auth} setAuth={setAuth} />
            )
          }
        />

         <Route

          path="/clients"
          element={
            auth.email ? (
              <ClientForm auth={auth} setAuth={setAuth} />
            ) : (
              <ClientsLogin auth={auth} setAuth={setAuth} setIsClient={setIsClient}/>
            )
          }
        />
      </>

      <Route exact path="/form/one" element={<FormPageOne />} />
      <Route exact path="/form/two" element={<FormPageTwo />} />
      <Route exact path="/form/three" element={<FormPageThree />} />
      <Route exact path="/form/four" element={<FormPageFour />} />
      <Route exact path="/form/five" element={<FormPageFive />} />
      <Route exact path="/form/six" element={<FormPageSix />} />
      <Route exact path="/form/seven" element={<FormPageSeven />} />
      <Route exact path="/profile" element={<Profile auth={auth} setAuth={setAuth}/>} />
      <Route exact path="/tyc" element={<Terms/>} />

      <Route
        path="/"
        element={
          auth.email ? (
            <FormPageOne />
          ) : (
            <Login setIsClient={setIsClient} auth={auth} setAuth={setAuth} />
          )
        }
      />

    </Routes>
  </NavigationLayout>
</BrowserRouter>


text:
Q: What is the best way to check for credentials in wcf service? I need to write a WCF Service which takes one input parameter and based on this input parameter,there will be a business logic and it returns a true or false.
Now to have authorization to use this service,i need to check for credentials also.
What is best approach to check for credentials and allow him to access my service.
Can we do anything in headers ?

A: The better if not the best solution, to make your service more secure when you are using a Username authentication is to use a Certificate.
Sending unencrypted username and password over any communication framework is not the best scenario. Therefore when we choose the UserName client credential type WCF insists that your service must also reference a service certificate that contains a private key. The public key in this certificate is used to protect the confidentiality of the username and password sent to the service. The private key is then used by the service to obtain those encrypted credentials.
An easy way to create a certificate on our own is using a Pluralsight tool called Self Cert. Or you can also buy a certificate.
To know the details of how to implement this procedure see this link:
Securing a WCF service with Username and Password using Message security and the Channel Factory pattern


text:
Q: Add RequiredFieldValidator to dynamically created control in code behind I have a page with some textboxes.  Some of the ASP:Textboxes are made in the .aspx file, and other custom ones are created in codebehind (based on db).  I want to validate to make sure all fields are filled.
When I press my ASP:Button to continue, the textboxes created in my html/aspx file are correctly validated, but for some reason, the dynamically created RequiredFieldValidators are ignored.
Code:

                            Weight: <asp:Label runat="server" ID="weightReqLabel" CssClass="required" Visible="false">*</asp:Label>

                            <asp:TextBox runat="server" ID="weight" CssClass="form-control"></asp:TextBox>
                            <asp:RequiredFieldValidator runat="server" ID="validator_weight" ControlToValidate="weight" SetFocusOnError="true" ErrorMessage="Required." CssClass="validation-error"></asp:RequiredFieldValidator>

The above works correctly.
However, this does not work:
TextBox txtbx = new TextBox();
txtbx.ID = "TextBox_" + i;
txtbx.CssClass = "form-control";
txtbx.Text = fieldValue;

RequiredFieldValidator reqFieldVal = new RequiredFieldValidator();
reqFieldVal.ID = "validator_" + i;
reqFieldVal.ControlToValidate = txtbx.ID;
reqFieldVal.SetFocusOnError = true;
reqFieldVal.ErrorMessage = "Required";
reqFieldVal.EnableClientScript = false;
reqFieldVal.CssClass = "required";
reqFieldVal.Enabled = true;

placeHolder.Controls.Add(txtbx);
placeHolder.Controls.Add(reqFieldVal);

Before I added EnableClientScript=false, none of the validation was working.  After I added that, the normally coded validators worked, but the code behind ones do not.
I've also tried to add a ValidationGroup and try Page.Validate in the OnClick of the button but it doesn't seem to help.
protected void SaveAndContinue_Click(object sender, EventArgs e)
{
    Page.Validate();
        if (Page.IsValid)
        {
            ((Redirect))
        }

}

What am I doing wrong?

A: try this
...
placeHolder.Controls.Add(reqFieldVal);
reqFieldVal.Validate();
...

it worked for me


text:
Q: Entity Framework Core: General model configuration When configuring my model mappings in EF Core, I want to set some general mapping rules, eg. tell every class having Id property that this property gets mapped to DB column ID.
Using Entity Framework, I was able to achieve this using this code:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Types<IEntity<long>>().Configure(c =>
    {
        c.Property(x => x.Id).HasColumnName("ID");
    });
}

(IEntity<long> is a simple interface having only single property long Id { get; set; }. Every entity class in my model simply implements this interface.)
Is anything similar possible also with Entity Framework Core 2.2+?

A: In the end, I ended up with this solution:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (IMutableEntityType mutableEntityType in modelBuilder.Model.GetEntityTypes())
    {
        bool isEntity = mutableEntityType.ClrType.GetInterface($"{nameof(IEntity<int>)}`1") != null;
        if (isEntity)
        {
            modelBuilder.Entity(mutableEntityType.ClrType).Property(nameof(IEntity<int>.Id)).HasColumnName("ID");
        }
    }
}


text:
Q: Retrieve data from Firebase by Refering to a Child's Index I am attempting to access, one by one, the values inside of the 'Progress' Child, as can be seen in the following image. Having done my research, I cannot seem to find a function which allows me to refer to a child by its index. Is it possible to access these records by referring to some sort of index, such as [0], [1], [2] etc. as opposed to referring to their key?

A: Firebase Realtime Database only allows accessing data by its path. There is no way to access data by a derived property such as its index/position.
If you need to access data by index, you should use the indices as the keys for those items. But note that Firebase in most cases recommends against doing this, as it hurts scalability and won't work while offline. See Best Practices: Arrays in Firebase.


text:
Q: Write a linux script that can be run as root/sudo What I want to do is:

*

*Write a script to install some software with yum: yum install whatever

*This script will be executed by a user that doesn't have root or sudo permissions

I have no objection to putting the root password in the script, I just don't know how to do it, I mean my script could look like this:
sudo -u root -p password
yum install whatever

The first line is where I don't know what I'm doing, I understand the security risks involved with putting the root credentials in here but it's not important for this.

A: The full power is described here:
The flexibility of sudo is widely under-estimated. This leads to very poor practices (like the sudo su - canon-ball surgery method).
A much better method is to specificly allow the commands you intend to allow without use of a password:
phill = NOPASSWD: /bin/ls, /usr/bin/lprm

You can optionally do this for specific users from specific hosts running as specific admin users. You can even prevent users from passing shell escapes as parameters. You can make sudo prevent the launched program to execute further applications dynamically etc. etc. You will want to read the man-page for sudoers (and be sure to read the procedures for editing this special file!).
Here is a small taste of things, (from here):
User_Alias     OPERATORS = joe, mike, jude
Runas_Alias    OP = root, operator
Host_Alias     OFNET = 10.1.2.0/255.255.255.0
Cmnd_Alias     PRINTING = /usr/sbin/lpc, /usr/bin/lprm

OPERATORS ALL=ALL
#The users in the OPERATORS group can run any command from any terminal.

linus ALL=(OP) ALL
# The user linus can run any command from any terminal as any user in the OP group (root or operator).

user2 OFNET=(ALL) ALL
# user user2 may run any command from any machine in the OFNET network, as any user.

user3 ALL= PRINTING
# user user3 may run lpc and lprm from any machine.

go2linux ALL=(ALL) ALL
# user go2linux may run any command from any machine acting as any user. (like Ubuntu)

 If you want not to be asked for a password use this form
go2linux ALL=(ALL) ALL NO PASSWD: ALL

A: If the user doesn't habe sudo permissions, then calling sudo is quite useless as it will simply deny the access. Also: using sudo the user will not be asked for the root password but for his own password.


text:
Q: Class number formula for binary hermitian forms The class number of integral binary quadratic forms of discriminant $D$ correspond to the class number of $\mathbb Q(\sqrt{D})$. In this case the class number formula is the classical one of Dirichlet.
For the class number of binary hermitian forms of discriminant $D$, on the other hand, there is no such correspondence I am aware of. Still, there is a similar formula proved by G. Humbert around 1920, but it does not give $h(D)$ itself (see here). In a special case:
$$
\sum_{j=1}^{h(D)}\frac{D}{4}\sigma(F_j)=\frac{\pi}{4}\prod_{p|D,p\neq2}(1+\Big(\frac{-1}{p}\Big)\frac{1}{p})
$$
where $\sigma(F_j)$ is a certain collection of fundamental domains.
I'd like to know if there is a more precise formula available.

A: May be you can consult Latimer's paper On ideals in generalized quaternion algebras and Hermitian forms., Trans. Amer. Math. Soc. 38 (1935), no. 3, 436–446.
The main theorem (Theorem 3) establishes a bijection between what he calls "regular classes of ideals" in the maximal order of a certain quaternion algebra, and the classes of binary hermitian forms of discriminant $\alpha$ (in his notation) with coefficients in $\mathbb{Z}$. Actually, he works in greater generality, over a number field $K$ and replacing $\mathbb{Z}$ with $\mathcal{O}_K$ (which he calls $G$). Latimer himself says in the Introduction that what he's doing is a generalization of the classical relation between quadratic forms and class groups of quadratic fields.


text:
Q: Associate a value with a type in Haskell using a typeclass I want to use a typeclass to return a String instance that is functionally dependent upon a Haskell type. For example, imagine we have the type Form. I want to associate the string "form" with this type. Given the type Invocation, I want to associate the string "job". And so on. The important thing is that I will often not have an instance of the type in question, though the type will be in the type signature of any function that uses it.
Perhaps an easy way to demonstrate this is with Swift:
protocol Resource {
  static var resourcePathSegment: String { get }
}

struct Form : Resource {
    static let resourcePathSegment = "form"
}

struct Invocation: Resource {
    static let resourcePathSegment = "job"
}

print(Form.resourcePathSegment)

Why would I want such a thing? I'm talking to a REST API that uses certain conventions. For a GET request, the path segment to the resource in question is functionally dependent upon the type of the data returned from the request. However, I won't have an instance of this type until the request completes.

A: The Proxy type, from Data.Proxy, is defined as data Proxy a = Proxy.
This may be used to create a typeclass for this functionality:
class Resource a where
    name :: Proxy a -> String

instance Resource Form
    name _ = "form"

instance Resource Invocation where
    name _ = "job"

-- etc.

You can then get the name of a type by calling name (Proxy :: Proxy type_name).
There are several variations of this technique; an excellent summary can be found at the recent blog post Proxy arguments in class methods: a comparative analysis.
EDIT: I see that @Alexis King has submitted a very similar answer. Refer to the blog post above for an overview of the pros and cons of each approach. (Personally, I would use Alexis's technique, since I like TypeApplications, but I feel that mine is a bit simpler since it doesn't require AllowAmbiguousTypes or TypeApplications to use.)

A: Using TypeApplications, this is easy:
{-# LANGUAGE AllowAmbiguousTypes, TypeApplications #-}

class Resource a where
  resourcePathSegment :: String

instance Resource Form where
  resourcePathSegment = "form"

instance Resource Invocation where
  resourcePathSegment = "job"

To illustrate how to use the above:
ghci> :t resourcePathSegment
resourcePathSegment :: Resource a => String
ghci> resourcePathSegment @Form
"form"
ghci> resourcePathSegment @Invocation
"job"


text:
Q: Как посмотреть код через дизассемблер ildasm? Выдает ошибку Visual Studio 2015. Хочу посмотреть код через дизассемблер.
Ildasm выдает ошибку: отсутствует допустимый заголовок CLR, поэтому дизассемблирование невозможно.
Кто-нибудь знает, как решить эту проблему?


text:
Q: How to handle a drag gesture in corona I'm new to corona, and was wondering how to create a drag gesture in corona?

A: First off use a "touch" event listener and not "tap." Tap only responds when you lift your finger back up, but touch responds to both putting down and picking up your finger.
The touch event has separate phases for "began" and "ended" that you can use to get the beginning and end of the drag gesture:
http://developer.anscamobile.com/reference/index/eventphase-0
Also, if you want to respond to touches anywhere onscreen (rather than just on one object) then add the listener to Runtime:
Runtime:addEventListener("touch", onTouch)

A: function drawLine( event )
  if(event.phase == "ended") then
    line = display.newLine(event.xStart, event.yStart, event.x, event.y)
    line:setColor(255,0,0)
    line.width = 5
  end
end
Runtime:addEventListener("touch", drawLine)

will produce a line between the start and end of the drag.
source: http://developer.anscamobile.com/reference/index/eventxstart
(should search before asking)


text:
Q: media add error wordpress I am using wampserver64 windows7 OS
When I try to upload image via wordpress media library add new it shows error.
I tried to increase php memory by adding at wp-config.php
   define('WP_MEMORY_LIMIT', '256M');

But It did not help then I added below code at functions.php
  add_filter( 'wp_image_editors', 'change_graphic_lib' );
  function change_graphic_lib($array) {
   return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
 }

Again it did not help. then I add below code at .htaccess
  <IfModule mod_security.c>
   SecFilterEngine Off
   SecFilterScanPOST Off
  </IfModule>

Also it did not help. I changed at wordpress
   dashboard  settings>media> maximum file size width  2048 and height 2048
   I tried to upload 1024x768 size image.

But nothing help.
Thanks in advance

A: 1 .- PLUGINS trouble shooting:
You should have done this already there are plenty of posts in WP support…
Disable all the plugins and re-enable them one by one until the uploader breaks.
If disabling the plugins dont fix your uploader, Rename your Plugins folder and try to upload to see if that fixes it.
2 .- FUNCTIONS.PHP
Make sure you don't have any lines with comments in HTML mark up (Example  )
Make sure you open and close the PHP tags ONLY ONCE!!! in the file.
that fixed my uploader.
3.- JavaScript Problems
The reason there is not much support for this problem is because WordPress works, and the problem is coming from something you or your theme developer broke.
First Step: Chrome; go to the home page of your WordPress blog.
Right click anywhere on the screen and on the menu that pops click on inspect element this will open a pseudo-window  with information about your page source code etc…
In the bottom right of this window there is a cog (gear)  icon and next to it a little red circle with a white x on it, next to that usually is a number (That lists parsing errors when your page loaded.
If you have any number next to the red circle click on it to see the detail of the error.

A: I've got this issue sometimes. Mostly with large MP3s. I've not found why there were an error. I think it's because of a malformed header in the file itself. Wordpress checks the header of file each time you upload it.
My answers :
1 : (NOT ADVISED ! RISKY AND UNSECURE AND I DON'T KNOW IF IT WORKS) You could (but shouldn't) try to remove mime types checking of uploaded files (in function.php). As it's insecure, If you want to test that you'll find how to do with google. Not by me :)
2 : The thing that works mostly everytime : Open your file and reencode (or save it) again with your editor/encoder. As I said, I had to reencode some MP3s I had (legal MP3s !) and after that, I could put the files on the server. Again, not really know why.


text:
Q: Calculating probability in a Bayesian Network $$\require{enclose}\newcommand{\circletext}[1]{\enclose{circle}{\bbox[0.75ex]{\rm #1}}} \begin{array}{c} && \circletext{Influenza} &&&& \circletext{Smokes} \\ & \swarrow & \downarrow & \searrow &  &\swarrow \\ \circletext{Sore\, throat} && \circletext{Fever} & & \circletext{Brochitis}\\ &&& \swarrow & & \searrow \\ && \circletext{Coughing}&&&&\circletext{Wheezing}\end{array}$$
Suppose I have a network defined as above.
What would be the formula for calculating
$\mathsf P(\text{Wheezing})$?

A: Do you mean calculate it from the root probabilities and branch conditionals?
Letting $W$ stand for "Wheezing", $B$ for "Bronchitis", $I$ for "Influenza", $S$ for "Smoker", et cetera.
$$\def\P{\operatorname{\mathsf P}} \P(W) ~{=~ \sum\limits_{b\in\{B,B^\complement\}} \P(W\mid b)\P(b) \\ =~\sum\limits_{b\in\{B,B^\complement\}} \P(W\mid b)\Big(\sum\limits_{i\in\{I,I^\complement\}}\underline{\phantom{ \P(i)}}\big(\sum\limits_{s\in\{S,S^\complement\}}\underline{\phantom{\P(s)\P(b\mid s, i)}}\big)\Big) }$$

A: You have that:
$$P(I, SH, F, B, S, C, W) = P(I)P(SH|I)P(F|I)P(B|I,S)P(S)P(C|B)P(W|B)$$
Which will give you:
$$P(W) = \sum_{I,SH,F,B,S,C} P(I)P(SH|I)P(F|I)P(B|I,S)P(S)P(C|B)P(W|B)$$
$$P(W) = \sum_{I} P(I) \sum_{SH}P(SH|I) \sum_{F}P(F|I)\sum_{B} P(B|I,S) \sum_{S} P(S) \sum_{C} P(C|B)P(W|B)$$
$$P(W) = P(W|B) \sum_{C} P(C|B)$$
$$P(W) = P(W|B)$$


text:
Q: Part 1: Referencing an Array Without Using Pointers and only Subscripting | Part 2: "..." with Pointers #include <iostream>
#include <time.h>
using namespace std;

void my_func();
int main()
{
    float start_time = clock();
    cout << "Starting time of clock: " << start_time;
    cout << endl << endl;

    for (int i = 0; i < 100000; i++)
    {
        my_func();
    }

    float end_time = clock();
    cout << "Ending time of clock: " << end_time;
    cout << endl << endl;
}

void my_func()
{
    int my_array[5][5];
}

I need to write a program that does a large number of references to elements of a two-dimensional array, using only subscripting. This is really a two-part project, but I'm only concerned with getting the first part right. The second part allows the use of pointers but for now, I am only subject to "subscripting" (indices?). Any advice on how to proceed?
I have successfully completed the first part thanks to Volkan İlbeyli. I am now moving on to the second part:
I need to write a program that does a large number of references to elements of a two-dimensional array, using pointers and pointer arithmetic. Here's what I have so far:
#include <iostream>
#include <time.h>
using namespace std;

void my_func();

int main()
{

    float start = clock();

    for (int i = 0; i < 100000; i ++)
    {
        my_func();
    }

    float end = clock();
    cout << "Ending time of clock: " << (end - start) / ((double)CLOCKS_PER_SEC);
}

void my_func()
{
    int my_array[10][10];

    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            *(my_array+i+j);
        }
    }
}

I have done the first part and now I am working on the next part. I just want to know if I've missed anything. The code works fine and so does the program. Pointers are not my strongpoint and it took me a lot of time on the Internet to find my answers. Asking for a technical standpoint now on pointers and "pointer arithmetic".

A: Well, even though I could not understand the purpose or the meaning of the task you are attempting, if I didn't get it wrong, you are asked to reach to the elements of the 2D array by using indices.
Considering your code, in your my_func() you do not access to the elements. You only declare that you will use a 2D array with size 5x5. To access the elements, (i think) in your case to reference the arrays, you should use for loops and indices to access the elements of the array.
I should go like this in your case:
void my_func()
{                                   //assuming that the usage of
    int my_array[1500][500] = {0};  //square matrice is not mandatory

    for(int i=0; i<1500 ; i++){
        for(int j=0; j<500 ; j++){
            my_array[i][j]; //no operation is done, only accessing the element
        }
    }

    return;
}

You could also swap the for loops to access the array in a vertical manner, i.e. going through first column, then 2nd, then 3rd... That will make your referencing a 2D array by indices slower. See this post on SO why it slows down to swap the for loops, i.e. changing the row-column order into column-row.
You should also note that if you are concerned with critical time measuring of a certain event, you should include only that event when starting the clock and ending the clock. In your code, you also include the time to call cout, endl, and the calling time of my_func() which has nothing to do with the array referencing. Also I'd rather measure the time in the main() function since the accessing the 2D array doesn't require too much code. If it did require too much time, I'd call the function, declare the timing variables inside, definitely not print the starting time, start the time before the repeat-the-operations loop and stop after the loop terminates. You can see this post to have an idea about how time is measured and printed (when you need to consider seconds, or milliseconds etc.).


text:
Q: How to generate 3D helix in MATLAB or Python? I have written a code to generate x, y, z points of a helix and got this result:

Code:
clear all; delete all, clc;
% Spiral constants
THETA_0 = 5; % constant
THETA_1 = 10.3; % starting angle
A = 3.762;
B = 0.001317;
C = 7.967;
D = 0.1287;
E = 0.003056;

s=2;
% Calculate (x,y,z) coordinates of points defining the spiral path
theta = THETA_1:.1:910.3;  % range, starting degree angle:final degree angle
for i = 1:length(theta)
    if (theta(i)<=99.9)
        R(i) = C*(1-D*log(theta(i)-THETA_0));
    else
%       theta_mod = 0.0002*theta(i)^2+.98*theta(i);
        R(i) = A*exp(-B*theta(i));
    end
    % scaling
    x(i) = s*R(i)*cosd(theta(i));
    y(i) = s*R(i)*sind(theta(i));
    z(i) = s*E*(theta(i)-THETA_1);
end

helix=animatedline('LineWidth',2);
axis equal;
axis vis3d;
% set (gca,'XLim', [-5 5],'YLim', [-10 10], 'ZLim',[0 6])
view(43,24);
hold on;
for i=1:length(z)
    addpoints(helix, x(i),y(i),z(i));
    head=scatter3 (x(i),y(i),z(i));
    drawnow
%   pause(0.01);
    delete(head);
end

and I want a helical structure around it similar to this

A: Spent some time looking for this and wanted to share a copy of the code with more comments on what each variable does. Please correct me if I have them wrong but I've played with the code and this seems about right. Hope this helps others who end up looking for some more detail because its been a while since Calculus III :)
    %% 3D Helical Curve
    % tested on MATLAB R2018a
    % See also https://stackoverflow.com/a/55126315/11895567
    % See also https://stackoverflow.com/q/55119694/11895567
    %
    % Code is in the state used to obtain the second of the two images shown below
    clear, clc, close all
    format compact

    %% Input Parameters
    res = 25;   % plot resolution; higher -> finer resolution
    R = 0.15;   % wire radius
    r = 4;      % radius to wire centerline
    t = 3;      % number of coils

    %% Surface of the wire
    a = 3;  % scalar for resolutoin for surface.u to make it look nicer
    b = 2;  % Set to 2 for upper and lower surfaces. Set to 1 for upper surface only

    surface.u = linspace(0, t*2*pi, a*res); % Path of the wire surface
    surface.v = linspace(0, b*pi, res);     % Wire surface
    [surface.u, surface.v] = meshgrid(surface.u, surface.v);

    surface.x = (r + R*cos(surface.v)).*cos(surface.u);
    surface.y = (r + R*cos(surface.v)).*sin(surface.u);
    surface.z = R*sin(surface.v) + surface.u/pi;

    %% Center line of the wire
    c = a;  % scalar for resolution for line.u to make it look nicer

    line.u = linspace(0, t*2*pi, c*res);
    line.x = r.*cos(line.u);
    line.y = r.*sin(line.u);
    line.z = line.u/pi;

    %% Plotting
    f = figure();
    grid on
    hold on
    plot3(line.x, line.y, line.z, 'r');
    surf(surface.x, surface.y, surface.z)
    view(45, 12);   % Azimuth = 45, Elevation = 12
    axis equal

Samples (assume units are millimeters):

*

*Inputs: R = 0.25, r = 1, t = 1, res = 25

*

*Wire radius, R, is 0.25mm

*coil radius, r, is 1mm

*number of coils, t, is 1 (unitless)

*plot resolution, res, is 25 (unitless)

*Inputs: R = 0.15, r = 4, t = 3, res = 25

*

*Wire radius, R, is 0.15mm

*coil radius, r, is 4mm

*number of coils, t, is 3 (unitless)

*plot resolution, res, is 25 (unitless)

A: Your second picture give you:

*

*The parametric equations for x,y and z.

*The restriction on u and v
You have all the necessary informations to create your geometry:
%plot the mesh
u=linspace(0,4*pi,50);
v=linspace(0,2*pi,50);
[u,v]=meshgrid(u,v);
x=(1.2+0.5*cos(v)).*cos(u);
y=(1.2+0.5*cos(v)).*sin(u);
z=0.5*sin(v)+u/pi;
surf(x,y,z)
hold on

%plot the 3d line
u = linspace(0,4*pi,40)
x=1.2.*cos(u);
y=1.2.*sin(u);
z=u/pi;
plot3(x,y,z,'r');

axis equal

Now you just have to adjust the parametric equations to fit your line.

EDIT:
To apply the same solution to your specific case you simply have to replace u and v with your theta and R variable in the meshgrid function:
THETA_0 = 5; % constant
THETA_1 = 10.3; % starting angle
A = 3.762;
B = 0.001317;
C = 7.967;
D = 0.1287;
E = 0.003056;

s=2;
% Calculate (x,y,z) coordinates of points defining the spiral path
theta = THETA_1:5:910.3;
for i = 1:length(theta)
    if (theta(i)<=99.9)
        R(i) = s*C*(1-D*log(theta(i)-THETA_0));
    else
        R(i) = s*A*exp(-B*theta(i));
    end

end

x = R.*cosd(theta);
y = R.*sind(theta);
z = E.*(theta-THETA_1);
plot3(x,y,z,'r','linewidth',2)

hold on
[u,v]=meshgrid(theta,R);
x=(R+0.5*cos(v)).*cosd(u);
y=(R+0.5*cos(v)).*sind(u);
z=0.5*sin(v)+E.*(u-THETA_1);
mesh(x,y,z,'facecolor','none')

axis equal

Result:

by the way I'm not a big fan of mixing cosd and cos in the same script, but do what you want.


text:
Q: What are the equivalent methods of the following native API functions? I am looking for the equivalent methods (in .Net) of the following WinAPI:

*

*CreateFile(); or OpenFile();

*CreateFileMapping();

*MapViewOfFile();

A: You can use those functions directly. The .net wrappers  of the memory mapped file API were only introduced in .net 4.0.

A: For .NET 4.0 developers, the interesting classes that work with memory-mapped files live in the new System.IO.MemoryMappedFiles namespace.
See this article: http://www.developer.com/net/article.php/3828586/Using-Memory-Mapped-Files-in-NET-40.htm


text:
Q: Laravel WhereIn method in Eloquent not working I want to use the WhereIn method in Eloquent but it now works like the below function.
<?php
  $product = DB::table('product')
                   ->join('supplier','supp_code','=','prod_supplier_code')
                   ->select('product.*','supplier.supp_margin')
                   ->where('prod_seo_title','=',$id)
                   ->first();

  $decArr = explode(',',$product->prod_decoration_type);

        for($i=0; $i<count($decArr); $i++)
        {
            if($i==0)
            $inString = "'".$decArr[$i]."','";
            elseif ($i<(count($decArr))-1)
            $inString .= $decArr[$i]."','";
            else
            $inString .= $decArr[$i]."'";
        }

        $proDeco = DB::table('decoration')->whereIn('deco_print_type', [$inString])->get();
?>

But In the query, it's displaying like this.
select * from `decoration` where `deco_print_type` in ('\'100109C9\',\'100110B9\',\'100144C9\',\'100186C9\'');

I can't understand why these slashes are coming. Please help me to fix this issue.

A: The whereIn() method will accept an array of all the items. In your example you are passing an array with one element with all the values already concatenated. Based on your example you only need to pass $decArr
DB::table('decoration')->whereIn('deco_print_type', $decArr)->get();


text:
Q: Text inside ActiveX textbox 'stretches' with move & size with cells On my worksheet there are ActiveX textboxes, which I have sized so they fit the cell they are in.
I have set object positioning to move and size with cells.
When I change the size of the cells, the textboxes resize as intended, but the text inside the box 'stretches' instead of remaining the same.

A: Well you obviously run into one of the numerous ActiveX bugs. I can only recommend to stay far away from ActiveX, as they are well known to cause odd issues and numerous bugs.
As solution I suggest to ask Microsoft to fix the bug and/or in the meanwhile use the following workaround after you resized columns.

There is a workaround, that could fix the odd stretch looking bug:

You just need to resize the TextBox with VBA like TextBox1.Width = TextBox1.Width and everything looks smooth again.

To fix all TextBoxes just loop through all of them and reset their width:
Option Explicit

Public Sub FixOddTextBoxesAfterColumnResize()
    Dim obj As OLEObject
    For Each obj In ActiveSheet.OLEObjects
        If obj.progID = "Forms.TextBox.1" Then
            obj.Width = obj.Width
        End If
    Next obj
End Sub


text:
Q: Spring Boot invalid CSRF token on Heroku I have app with backend written in Java (Spring Boot) exposing REST API and frontend in Javascript (React). Requests are handled correctly on localhost (even when running the backend with heroku local web, however when I deployed the API server on Heroku, any request which is not GET will fail with 403 - Forbidden error. Investigating the logs I found out the issue is in CSRF token being supposedly invalid:
2020-07-02T08:40:35.288650+00:00 app[web.1]: 2020-07-02 08:40:35.288 DEBUG 4 --- [io-12333-exec-5] o.a.coyote.http11.Http11InputBuffer      : Received [POST /api/login HTTP/1.1
2020-07-02T08:40:35.288652+00:00 app[web.1]: Host: xxx-server.herokuapp.com
2020-07-02T08:40:35.288653+00:00 app[web.1]: Connection: close
2020-07-02T08:40:35.288653+00:00 app[web.1]: User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0
2020-07-02T08:40:35.288654+00:00 app[web.1]: Accept: application/json, text/plain, */*
2020-07-02T08:40:35.288654+00:00 app[web.1]: Accept-Language: en-US,en;q=0.5
2020-07-02T08:40:35.288654+00:00 app[web.1]: Accept-Encoding: gzip, deflate, br
2020-07-02T08:40:35.288655+00:00 app[web.1]: Content-Type: application/json;charset=utf-8
2020-07-02T08:40:35.288655+00:00 app[web.1]: Origin: https://xxx-client.herokuapp.com
2020-07-02T08:40:35.288656+00:00 app[web.1]: Dnt: 1
2020-07-02T08:40:35.288656+00:00 app[web.1]: Referer: https://xxx-client.herokuapp.com/login
2020-07-02T08:40:35.288657+00:00 app[web.1]: Cookie: XSRF-TOKEN=d6392331-6f4f-4563-9d39-dd0fc55f7a8c; JSESSIONID=858AAFEE26679A572B991C091B4D15A7
2020-07-02T08:40:35.288658+00:00 app[web.1]: X-Request-Id: 6f81547f-0699-4ecd-9ba3-b550431e6574
2020-07-02T08:40:35.288658+00:00 app[web.1]: X-Forwarded-For: 213.175.51.1
2020-07-02T08:40:35.288658+00:00 app[web.1]: X-Forwarded-Proto: https
2020-07-02T08:40:35.288659+00:00 app[web.1]: X-Forwarded-Port: 443
2020-07-02T08:40:35.288659+00:00 app[web.1]: Via: 1.1 vegur
2020-07-02T08:40:35.288659+00:00 app[web.1]: Connect-Time: 1
2020-07-02T08:40:35.288660+00:00 app[web.1]: X-Request-Start: 1593679235264
2020-07-02T08:40:35.288660+00:00 app[web.1]: Total-Route-Time: 0
2020-07-02T08:40:35.288660+00:00 app[web.1]: Content-Length: 41
2020-07-02T08:40:35.288661+00:00 app[web.1]:
2020-07-02T08:40:35.288661+00:00 app[web.1]: {"username":"user","password":"password"}]
2020-07-02T08:40:35.289207+00:00 app[web.1]: 2020-07-02 08:40:35.289 DEBUG 4 --- [io-12333-exec-5] o.a.t.util.http.Rfc6265CookieProcessor   : Cookies: Parsing b[]: XSRF-TOKEN=d6392331-6f4f-4563-9d39-dd0fc55f7a8c; JSESSIONID=858AAFEE26679A572B991C091B4D15A7
2020-07-02T08:40:35.294663+00:00 app[web.1]: 2020-07-02 08:40:35.294 DEBUG 4 --- [io-12333-exec-5] o.a.catalina.connector.CoyoteAdapter     :  Requested cookie session id is 858AAFEE26679A572B991C091B4D15A7
2020-07-02T08:40:35.295067+00:00 app[web.1]: 2020-07-02 08:40:35.295 DEBUG 4 --- [io-12333-exec-5] o.apache.catalina.valves.RemoteIpValve   : Incoming request /api/login with originalRemoteAddr [10.36.40.162], originalRemoteHost=[10.36.40.162], originalSecure=[false], originalScheme=[http], originalServerName=[xxx-server.herokuapp.com], originalServerPort=[80] will be seen as newRemoteAddr=[213.175.51.1], newRemoteHost=[213.175.51.1], newSecure=[true], newScheme=[https], newServerName=[xxx-server.herokuapp.com], newServerPort=[443]
2020-07-02T08:40:35.295285+00:00 app[web.1]: 2020-07-02 08:40:35.295 DEBUG 4 --- [io-12333-exec-5] o.a.c.authenticator.AuthenticatorBase    : Security checking request POST /api/login
2020-07-02T08:40:35.295437+00:00 app[web.1]: 2020-07-02 08:40:35.295 DEBUG 4 --- [io-12333-exec-5] org.apache.catalina.realm.RealmBase      :   No applicable constraints defined
2020-07-02T08:40:35.295587+00:00 app[web.1]: 2020-07-02 08:40:35.295 DEBUG 4 --- [io-12333-exec-5] o.a.c.authenticator.AuthenticatorBase    : Not subject to any constraint
2020-07-02T08:40:35.296468+00:00 app[web.1]: 2020-07-02 08:40:35.296 DEBUG 4 --- [io-12333-exec-5] o.s.security.web.FilterChainProxy        : /api/login at position 1 of 14 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-07-02T08:40:35.296772+00:00 app[web.1]: 2020-07-02 08:40:35.296 DEBUG 4 --- [io-12333-exec-5] o.s.security.web.FilterChainProxy        : /api/login at position 2 of 14 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-07-02T08:40:35.296861+00:00 app[web.1]: 2020-07-02 08:40:35.296 DEBUG 4 --- [io-12333-exec-5] o.s.security.web.FilterChainProxy        : /api/login at position 3 of 14 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-07-02T08:40:35.297193+00:00 app[web.1]: 2020-07-02 08:40:35.297 DEBUG 4 --- [io-12333-exec-5] o.s.security.web.FilterChainProxy        : /api/login at position 4 of 14 in additional filter chain; firing Filter: 'CorsFilter'
2020-07-02T08:40:35.307430+00:00 app[web.1]: 2020-07-02 08:40:35.307 DEBUG 4 --- [io-12333-exec-5] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-07-02T08:40:35.335515+00:00 app[web.1]: 2020-07-02 08:40:35.335 DEBUG 4 --- [io-12333-exec-5] o.s.security.web.FilterChainProxy        : /api/login at position 5 of 14 in additional filter chain; firing Filter: 'CsrfFilter'
2020-07-02T08:40:35.336779+00:00 app[web.1]: 2020-07-02 08:40:35.336 DEBUG 4 --- [io-12333-exec-5] org.apache.tomcat.util.http.Parameters   : Set encoding to UTF-8
2020-07-02T08:40:35.336875+00:00 app[web.1]: 2020-07-02 08:40:35.336 DEBUG 4 --- [io-12333-exec-5] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for https://xxx-server.herokuapp.com/api/login
2020-07-02T08:40:35.411867+00:00 heroku[router]: at=info method=POST path="/api/login" host=xxx-server.herokuapp.com request_id=6f81547f-0699-4ecd-9ba3-b550431e6574 fwd="213.175.51.1" dyno=web.1 connect=1ms service=145ms status=403 bytes=702 protocol=https
2020-07-02T08:40:35.370981+00:00 app[web.1]: 2020-07-02 08:40:35.370 DEBUG 4 --- [io-12333-exec-5] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2020-07-02T08:40:35.383898+00:00 app[web.1]: 2020-07-02 08:40:35.383 DEBUG 4 --- [io-12333-exec-5] o.a.c.c.C.[Tomcat].[localhost]           : Processing ErrorPage[errorCode=0, location=/error]

As you can see, the XSRF-TOKEN cookie (which works on localhost) is there. Here are my security settings:
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers(Mappings.API_ROOT_USERS + "/current")
        .authenticated()
        .anyRequest()
        .permitAll()
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(jwtAuthenticationEntryPoint)
        .and()
        .logout()
        .logoutSuccessHandler(logoutSuccessHandler)
        .logoutUrl(Mappings.API_ROOT + "/logout")
        .deleteCookies(Constants.JWT_COOKIE_NAME)
        .and()
        .csrf()
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
        .cors(Customizer.withDefaults());

    http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    http.addFilterBefore(jsonUsernamePasswordFilter(), UsernamePasswordAuthenticationFilter.class);
  }

How could I fix this?
UPDATE: I tried to manually edit the request and copied the value from XSRF-TOKEN cookie to X-XSRF-TOKEN header and the request passed through. So the issue is probably that client (React/axios) can't see the cookie and set the header. I also can't see any client cookies in Storage tab of Developer tools when in Heroku deployed version (I can on localhost). Can it have something to do with herokuapp.com being listed in Public Suffix list? (https://devcenter.heroku.com/articles/cookies-and-herokuapp-com)


text:
Q: Why are my variables reporting as "undeclared identifier" when compiling? I have the following code:
       for(int iY=0;iY<(Height-YRemainder);iY=iY+16);
        {
            for(int iX=0;iX<(Width-XRemainder);iX=iX+16);
            {
                if(Operation==BLACKNESS)
                {
                    Operation = WHITENESS;
                    PatBlt(DeviceContext, iX, iY, 16, 16, Operation);
                }
                else
                {
                    Operation = BLACKNESS;
                    PatBlt(DeviceContext, iX, iY, 16, 16, Operation);
                }
            }
            if(Operation == BLACKNESS)
            {
                Operation = WHITENESS;
                PatBlt(DeviceContext, Width-XRemainder,iY,16,16,Operation);
            }
            else
            {
                Operation = BLACKNESS;
                PatBlt(DeviceContext, Width-XRemainder, iY, 16, 16, Operation);
            }

        }

When I compile, I get undeclared identifiers reported against each PatBlt for iX and iY.  Am I misunderstanding how the scope of each variable is working here or have I missed something?
Thanks in advance

A: You have semi colons at the end of the for statements which turns them into single line statements:
for(int iY=0;iY<(Height-YRemainder);iY=iY+16);

becomes
for(int iY=0;iY<(Height-YRemainder);iY=iY+16)


text:
Q: How can i bulk remove page breaks  in wordpress posts? I'm trying to remove pagebreaks (<!--nextpage-->) within my posts' contents. I have so many posts with pagebreaks that need to be removed, that I'd like to bulk-remove that code, or disable that function if possible. How can I achieve this? Thank you for help.
https://i.stack.imgur.com/w1iBs.png
https://i.stack.imgur.com/kb75y.png


text:
Q: p.adjust giving unexpected results I'm trying to get adjusted p-values for a list of p-values, but the p.adjust function is giving me unexpected values.
CRISPR_gene_BH <- with(CRISPR_gene, data.frame(Transcript_Cluster_ID, Gene_Symbol, Fold_Change, ANOVA_p.value,
                                           Adjusted_p.value = p.adjust(CRISPR_gene$ANOVA_p.value, method = "BH"))

> head(CRISPR_gene_BH)
  Transcript_Cluster_ID Gene_Symbol Fold_Change ANOVA_p.value Adjusted_p.value
1              16845410        ETV4       14.44      8.06e-07       0.02385276
2              17055354        ETV1        4.89      9.20e-05       0.99969993
3              17065367   FAM90A20P       -1.11      1.08e-04       0.99969993
4              16962380        ETV5        4.89      1.93e-04       0.99969993
5              16817824      CORO1A        1.29      2.10e-04       0.99969993
6              16912114    RNU1-23P       -1.42      2.85e-04       0.99969993

The exact same commands on a separate data set (with an identical number of probes, i.e. rows), give me this:
> tail(ZFN_hits)
    Transcript_Cluster_ID Gene_Symbol Fold_Change ANOVA_p.value Adjusted_p.value
546              16890067       CREB1       -1.39      0.001823       0.09868273
547              16913095      CEP250       -1.13      0.001824       0.09868273
548              16891152     ZFAND2B       -1.13      0.001828       0.09871867
549              16914791       SNAI1        1.22      0.001833       0.09880838
550              16979024       PITX2       -1.18      0.001837       0.09884396
551              16872760         ERF       -1.33      0.001850       0.09936279

I used tail to show that, in this case, higher p-values have lower adjusted p-values compared to above, even though the two datasets are of equal length. Also, in case it matters (I've been reading conflicting reports), the p-values were already sorted in CRISPR_gene. Can anyone tell me why this is happening? Am I just not grasping how the BH adjustment really works, or am I doing something wrong?
Thanks in advance,
Veronique


text:
Q: What is the difference between 'satisfied life' and 'satisfying life'? I have found 'satisfying life' is more frequently used than 'satisfied life.'
What is the difference between them?

A: 'Satisfying' is a present participle and works as an adjective. 'Satisfied' is a past participle and functions as an adjective.
boiling- present participle, boiled- past participle
boiling water- Water is continuing to boil. boiled water- Water has been boiled.
satisfying life- Life is continuing to satisfy. satisfied life- Life has been satisfied.

A: When you look at them, they both appear kind of the same.
But, a "satisfying life" means the person living that life is continually satisfied in that life as opposed to a "satisfied life" which indicates the life was satisfactory at one point of time but not so anymore.
Consider these examples.

*

*"The money is good these days. I have a satisfying life".

*"I have had a satisfied life. But after my dog died, it became hellish."


text:
Q: jQuery Parent change inner HTML I got this so far:
$('.event-tools a').click(function()
{
    var status = $(this).attr('id');
    var id = $(this).parent().attr('id');

    $.ajax({
        type: "GET",
        url: "http://localhost:8888/update/test.php",
        data: "rsvp=" + status + '&id=' + id,
        success: function()
        {
            $(this).parent().html(status);
            //alert(status);
        },
        error: function()
        {
            alert('failz');
        }
    });
});

With this:

    Attending
    Maybe Attending
    Not Attending

When I click on one of them and use the alert() it works by prompting the alert box, however, when I use the $(this).parent().html(status); on the success: event, it doesn't change the HTML with the status...

A: this inside your success-function does not have the same scope as outside of it, since JavaScript has function scope. You need to do something like this to preserve the original value of the outer function's this:
var self = this;
$.ajax({
    // ...
    success: function() {
        $(self).parent().html(status);
    }
});

Alternatively, you could use jQuery's .proxy()-method:
$.ajax({
    // ...
    success: $.proxy(function() {
        $(this).parent().html(status);
    }, this)
});

A: try this
JS:
$('.event-tools a').click(function(ev)
{
    ev.stopPropagation()

    var status = $(this).attr('id'),
        id = $(this).parent().attr('id'),
        myparent = $(this).parent();

    $.ajax({
        type: "GET",
        url: "http://localhost:8888/update/test.php",
        data: "rsvp=" + status + '&id=' + id,
        success: function()
        {
            $(myparent).parent().html(status);
            //alert(status);
        },
        error: function()
        {
            alert('failz');
        }
    });
    return false;
});

HTML:

    Attending
    Maybe Attending
    Not Attending


text:
Q: Column width issue with jQuery DataTables and jQuery UI Accordion I'm using DataTables with a jQuery UI accordion.
I have code which fills the Datatable with data (vis json) when the accordion section is opened, but this doesn't align the header correctly.

Table definition
        $('#tblSuppContacts').dataTable({
              "autoWidth":false
            , "footer": false
            , "info":false
            , "JQueryUI":true
            , "language": {"emptyTable":"No Contacts For Supplier"}
            , "ordering":true
            , "paging":false
            , "scrollY":"325px"
            , "scrollCollapse": true
            , "columnDefs": [
                        { className: "LeftNoWrap", "targets": [ 1,2,3,4,5,6,7 ] }
                    ,   { className: "RightNoWrap", "targets": [ 0 ] }
                ]
        });

This is the code which fires when the accordion section opens which checks if the table has any rows before reading it.
var table = $('#tblSuppAddress').DataTable();
if ( ! table.data().any() ) {fncSuppAddressRead();}

Then this codes loads the data into the table.
    if ( $.fn.DataTable.isDataTable('#tblSuppContacts') ) {
        $('#tblSuppContacts').DataTable().clear();
    }

    var dTable = $('#tblSuppContacts').DataTable();

    for (var i = 0; i < pData.length; i++) {
        dTable.row.add([
             fncFormatNumber(pData[i].REF,0,"N")
            ,trim(pData[i].NAME)
            ,trim(pData[i].DEPARTMENT)
            ,trim(pData[i].POSITION)
            ,trim(pData[i].PHONE)
            ,trim(pData[i].FAX)
            ,trim(pData[i].COMMENT)
            ,trim(pData[i].EMAIL)
        ]);
    }
    $('#tblSuppContacts').DataTable().draw();
}

When i click on the table header, the columns headers then line up correctly with the data columns.

A: Use the code below to force jQuery DataTables to recalculate column widths for initially hidden table when accordion content becomes visible.
$(".accordion").accordion({
   activate: function( event, ui ) {
      $($.fn.dataTable.tables(true)).DataTable()
         .columns.adjust();
   }
});

See jQuery DataTables: Column width issues with Bootstrap tabs for more information, examples and details.


text:
Q: Testar a interação com o html e JavaScript utilizando o Jasmine é errado? O código em JavaScript possui algumas interações com o html como esse exemplo:
function retornaListaDeItens(argument) {
  return document.getElementsByClassName(argument);
}

Utilizo o retorno dessa função para a realização de operações no JavaScript, realizando os teste de unidade utilizando o Jasmine acabei me deparando com o seguinte cenário de dúvidas:

*

*É errado realizar o teste dessa função?

*É possível simular o meu html para realizar testes que fazem interações com ele?
A estrutura do teste utiliza o próprio arquivo SpecRunner.html do Jasmine e não tem contato com o html onde possui a lista de itens a ser retornada nesse exemplo, isso acaba dificultando os testes de unidade.
A estrutura esta mais ou menos assim:
app
  lib
  --bootstrap
  --jasmine
  src
  --css
  --js
    --teste.js
  test
  --testeSpec.js
  index.html

A ideia de teste é assim:
  it("retorno de lista de itens não deve ser vazio", function() {
    var item = "item";
    var list = retornaListaDeItens(item);
    console.log(list.length);
    expect(list).not.toBeLessThan(0);
  });

A: Ví que resolveu o problema e fico feliz por isso, mas ainda sim a necessidade de fazer testes reais na aplicação existe em muitos casos.
Caso você queira testar uma aplicação como um usuário (simular ações no HTML e esperar os retornos para verificar se estão corretos) você pode usar alguma lib para auxiliar no que chamamos de testes e2e (end to end).
Esses testes são mais trabalhosos e mais lentos, porém buscam emular exatamente as ações de um usuário dentro do sistema.
Aconselho pesquisar e ler sobre: SeleniumHQ, PhantomJS, WebdriverIO e Chimp.
Confesso que meu conhecimento com esse tipo de testes é bem raso, mas estou estudando e me aprofundando a cada dia e já posso lhe afirmar que para grandes sistemas são muito úteis.
Bons estudos!

EDIT:
Eu não faço meus testes com jasmine, mas sim com MochaJS, aconselho você dar uma olhada também.


text:
Q: Fake modal dialog using Show? My application have several modules, each in one tab on the mainform.
When using a dialog it is convenient to call ShowModal because you know when the dialog is finished. But for the user it is not good as it lock the whole program until the dialog closes.
I want to have a locally modal dialog. So one module can open a dialog and it locks current module only. The user can still switch to another module and continue to work. If the user return to the first module the dialog is there waiting for close before the user can continue to work in that module.
I have to make some kind of framework for this that all dialogs in the application can use.
I have a baseclass for all dialogs TAttracsForm and I think here is the place to add my Show() method.
This should lock access to all wincontrols only in the current module.
It should simulate a call to ShowModal(). How can I achieve this ?
Regards

A: You will have to do the following:

*

*Have an identity for each module

*Have a flag that is active or inactive for each module

*Have a flag that stores the modality of the attached dialog. If it is modal and the module is active, then call the show method in the appropriate eventhandler. Remember to update these values in the onshow and onclose events of each dialog.

You may have to fine tune this suggestion till you achieve the exact functionality that you require.

A: Do you still want to implement this with "you know when the dialog is finished" metaphor?
So like
DoSomethingBeforeDialog();
Form:=TFakeFormDialog.Create(Nil);
try
   Form.FakeShowModal();
finally
  Form.Free;
end;
DoSomethingAfterDialog();

if the answer is yes, you would try to implement this with threads, like Google Chrome do this with tab pages. But without threads only you can catch message processing with a code like this
function TFakeModalDlg.FakeShowModal(FormParent: TWinControl): boolean;
begin
  Parent:=FormParent;
  SetBounds((FormParent.Width - Width) div 2, (FormParent.Height - Height) div 2,
    Width, Height);
  Show;
  while NoButtonIsPressed() do
  begin
    Application.HandleMessage;
  end;
  Hide;
end;

And you even have code below...
Form:=TFakeModalDlg.Create(Nil);
try
  (Sender as TButton).Caption:='Going modal...';
  Form.FakeShowModal(TabSheet1);
  (Sender as TButton).Caption:='Returned from modal';
finally
  Form.Free;
end;

called multiply times from your tabs, but the problem is the these "dialogs" should be closed in "stack order" i.e. reverse to the order they were showed. I think it's impossible to force users to close forms in developers preference order :)

A: I have actually almost implemented local modal dialogs now.
It is built around that when a TForms Enabled property is set To False the whole Form is locked from input. And my modules is just a descendant from TForm.
My ViewManager class that decide what modules is current add/close modules etc got 2 new methods. LockCurrentView and UnLOckCurrentView.
function TViewManager.LockCurrentView: TChildTemplate;
begin
  Result := CurrentView;
  Result.Enabled := False;
  Result.VMDeactivate;         // DeActivate menus and toolbas for this module
end;

procedure TViewManager.UnLockCurrentView(aCallerForm: TChildTemplate);
begin
  aCallerForm.VMActivate;           // Activate menus and toolbas for this module
  aCallerForm.Enabled := True;
end;

TAttracsForm is the baseclass of all dialogs. I Override FormClose and add a new method ShowLocalModal to call instead of ShowModal. I also have to add a TNotifyEvent OnAfterDestruction to be called when the dialog is closed.
procedure TAttracsForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if Assigned(fCallerForm) then
  begin
    ClientMainForm.ViewManager.UnLockCurrentView(fCallerForm as TChildTemplate);

    if Assigned(OnAfterDestruction) then
      OnAfterDestruction(Self);

    Action := caFree;
  end;
end;

{ Call to make a dialog modal per module.
  Limitation is that the creator of the module must be a TChildtemplate.
  Several modal dialogs cannot be stacked with this method.}
procedure TAttracsForm.ShowLocalModal(aNotifyAfterClose: TNotifyEvent);
begin
  fCallerForm := ClientMainForm.ViewManager.LockCurrentView;    // Lock current module and return it
  PopupParent := fCallerForm;
  OnAfterDestruction := aNotifyAfterClose;
  Show;
end;

Some test with simple dialogs looks promising. So the module just have to call ShowLocalModal(myMethod) which have a TNotifyEvent as parameter. This method is called when the dialog is closed.


text:
Q: How to initialize or change values inside of an array in a class? I am working with a class which has an array of characters.
class board
{
   char spot[64];

public:
   board();
   ~board(void);

};

I want to set each of the values in the array to the same character when the program begins how can I initialize there values in the constructor? and is there an easy way to access and allow changes to them by their index?
Thank you,

A: You cannot do this in C++03. However, it is possible to initialize arrays in a constructor initializer list in C++11:
board::board()
: spot { 1, 2, 1, 2, /* ... */ }
{  }

You can either type out the values, or come up with a magic variadic template to provide "N repeated values" (as long as the type is integral). Also, any missing elements are zero-initialized (e.g. char spot[4] { 1, 2 };).
For access, you use spot[i] inside the class, and you can write suitable accessor functions if you need to (though you should always worry if your class is just "forwarding" a member -- really you want your class to encapsulate some higher-order functionality).
If you want to see template code to "initialize an array of N with fixed values", perhaps you should post that as a separate question.

Update: Here is a naive template trick that initializes all array elements to the value 2.
#include <iostream>
#include <utility>
#include <prettyprint.hpp>

class Foo
{
    int arr[10];

    template <typename T, T> struct Filler { };
    template <typename T, bool, unsigned int, T...> struct FillHelper { };

    template <typename T, unsigned int I, T V, T ...Vals>
    Foo(FillHelper<T, true, I, V, Vals...>)
    : arr { V, Vals... } { }

    template <typename T, unsigned int I, T V, T ...Vals>
    Foo(FillHelper<T, false, I, V, Vals...>)
    : Foo(FillHelper<T, I == 1, I - 1, V, V, Vals...>()) { }

    template <typename T, unsigned int N, T V>
    Foo(Filler<T, V>, T const (&)[N])
    : Foo(FillHelper<T, N == 1, N - 1, V>())
    { }

public:
    Foo() : Foo(Filler<int, 2>(), arr)
    {
        std::cout << "Foo: " << arr << "\n";
    }
};

int main()
{
    Foo x;
}

Output: Foo: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

A: to set  all the values in an array to a default value x, you can use something like std::fill_n
for example to set all the elements to -1
    std::fill_n(array, 100, -1);

A:
set each of the values in the array to the same character

Why not using memset ? For example init each of the values to 0x01
board::board()
{
    memset(spot, 0x01, sizeof(spot));
}

A: You can only assign each element using for loop.


text:
Q: How to copy package.json in Dockerfile? I have a problem with copying my package.json to Dockerfile context, here is my files tree:
src
- apps
-- api
--- Dockerfile
- docker
-- tcp
--- docker-compose.yml
- package.json

here is my Dockerfile:
FROM node:14.8.0-alpine as develop

WORKDIR /usr/src/app

COPY ../package.json .
COPY ../yarn.lock .

RUN yarn install

CMD npm run build api&& node dist/apps/api/main

and docker-compose.yml
version: '3'
services:
  api:
    container_name: api-gateway
    build:
      context: ../../apps/api
      dockerfile: ../../apps/api/Dockerfile
    restart: always
    hostname: api
    env_file:
      - ../../.env
    ports:
      - "3000:3000"
    networks:
      - backend

can someone tell me how to copy properly package.json file to resolve below error?
 => ERROR [3/5] COPY ../package.json .                                                                             0.0s
 => ERROR [4/5] COPY ../yarn.lock .                                                                                0.0s
------
 > [3/5] COPY ../package.json .:
------
------
 > [4/5] COPY ../yarn.lock .:
------
failed to compute cache key: "/yarn.lock" not found: not found

thanks for any help!

A: Move docker-compose.yml to the root of the project
Remove the context since it defaults to the current folder and change the Dockerfile path (or move the Dockerfile too since it is not part of your app source code)
build:
  dockerfile: src/apps/api/Dockerfile

Update the env file too
Then copy from the direct context. The container should be responsible for its own yarn lock file, IMO, so don't need to copy that
COPY package.json .

You should also consider adding a .dockerignore for at least node_modules