Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
58,956,907
I have Angular 8 app and I have table: ``` <table> <thead> <tr> <th>...</th> ... </tr> </thead> <tbody> <tr *ngFor="let item of items"> <td (click)="toggleDetails(item)">...</td> <td>...</td> ... </tr> </tbody> </table> <span id="details-row" *ngIf="expandedItem"> <a (click)="convertFile(expandedItem.id, 'pdf')" class="pointer ml-3"> <i class="far fa-file-pdf"></i> Download as PDF </a> </span> ``` in my .ts file I have: ``` toggleDetails(item: any) { this.expandedItem = item; //todo if row isn't clicked -> insert document.getElementById("details-row").innerHTML new table row after row I clicked and angular bindings must work (I mean click handler) //todo if this row is already clicked -> remove this new table row } convertFile(id: number, format: string) { console.log(id); console.log(format); } ``` I can't use multiple `tbody`s. How can I implement my todos? Or are there other ways to implement that?
2019/11/20
[ "https://Stackoverflow.com/questions/58956907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5525734/" ]
A `br` to a block label jumps to the *end* of the contained instruction sequence -- it is a behaves like a `break` statement in C. A `br` to a loop label jumps to the *start* of the contained instruction sequence -- it behaves like a `continue` statement in C. The former enables a *forward* jump, the latter a *backwards* jump. Neither can express the other.
No you can't block has the label at end as it sayed block has the label at the end ``` LOOP START label: SOME CODE IF condtion BR label: EVEN MORE CODE LOOP END ``` Will execute SOME CODE once. Than repeats SOME CODE until condition is not true. And than execute EVEN MORE CODE ``` BLOCK START SOME CODE IF condition BR label: EVEN MORE CODE label: BLOCK END ``` Will execute SOME CODE only once. And than EVEN MORE CODE might be execute when contdtion is not true.
35,521,122
Besides the wrong use of DLLs, when I try to use the `theTestValue` inside the `IntPtr` method the IntelliSense marks it as fail. I would like to know why this is happening because I need to use a `bool` from outside inside this method. ``` public partial class Form1 : Form { [DllImport("user32.dll")] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); private static LowLevelKeyboardProc _proc = HookCallback; private delegate IntPtr LowLevelKeyboardProc( int nCode, IntPtr wParam, IntPtr lParam); public bool theTestValue = false; //This is the value private static IntPtr HookCallback( int nCode, IntPtr wParam, IntPtr lParam) { theTestValue = true; //Red marked } return CallNextHookEx(_hookID, nCode, wParam, lParam); } ```
2016/02/20
[ "https://Stackoverflow.com/questions/35521122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3772108/" ]
You cannot access the field because the method is static and the field has been declared on instance level (not static). If you change the code so that both are either static or not, the error will be gone.
Make `theTestValue` static or remove the static modifier from your HookCallBack function.If the class is declared static all of the members must be static too.
39,961,269
I want to use a thread as an event loop thread. I mean a Java thread with a "QThread like behaviour" (`t2` in the following example). Explanation: I have a thread `t1` (main thread) and a thread `t2` (a worker thread). I want that `method()`, called from `t1`, is executed in `t2` thread. Currently, I made this code (it works, but I don't like it): -Thread **t1** (Main thread, UI thread for example): ``` //... // Here, I want to call "method()" in t2's thread Runnable event = new Runnable() { @Override public void run() { t2.method(param); } }; t2.postEvent(event); //... ``` -Thread **t2**: ``` //... Queue<Runnable> eventLoopQueue = new ConcurrentLinkedQueue<Runnable>(); //... @Override public void run() { //... Runnable currentEvent = null; while (!bMustStop) { while ((currentEvent = eventLoopQueue.poll()) != null) { currentEvent.run(); } } //... } public void method(Param param) { /* code that should be executed in t2's thread */ } public void postEvent(Runnable event) { eventLoopQueue.offer(event); } ``` This solution is ugly. I don't like the "always-working" main loop in `t2`, the new `Runnable` allocation each time in `t1`... My program can call `method` something like 40 times per second, so I need it to be efficient. I'm looking for a solution that should be used on Android too (I know the class [Looper](https://developer.android.com/reference/android/os/Looper.html) for Android, but it's only for Android, so impossible)
2016/10/10
[ "https://Stackoverflow.com/questions/39961269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6523232/" ]
Consider using `BlockingQueue` instead of `Queue` for its method `take()` will block the thread until an element is available on the queue, thus not wasting cycles like `poll()` does.
You could as well synchronize (using synchronized / wait / notify) to wait until a new even is posted. But mentioned in the previous answer, the BlockingQueue could do the job. Just do not forget to interrupt when you plan to quit the thread (in both cases).
39,961,269
I want to use a thread as an event loop thread. I mean a Java thread with a "QThread like behaviour" (`t2` in the following example). Explanation: I have a thread `t1` (main thread) and a thread `t2` (a worker thread). I want that `method()`, called from `t1`, is executed in `t2` thread. Currently, I made this code (it works, but I don't like it): -Thread **t1** (Main thread, UI thread for example): ``` //... // Here, I want to call "method()" in t2's thread Runnable event = new Runnable() { @Override public void run() { t2.method(param); } }; t2.postEvent(event); //... ``` -Thread **t2**: ``` //... Queue<Runnable> eventLoopQueue = new ConcurrentLinkedQueue<Runnable>(); //... @Override public void run() { //... Runnable currentEvent = null; while (!bMustStop) { while ((currentEvent = eventLoopQueue.poll()) != null) { currentEvent.run(); } } //... } public void method(Param param) { /* code that should be executed in t2's thread */ } public void postEvent(Runnable event) { eventLoopQueue.offer(event); } ``` This solution is ugly. I don't like the "always-working" main loop in `t2`, the new `Runnable` allocation each time in `t1`... My program can call `method` something like 40 times per second, so I need it to be efficient. I'm looking for a solution that should be used on Android too (I know the class [Looper](https://developer.android.com/reference/android/os/Looper.html) for Android, but it's only for Android, so impossible)
2016/10/10
[ "https://Stackoverflow.com/questions/39961269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6523232/" ]
Consider using `BlockingQueue` instead of `Queue` for its method `take()` will block the thread until an element is available on the queue, thus not wasting cycles like `poll()` does.
Since Java 1.5 there is an excellent solution provided out of the box for thread pooling. You have a Thread pool to which you can submit a Task for execution. The pool takes a thread and executes your task. Once the task is executed the Thread transparently returns to the pool. Please look at [ExecutorService](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html) interface and all its implementations. Also take a look at [Executors](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html) helper class. This should give you all you need and much more
48,984,780
I just started out with node.js and wanted to do something with nodemailer. I've installed the packages (Oauth2, Express, Body-parser, Node, Nodemailer) using `npm install (package name)` The issues I have are when I try and get information from my HTML form by using `req.body.subject` it gives the error that it req is not defined. (Sending a mail by doing `node app.js` in the cmd works fine and doesn't give any errors) ``` C:\Users\Gebruiker\Desktop\nodemailer\app.js:31 subject: req.body.subject, ^ ReferenceError: req is not defined at Object.<anonymous> (C:\Users\Gebruiker\Desktop\nodemailer\app.js:31:14) at Module._compile (module.js:660:30) at Object.Module._extensions..js (module.js:671:10) at Module.load (module.js:573:32) at tryModuleLoad (module.js:513:12) at Function.Module._load (module.js:505:3) at Function.Module.runMain (module.js:701:10) at startup (bootstrap_node.js:190:16) at bootstrap_node.js:662:3 PS C:\Users\Gebruiker\Desktop\nodemailer> ``` I have this error on my pc and on my server. I have been searching for a answer for a while now and couldn't find a answer for my issue. I am sorry if I did something wrong in this post or that it isn't clear enough I am pretty new on here. The code: HTML form. ``` <html> <head> <script src="app.js"></script> </head> <form action="/send-email" method="post"> <ul class="inputs"> <li> <label for="from">From</label> <input type="text" id="from" name="from" /> </li> <li> <label for="to">To</label> <input type="text" id="to" name="to" /> </li> <li> <label for="subject">Subject</label> <input type="subject" id="subject" name="subject" /> </li> <li> <label for="message">Message</label> <input type="message" id="message" name="message" /> </li> <li> <button>Send Request</button> </li> </ul> </form> </body> </html> ``` Nodemailer code. ``` var nodemailer = require('nodemailer'); var path = require('path'); var bodyParser = require('body-parser'); var express = require('express'); var OAuth2 = require('oauth2'); var app = express(); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.get('/', function (req, res) { res.render('default'); }); const transporter = nodemailer.createTransport({ service: 'Gmail', auth: { type: 'OAuth2', user: 'xxxx@gmail.com', clientId: 'xxxx', clientSecret: 'xxxx', refreshToken: 'xxxx', accessToken: 'xxxx', }, }); var mailOptions = { from: 'Xander <xxxx@gmail.com>', to: req.body.to, subject: req.body.subject, html: 'Hello Planet! <br />Embedded image: <img src="cid: download.jpg"/>', attachments: [{ filename: 'download.jpg', path: 'download.jpg', cid: 'download.jpg' }] } transporter.sendMail(mailOptions, function(err, res){ if(err){ console.log('Mail not sent'); } else { console.log('Mail sent'); } }); ``` I am sorry if the answer to this question is really simple and easy, this is my first real thing I am trying to do with nodemailer and node.js.
2018/02/26
[ "https://Stackoverflow.com/questions/48984780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9391401/" ]
You don't have to revert your code back to using `$scope` since using controller as syntax is better ([See advantages](https://stackoverflow.com/questions/32755929/what-is-the-advantage-of-controller-as-in-angular)). You have to bind not only your `ng-model` but also your `ng-submit` to your controller instance `subscription`. ```js var app = angular.module('myApp', []) app.controller('SubscriptionCtrl', function() { var subscription = this; subscription.redeem = function() { console.log(subscription.accessCode) } }) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="SubscriptionCtrl as subscription"> <form ng-submit="subscription.redeem()"> <input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="subscription.accessCode" /> <input type="submit" class="btn btn-dark-green" value="Indløs" /> </form> </div> </div> ```
> > I think you forget to add the controller `as` section with `ng-model`, > because you used: > > > ``` ng-controller="SubscriptionCtrl as subscription" ``` > > So, in your ng-model, you have to use: > > > ``` ng-model="subscription.accessCode" ``` > > Also change `ng-submit="redeem()"` to > `ng-submit="subscription.redeem()"` > > > So, the HTML section will be as follows: > > > ``` <form ng-submit="subscription.redeem()" ng-controller="SubscriptionCtrl as subscription"> <input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="subscription.accessCode" /> <input type="submit" class="btn btn-dark-green" value="Indløs" /> </form> ``` > > In controller side implement as follows: > > > ``` //creating a module var app = angular.module("app",[]); //registering the above controller to the module app.controller("SubscriptionCtrl",['$scope',function ($scope){ $scope.accessCode = ""; $scope.redeem = function () { console.log($scope.accessCode); }; }]); ```
48,984,780
I just started out with node.js and wanted to do something with nodemailer. I've installed the packages (Oauth2, Express, Body-parser, Node, Nodemailer) using `npm install (package name)` The issues I have are when I try and get information from my HTML form by using `req.body.subject` it gives the error that it req is not defined. (Sending a mail by doing `node app.js` in the cmd works fine and doesn't give any errors) ``` C:\Users\Gebruiker\Desktop\nodemailer\app.js:31 subject: req.body.subject, ^ ReferenceError: req is not defined at Object.<anonymous> (C:\Users\Gebruiker\Desktop\nodemailer\app.js:31:14) at Module._compile (module.js:660:30) at Object.Module._extensions..js (module.js:671:10) at Module.load (module.js:573:32) at tryModuleLoad (module.js:513:12) at Function.Module._load (module.js:505:3) at Function.Module.runMain (module.js:701:10) at startup (bootstrap_node.js:190:16) at bootstrap_node.js:662:3 PS C:\Users\Gebruiker\Desktop\nodemailer> ``` I have this error on my pc and on my server. I have been searching for a answer for a while now and couldn't find a answer for my issue. I am sorry if I did something wrong in this post or that it isn't clear enough I am pretty new on here. The code: HTML form. ``` <html> <head> <script src="app.js"></script> </head> <form action="/send-email" method="post"> <ul class="inputs"> <li> <label for="from">From</label> <input type="text" id="from" name="from" /> </li> <li> <label for="to">To</label> <input type="text" id="to" name="to" /> </li> <li> <label for="subject">Subject</label> <input type="subject" id="subject" name="subject" /> </li> <li> <label for="message">Message</label> <input type="message" id="message" name="message" /> </li> <li> <button>Send Request</button> </li> </ul> </form> </body> </html> ``` Nodemailer code. ``` var nodemailer = require('nodemailer'); var path = require('path'); var bodyParser = require('body-parser'); var express = require('express'); var OAuth2 = require('oauth2'); var app = express(); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.get('/', function (req, res) { res.render('default'); }); const transporter = nodemailer.createTransport({ service: 'Gmail', auth: { type: 'OAuth2', user: 'xxxx@gmail.com', clientId: 'xxxx', clientSecret: 'xxxx', refreshToken: 'xxxx', accessToken: 'xxxx', }, }); var mailOptions = { from: 'Xander <xxxx@gmail.com>', to: req.body.to, subject: req.body.subject, html: 'Hello Planet! <br />Embedded image: <img src="cid: download.jpg"/>', attachments: [{ filename: 'download.jpg', path: 'download.jpg', cid: 'download.jpg' }] } transporter.sendMail(mailOptions, function(err, res){ if(err){ console.log('Mail not sent'); } else { console.log('Mail sent'); } }); ``` I am sorry if the answer to this question is really simple and easy, this is my first real thing I am trying to do with nodemailer and node.js.
2018/02/26
[ "https://Stackoverflow.com/questions/48984780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9391401/" ]
You don't have to revert your code back to using `$scope` since using controller as syntax is better ([See advantages](https://stackoverflow.com/questions/32755929/what-is-the-advantage-of-controller-as-in-angular)). You have to bind not only your `ng-model` but also your `ng-submit` to your controller instance `subscription`. ```js var app = angular.module('myApp', []) app.controller('SubscriptionCtrl', function() { var subscription = this; subscription.redeem = function() { console.log(subscription.accessCode) } }) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="SubscriptionCtrl as subscription"> <form ng-submit="subscription.redeem()"> <input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="subscription.accessCode" /> <input type="submit" class="btn btn-dark-green" value="Indløs" /> </form> </div> </div> ```
Try this .. Might have missed `module` name in html. **In `app.js` :** ``` var app = angular.module('myApp', []); app.controller('SubscriptionCtrl', function($scope) { console.log($scope.accessCode); ..... }); ``` Instead of using `as` . **Directly inject the $scope into the controller.** **In HTML:** ``` <body ng-app="myApp"> <form ng-submit="redeem(collection.Id)" ng-controller="SubscriptionCtrl"> <input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="accessCode" /> <input type="submit" class="btn btn-dark-green" value="Indløs" /> </form> </body> ``` Follow [ng-controller](https://docs.angularjs.org/api/ng/directive/ngController) Hope it helps..!
4,341,848
``` var adList = new Array(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ``` I'm getting an error `adList[0] is undefined`, can I not define arrays like this? Do I have to specify `adList[0]` as an array before I assign variables to it?
2010/12/03
[ "https://Stackoverflow.com/questions/4341848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
You must do: ``` adList[0] = new Array(); ``` in similar fashion to how you created adList itself.
Yyou have to specify what the arrays contains before you can start doing stuff with it. Its just like trying to use any other uninitialized variable. ``` var adList = new Array(); sizeOfArray = 5; for (var i=0; i < sizeOfArray; i++) { adList[i] = new Array(); } adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; ``` This will initialize the contents of adList at 0-4 with arrays. THEN you can go on assigning their values. Note that `adList[0]["img"]` doesn't actually use the arrays' indexes. Since the array is an object, it lets you set its properties anyway. This is the same as `adList[0].img`.
4,341,848
``` var adList = new Array(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ``` I'm getting an error `adList[0] is undefined`, can I not define arrays like this? Do I have to specify `adList[0]` as an array before I assign variables to it?
2010/12/03
[ "https://Stackoverflow.com/questions/4341848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
The problem is that you're trying to refer to `adList[0]` which hasn't had a value assigned to it. So when you try to access the value of `adList[0]['img']`, this happens: ``` adList -> Array adList[0] -> undefined adList[0]["img"] -> Error, attempting to access property of undefined. ``` Try using array and object literal notation to define it instead. ``` adList = [{ img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', h3: 'Product title 1', button: { text: 'Buy now', url: '#link-url' } }, { img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', h3: 'Product title 2', button: { text: 'Buy now', url: '#link-url' } }]; ``` Or you can simply define `adList[0]` and `adList[1]` separately and use your old code: ``` var adList = new Array(); adList[0] = {}; adList[1] = {}; adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; ... etc etc ```
You must do: ``` adList[0] = new Array(); ``` in similar fashion to how you created adList itself.
4,341,848
``` var adList = new Array(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ``` I'm getting an error `adList[0] is undefined`, can I not define arrays like this? Do I have to specify `adList[0]` as an array before I assign variables to it?
2010/12/03
[ "https://Stackoverflow.com/questions/4341848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
You must do: ``` adList[0] = new Array(); ``` in similar fashion to how you created adList itself.
Your problem is that `adList[0]` and `adList[1]` have not been inititalized. This has nothing to do with `adList` being an Array. So, `adList[0] = new Object();` before assigning property values should work for what you are trying to do. ``` var adList = new Array(); adList[0] = new Object(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1] = new Object(); adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ```
4,341,848
``` var adList = new Array(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ``` I'm getting an error `adList[0] is undefined`, can I not define arrays like this? Do I have to specify `adList[0]` as an array before I assign variables to it?
2010/12/03
[ "https://Stackoverflow.com/questions/4341848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
The problem is that you're trying to refer to `adList[0]` which hasn't had a value assigned to it. So when you try to access the value of `adList[0]['img']`, this happens: ``` adList -> Array adList[0] -> undefined adList[0]["img"] -> Error, attempting to access property of undefined. ``` Try using array and object literal notation to define it instead. ``` adList = [{ img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', h3: 'Product title 1', button: { text: 'Buy now', url: '#link-url' } }, { img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', h3: 'Product title 2', button: { text: 'Buy now', url: '#link-url' } }]; ``` Or you can simply define `adList[0]` and `adList[1]` separately and use your old code: ``` var adList = new Array(); adList[0] = {}; adList[1] = {}; adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; ... etc etc ```
Yyou have to specify what the arrays contains before you can start doing stuff with it. Its just like trying to use any other uninitialized variable. ``` var adList = new Array(); sizeOfArray = 5; for (var i=0; i < sizeOfArray; i++) { adList[i] = new Array(); } adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; ``` This will initialize the contents of adList at 0-4 with arrays. THEN you can go on assigning their values. Note that `adList[0]["img"]` doesn't actually use the arrays' indexes. Since the array is an object, it lets you set its properties anyway. This is the same as `adList[0].img`.
4,341,848
``` var adList = new Array(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ``` I'm getting an error `adList[0] is undefined`, can I not define arrays like this? Do I have to specify `adList[0]` as an array before I assign variables to it?
2010/12/03
[ "https://Stackoverflow.com/questions/4341848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
You can also use object notation: ``` adList = [ { "img": 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', "h3": 'Product title2', "button": {"link": '#link-url', "text": 'Buy now'}, "h3": 'asdfasdfasdf' }, { "img": 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', "h3": 'Product title2', "button": {"link": '#link-url', "text": 'Buy now'}, "h3": 'asdfasdfasdf' }]; ```
Yyou have to specify what the arrays contains before you can start doing stuff with it. Its just like trying to use any other uninitialized variable. ``` var adList = new Array(); sizeOfArray = 5; for (var i=0; i < sizeOfArray; i++) { adList[i] = new Array(); } adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; ``` This will initialize the contents of adList at 0-4 with arrays. THEN you can go on assigning their values. Note that `adList[0]["img"]` doesn't actually use the arrays' indexes. Since the array is an object, it lets you set its properties anyway. This is the same as `adList[0].img`.
4,341,848
``` var adList = new Array(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ``` I'm getting an error `adList[0] is undefined`, can I not define arrays like this? Do I have to specify `adList[0]` as an array before I assign variables to it?
2010/12/03
[ "https://Stackoverflow.com/questions/4341848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
The problem is that you're trying to refer to `adList[0]` which hasn't had a value assigned to it. So when you try to access the value of `adList[0]['img']`, this happens: ``` adList -> Array adList[0] -> undefined adList[0]["img"] -> Error, attempting to access property of undefined. ``` Try using array and object literal notation to define it instead. ``` adList = [{ img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', h3: 'Product title 1', button: { text: 'Buy now', url: '#link-url' } }, { img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', h3: 'Product title 2', button: { text: 'Buy now', url: '#link-url' } }]; ``` Or you can simply define `adList[0]` and `adList[1]` separately and use your old code: ``` var adList = new Array(); adList[0] = {}; adList[1] = {}; adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; ... etc etc ```
You can also use object notation: ``` adList = [ { "img": 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', "h3": 'Product title2', "button": {"link": '#link-url', "text": 'Buy now'}, "h3": 'asdfasdfasdf' }, { "img": 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', "h3": 'Product title2', "button": {"link": '#link-url', "text": 'Buy now'}, "h3": 'asdfasdfasdf' }]; ```
4,341,848
``` var adList = new Array(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ``` I'm getting an error `adList[0] is undefined`, can I not define arrays like this? Do I have to specify `adList[0]` as an array before I assign variables to it?
2010/12/03
[ "https://Stackoverflow.com/questions/4341848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
The problem is that you're trying to refer to `adList[0]` which hasn't had a value assigned to it. So when you try to access the value of `adList[0]['img']`, this happens: ``` adList -> Array adList[0] -> undefined adList[0]["img"] -> Error, attempting to access property of undefined. ``` Try using array and object literal notation to define it instead. ``` adList = [{ img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', h3: 'Product title 1', button: { text: 'Buy now', url: '#link-url' } }, { img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', h3: 'Product title 2', button: { text: 'Buy now', url: '#link-url' } }]; ``` Or you can simply define `adList[0]` and `adList[1]` separately and use your old code: ``` var adList = new Array(); adList[0] = {}; adList[1] = {}; adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; ... etc etc ```
Your problem is that `adList[0]` and `adList[1]` have not been inititalized. This has nothing to do with `adList` being an Array. So, `adList[0] = new Object();` before assigning property values should work for what you are trying to do. ``` var adList = new Array(); adList[0] = new Object(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1] = new Object(); adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ```
4,341,848
``` var adList = new Array(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ``` I'm getting an error `adList[0] is undefined`, can I not define arrays like this? Do I have to specify `adList[0]` as an array before I assign variables to it?
2010/12/03
[ "https://Stackoverflow.com/questions/4341848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
You can also use object notation: ``` adList = [ { "img": 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', "h3": 'Product title2', "button": {"link": '#link-url', "text": 'Buy now'}, "h3": 'asdfasdfasdf' }, { "img": 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', "h3": 'Product title2', "button": {"link": '#link-url', "text": 'Buy now'}, "h3": 'asdfasdfasdf' }]; ```
Your problem is that `adList[0]` and `adList[1]` have not been inititalized. This has nothing to do with `adList` being an Array. So, `adList[0] = new Object();` before assigning property values should work for what you are trying to do. ``` var adList = new Array(); adList[0] = new Object(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1] = new Object(); adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ```
65,018,327
I am a beginner on React and am working on a project but I could not pass this error, I looked through similar topics, but still couldn't fix the problem, I will be glad if you guys help me! --- > > ERROR Invariant Violation: The navigation prop is missing for this > navigator. In react-navigation v3 and v4 you must set up your app > container directly. More info: > <https://reactnavigation.org/docs/en/app-containers.html> This error is > located at: > in Navigator (at MainComponent.js:81) > in RCTView (at View.js:34) > in View (at MainComponent.js:80) > in Main (at App.js:7) > in App (at renderApplication.js:45) > in RCTView (at View.js:34) > in View (at AppContainer.js:106) > in RCTView (at View.js:34) > in View (at AppContainer.js:132) > in AppContainer (at renderApplication.js:39) > > > --- **MainComponent.js** ```html import React, { Component } from 'react'; import Menu from './MenuComponent'; import Home from './HomeComponent'; import Dishdetail from './DishdetailComponent'; import { View } from 'react-native'; import 'react-native-gesture-handler'; import { createStackNavigator } from 'react-navigation-stack'; import { createDrawerNavigator } from 'react-navigation-drawer'; import { DISHES } from '../shared/dishes'; const MenuNavigator = createStackNavigator({ Menu: { screen: Menu }, Dishdetail: { screen: Dishdetail } }, { initialRouteName: 'Menu', navigationOptions: { headerStyle: { backgroundColor: "#512DA8" }, headerTintColor: '#fff', headerTitleStyle: { color: "#fff" } } } ); const HomeNavigator = createStackNavigator({ Home: { screen: Home } }, { navigationOptions: { headerStyle: { backgroundColor: "#512DA8" }, headerTitleStyle: { color: "#fff" }, headerTintColor: "#fff" } }); const MainNavigator = createDrawerNavigator({ Home: { screen: HomeNavigator, navigationOptions: { title: 'Home', drawerLabel: 'Home' } }, Menu: { screen: MenuNavigator, navigationOptions: { title: 'Menu', drawerLabel: 'Menu' }, } }, { drawerBackgroundColor: '#D1C4E9' }); class Main extends Component { constructor(props) { super(props); this.state = { dishes: DISHES, selectedDish: null }; } onDishSelect(dishId) { this.setState({selectedDish: dishId}) } render() { return ( <View style={{flex:1, paddingTop: 10}}> <MainNavigator /> </View> ); } } export default Main; ``` This is the Error SS: [![enter image description here](https://i.stack.imgur.com/UyUEq.png)](https://i.stack.imgur.com/UyUEq.png)
2020/11/26
[ "https://Stackoverflow.com/questions/65018327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14374677/" ]
Use dense\_rank instead row\_number ``` SELECT * FROM (SELECT Indicator, ReportedDate, dense_rank() OVER(PARTITION BY (select 1) ORDER BY ReportedDate desc) as periods FROM @t) a where periods <= 2 ```
What if: ``` declare @t table (Indicator decimal(37,12), ReportedDate datetime) insert into @t select 0.2917 , cast('2020-08-12 00:00:00' as datetime) union select 0.261919 , cast('2020-08-13 00:00:00' as datetime) union select 0.259211 , cast('2020-08-14 00:00:00' as datetime) union select 0.201075 , cast('2020-08-17 00:00:00' as datetime) union select 0.250153 , cast('2020-08-18 00:00:00' as datetime) union select 0.333093 , cast('2020-08-19 00:00:00' as datetime) union select 0.976495 , cast('2020-08-20 00:00:00' as datetime) union select 0.759739 , cast('2020-08-21 00:00:00' as datetime) union select 1.17279 , cast('2020-08-24 00:00:00' as datetime) union select 0.285365, cast('2020-08-25 00:00:00' as datetime) select top 3 * from @t order by 2 desc ```
28,884,115
I'm facing some problems launching my rails app hosted on bluehost. I think that the problem is the passenger version interacting with the rails 4 app but I'm not sure. When I launch my app I get this trace: ``` Ruby (Rack) application could not be started These are the possible causes: There may be a syntax error in the application's code. Please check for such errors and fix them. A required library may not installed. Please install all libraries that this application requires. The application may not be properly configured. Please check whether all configuration files are written correctly, fix any incorrect configurations, and restart this application. A service that the application relies on (such as the database server or the Ferret search engine server) may not have been started. Please start that service. Further information about the error may have been written to the application's log file. Please check it in order to analyse the problem. Error message: Could not initialize MySQL client library Exception class: RuntimeError Application root: /home5/barracam/rails_apps/admin/admin Backtrace: # File Line Location 0 /home5/barracam/ruby/gems/gems/mysql2-0.3.18/lib/mysql2.rb 31 in `require' 1 /home5/barracam/ruby/gems/gems/mysql2-0.3.18/lib/mysql2.rb 31 in `' 2 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 72 in `require' 3 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 72 in `block (2 levels) in require' 4 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 70 in `each' 5 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 70 in `block in require' 6 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 59 in `each' 7 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 59 in `require' 8 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler.rb 132 in `require' 9 /home5/barracam/rails_apps/admin/admin/config/application.rb 7 in `' 10 /home5/barracam/rails_apps/admin/admin/config/environment.rb 2 in `require' 11 /home5/barracam/rails_apps/admin/admin/config/environment.rb 2 in `' 12 config.ru 3 in `require' 13 config.ru 3 in `block in' 14 /home5/barracam/ruby/gems/gems/rack-1.5.2/lib/rack/builder.rb 55 in `instance_eval' 15 /home5/barracam/ruby/gems/gems/rack-1.5.2/lib/rack/builder.rb 55 in `initialize' 16 config.ru 1 in `new' 17 config.ru 1 in `' 18 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 225 in `eval' 19 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 225 in `load_rack_app' 20 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 157 in `block in initialize_server' 21 /etc/httpd/modules/passenger/lib/phusion_passenger/utils.rb 563 in `report_app_init_status' 22 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 154 in `initialize_server' 23 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 204 in `start_synchronously' 24 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 180 in `start' 25 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 129 in `start' 26 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 253 in `block (2 levels) in spawn_rack_application' 27 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server_collection.rb 132 in `lookup_or_add' 28 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 246 in `block in spawn_rack_application' 29 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server_collection.rb 82 in `block in synchronize' 30 prelude> 10:in `synchronize' 31 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server_collection.rb 79 in `synchronize' 32 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 244 in `spawn_rack_application' 33 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 137 in `spawn_application' 34 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 275 in `handle_spawn_application' 35 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 357 in `server_main_loop' 36 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 206 in `start_synchronously' 37 /etc/httpd/modules/passenger/helper-scripts/passenger-spawn-server 99 in `' Powered by Phusion Passenger, mod_rails / mod_rack for Apache and Nginx. ``` I tried to run a rails 3 app and all works fine. What do you think about the problem? Any help is really appreciated.
2015/03/05
[ "https://Stackoverflow.com/questions/28884115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/677210/" ]
I was getting the same error, so after a lot of research, and trial and error.... I locked my mysql2 gem at version 3.0.16, and set up my database.yml like so: ``` adapter: mysql2 encoding: utf8 database: store username: root password: host: localhost reconnect: true port: 3306 ``` My app is running rails on 4.20, and works fine now. (although it still has sporadic trouble connecting to the mysql db? maybe the bluest server gets overloaded? there is no real pattern, and it doesn't happen all that often.
try to change the database.yml Use `mysql` instead `mysql2` adapter
33,921
Do qualia have an evolutionary function, and if so what is it? Could qualia help us solve problems that Turing machines can't solve? Could qualia help us solve problems faster than normal computers? Our brain often works like a general problem solving machine. Could qualia have evolved to optimize this machine? Could evolution limit it to solving only the problems that our genes are "interested" in? Could qualia have other purposes?
2016/05/01
[ "https://philosophy.stackexchange.com/questions/33921", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/20480/" ]
Qualia are supposed to be (by definition) not the causes of any physical events, hence there is no way that they could enter into evolutionary or any other kinds of scientific explanation of a phenomenon. For instance, imagine there were ghosts which simply couldn't cause any events in the physical world--couldn't rattle any chains, nor even appear to anybody to scare them. Such ghosts could not even in principle enter in to any scientific account of a phenomenon. **Edit** I've received several down votes on this answer, which surprises me, since my answer is clearly correct. Let me quote some evidence. I'll start with an excellent introduction to the philosophy of mind. > > "If qualia cannot be physically described or explained, then they are not part of the network of physical causal relations that are responsible for human behavior. If qualia are not part of that causal network, however, then they make no causal contribution to human behavior." Jaworski, "Philosophy of Mind: An Introduction" Blackwell 2011, p. 213 > > > Somebody in the comment thread below says that Jaworski, a professional philosopher of mind who published a peer-reviewed book on the subject with a reputable publisher is just wrong about the definition of "qualia." Ok, so let's look and see what other scholars in standard, peer-reviewed reference works thing. > > "... this response does not apply to those philosophers who take the view that qualia are irreducible, non-physical entities [e.g. Chalmers, Frank Jackson, etc.]. **However, these philosophers have other severe problems of their own. In particular, they face the problem of phenomenal causation. Given the causal closure of the physical, how can qualia make any difference?** For more here, see Tye 1995, Chalmers 1996).'' Michael Tye, in the [SEP article on Qualia.](http://plato.stanford.edu/entries/qualia/#Uses) > > > The implied answer of the question is: "They can't." Nobody who believes in qualia should count as a physicalist, but rejecting physicalism is not the same thing as rejecting the causal closure of the physical world. Rejecting closure isn't just rejecting physicalism, it's opening the door back up to straightforward substance dualism where my mental properties cause physical events by pushing my pineal gland around or something. But, hey, maybe the entire scholarly community has gotten Chalmers and company wrong. Maybe Chalmers has simply been slighted by careless, slapdash slanders by wild eyed physicalists who cannot stand to hear their theories contradicted. So, let's look and see what Chalmers himself says about whether qualia have causal powers. > > "A problem with the view that I have advocated is that if consciousness is merely naturally supervenient upon the physical, then it seems to lack causal efficacy. The physical world is more or less causally closed, in that for any given physical event, it seems that there is a physical explanation of (modulo a small amount of quantum indeterminacy). This implies that there is no room for a nonphysical consciousness to do any independent causal work. It seems to be a mere epiphenomenon, hanging off the engine of physical causation, but making no difference in the physical world." David Chalmers, *The Conscious Mind: In Search of a Fundamental Theory,* Oxford University Press, 1996, p. 150. > > > Chalmers does go on to suggest ways in which he will try to avoid, or at least soften the blow, of having to make qualia epiphenomenal, but whether those responses are successful is a matter of further scholarly controversy. For my money, I don't think any of his proposed fixes, like endorsing causal overdetermination, or extreme humeanism about causation look even remotely plausible. I would love for people who are still down voting to explain in the comments exactly what kind of evidence they think would be necessary to prove the claim at issue here. Remember, the issue at stake is not the *empirical* question, "Do psychological states have causal powers?" but rather "Could qualia, those theoretical posits whose properties are stipulated by their use in the philosophy of mind of David Chalmers, Frank Jackson, et al., have causal powers?"
Qualia are either isomorphic to (if you're a dualist) or identical to (if you're a materialist) computational data structures. Take the simplest example, the visual field. The visual field is very similar to a PNG file. Any computation that could be done with the visual field could be done just as well with a PNG file. Most qualia are things like sensory experience, emotions, pleasure and pain. These things are not functional parts of a "general problem solving machine", but rather inputs to a problem solving machine.
33,921
Do qualia have an evolutionary function, and if so what is it? Could qualia help us solve problems that Turing machines can't solve? Could qualia help us solve problems faster than normal computers? Our brain often works like a general problem solving machine. Could qualia have evolved to optimize this machine? Could evolution limit it to solving only the problems that our genes are "interested" in? Could qualia have other purposes?
2016/05/01
[ "https://philosophy.stackexchange.com/questions/33921", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/20480/" ]
I will assume that we all do have subjective experiences which correspond precisely to the information encoded by specific objective brain states, and that the particular subjective qualities which identify different experiences may safely be referred to as qualia, a set of assumptions which some philosophers doubt. A common tenet of qualia theory is that our objective brain states are driven by the laws of physics, via objective physical processes, and that our subjective or conscious experience of those brain states merely rides on the back of that. Some, such as Daniel Dennett, hold that such a concept as qualia is therefore worthless; the brain states are all we need concern ourselves with. Others point to the ''sine qua non'' presence of qualia in the mind of every conscious philosopher and may even suggest that this provides unarguable evidence of a metaphysical aspect to the human mind. Either way, on this basis the evolution of the brain's rational capabilities is driven by broadly Darwinian evolution and consciousness of such reasoning just comes along for the ride. Modern information theory is beginning to bring another level of sophistication to the argument. For example [Integrated Information Theory](https://en.wikipedia.org/wiki/Integrated_information_theory) explicitly treats the information flows in the brain as the seat of consciousness, with the physiology and activity of the brain serving only to support sufficiently complex information. This must surely have profound consequences, for example the laws of physics never lie but semantic information often does, but I have not seen this aspect developed anywhere yet.
Qualia are either isomorphic to (if you're a dualist) or identical to (if you're a materialist) computational data structures. Take the simplest example, the visual field. The visual field is very similar to a PNG file. Any computation that could be done with the visual field could be done just as well with a PNG file. Most qualia are things like sensory experience, emotions, pleasure and pain. These things are not functional parts of a "general problem solving machine", but rather inputs to a problem solving machine.
33,921
Do qualia have an evolutionary function, and if so what is it? Could qualia help us solve problems that Turing machines can't solve? Could qualia help us solve problems faster than normal computers? Our brain often works like a general problem solving machine. Could qualia have evolved to optimize this machine? Could evolution limit it to solving only the problems that our genes are "interested" in? Could qualia have other purposes?
2016/05/01
[ "https://philosophy.stackexchange.com/questions/33921", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/20480/" ]
Qualia are supposed to be (by definition) not the causes of any physical events, hence there is no way that they could enter into evolutionary or any other kinds of scientific explanation of a phenomenon. For instance, imagine there were ghosts which simply couldn't cause any events in the physical world--couldn't rattle any chains, nor even appear to anybody to scare them. Such ghosts could not even in principle enter in to any scientific account of a phenomenon. **Edit** I've received several down votes on this answer, which surprises me, since my answer is clearly correct. Let me quote some evidence. I'll start with an excellent introduction to the philosophy of mind. > > "If qualia cannot be physically described or explained, then they are not part of the network of physical causal relations that are responsible for human behavior. If qualia are not part of that causal network, however, then they make no causal contribution to human behavior." Jaworski, "Philosophy of Mind: An Introduction" Blackwell 2011, p. 213 > > > Somebody in the comment thread below says that Jaworski, a professional philosopher of mind who published a peer-reviewed book on the subject with a reputable publisher is just wrong about the definition of "qualia." Ok, so let's look and see what other scholars in standard, peer-reviewed reference works thing. > > "... this response does not apply to those philosophers who take the view that qualia are irreducible, non-physical entities [e.g. Chalmers, Frank Jackson, etc.]. **However, these philosophers have other severe problems of their own. In particular, they face the problem of phenomenal causation. Given the causal closure of the physical, how can qualia make any difference?** For more here, see Tye 1995, Chalmers 1996).'' Michael Tye, in the [SEP article on Qualia.](http://plato.stanford.edu/entries/qualia/#Uses) > > > The implied answer of the question is: "They can't." Nobody who believes in qualia should count as a physicalist, but rejecting physicalism is not the same thing as rejecting the causal closure of the physical world. Rejecting closure isn't just rejecting physicalism, it's opening the door back up to straightforward substance dualism where my mental properties cause physical events by pushing my pineal gland around or something. But, hey, maybe the entire scholarly community has gotten Chalmers and company wrong. Maybe Chalmers has simply been slighted by careless, slapdash slanders by wild eyed physicalists who cannot stand to hear their theories contradicted. So, let's look and see what Chalmers himself says about whether qualia have causal powers. > > "A problem with the view that I have advocated is that if consciousness is merely naturally supervenient upon the physical, then it seems to lack causal efficacy. The physical world is more or less causally closed, in that for any given physical event, it seems that there is a physical explanation of (modulo a small amount of quantum indeterminacy). This implies that there is no room for a nonphysical consciousness to do any independent causal work. It seems to be a mere epiphenomenon, hanging off the engine of physical causation, but making no difference in the physical world." David Chalmers, *The Conscious Mind: In Search of a Fundamental Theory,* Oxford University Press, 1996, p. 150. > > > Chalmers does go on to suggest ways in which he will try to avoid, or at least soften the blow, of having to make qualia epiphenomenal, but whether those responses are successful is a matter of further scholarly controversy. For my money, I don't think any of his proposed fixes, like endorsing causal overdetermination, or extreme humeanism about causation look even remotely plausible. I would love for people who are still down voting to explain in the comments exactly what kind of evidence they think would be necessary to prove the claim at issue here. Remember, the issue at stake is not the *empirical* question, "Do psychological states have causal powers?" but rather "Could qualia, those theoretical posits whose properties are stipulated by their use in the philosophy of mind of David Chalmers, Frank Jackson, et al., have causal powers?"
I will assume that we all do have subjective experiences which correspond precisely to the information encoded by specific objective brain states, and that the particular subjective qualities which identify different experiences may safely be referred to as qualia, a set of assumptions which some philosophers doubt. A common tenet of qualia theory is that our objective brain states are driven by the laws of physics, via objective physical processes, and that our subjective or conscious experience of those brain states merely rides on the back of that. Some, such as Daniel Dennett, hold that such a concept as qualia is therefore worthless; the brain states are all we need concern ourselves with. Others point to the ''sine qua non'' presence of qualia in the mind of every conscious philosopher and may even suggest that this provides unarguable evidence of a metaphysical aspect to the human mind. Either way, on this basis the evolution of the brain's rational capabilities is driven by broadly Darwinian evolution and consciousness of such reasoning just comes along for the ride. Modern information theory is beginning to bring another level of sophistication to the argument. For example [Integrated Information Theory](https://en.wikipedia.org/wiki/Integrated_information_theory) explicitly treats the information flows in the brain as the seat of consciousness, with the physiology and activity of the brain serving only to support sufficiently complex information. This must surely have profound consequences, for example the laws of physics never lie but semantic information often does, but I have not seen this aspect developed anywhere yet.
41,732
My company has corporate offices around the country and I have been hired under contract to work in one office while the rest of my team works in another. We are in the same time zone, but definitely remote. I have not met the team yet, but will be flying up there soon. What is your best advice for integrating and developing with this team? What are the most important priorities? Standard versioning control, e-mail, phone, conference call and IM are all available resources, however Google apps, Skype and the like are not for security reasons.
2011/01/31
[ "https://softwareengineering.stackexchange.com/questions/41732", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/13514/" ]
* **An excellent IM tool**. My team uses MS Office Communicator (and are currently migrating to [Lync](http://lync.microsoft.com/en-us/launch/Pages/launch.aspx). You need something that's faster than email to ask those "QQ"s. * A **video/audio chat tool** (like Lync or the newest Skype) that supports **multiple** users having video/audio chat at the same time. This provides for faster meetings overall as there's less fumbling to switch who is presenter. * A **remote desktop** application. Many times you may be asked to look over someone's code, or vice versa. Having a quick remote desktop application integrated with audio is a must to quickly solve problems. We actually use this when my entire team is in the office because it's quicker and easier than walking to someone's desk. We can invite the whole team and do a quick tutorial.
I think the number one thing for remote working is communication. When you are all in 1 location, it is much easier to build trust, nothing beats face-to-face time. Now yes, video IM and the like can give you this a little, but for me it is still nowhere near the same as sitting at someone's desk, or grabbing a conference room, or even even just going for a coffee. Making sure the team know you are available is key, but equally getting them to include you is important too. You mentioned version control, well for dev process this is clearly not even a question -you should absolutely have this. Further, you should get a Continuous Build environment, hopefully running your unit test suite up and running as well - this will give your new team confidence in this new remote worker - really, it's important for any dev team!
41,732
My company has corporate offices around the country and I have been hired under contract to work in one office while the rest of my team works in another. We are in the same time zone, but definitely remote. I have not met the team yet, but will be flying up there soon. What is your best advice for integrating and developing with this team? What are the most important priorities? Standard versioning control, e-mail, phone, conference call and IM are all available resources, however Google apps, Skype and the like are not for security reasons.
2011/01/31
[ "https://softwareengineering.stackexchange.com/questions/41732", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/13514/" ]
* **An excellent IM tool**. My team uses MS Office Communicator (and are currently migrating to [Lync](http://lync.microsoft.com/en-us/launch/Pages/launch.aspx). You need something that's faster than email to ask those "QQ"s. * A **video/audio chat tool** (like Lync or the newest Skype) that supports **multiple** users having video/audio chat at the same time. This provides for faster meetings overall as there's less fumbling to switch who is presenter. * A **remote desktop** application. Many times you may be asked to look over someone's code, or vice versa. Having a quick remote desktop application integrated with audio is a must to quickly solve problems. We actually use this when my entire team is in the office because it's quicker and easier than walking to someone's desk. We can invite the whole team and do a quick tutorial.
As @James noted, face to face communication is very, very important. We are in the same situation, with members of the team scattered around the globe, currently in 3 different locations, with a total timezone difference of 5,5 hours. We just recently got a new teammate and it took some time before the first videoconference meeting with him. It made a big difference for me to be able to associate a face with the voice. We visit each other physically at more or less regular intervals (our team lead 3-4 times a year, us developers about once a year), for a couple of days to a week each time. Of course, upon these occasions we also arrange common lunch/dinner. This definitely helps team bonding, although it is still far from working in the same office all the time. We also do our daily stand-up meeting (Scrum style) via conference call; it's a bit awkward, still it helps keeping the team together.
41,732
My company has corporate offices around the country and I have been hired under contract to work in one office while the rest of my team works in another. We are in the same time zone, but definitely remote. I have not met the team yet, but will be flying up there soon. What is your best advice for integrating and developing with this team? What are the most important priorities? Standard versioning control, e-mail, phone, conference call and IM are all available resources, however Google apps, Skype and the like are not for security reasons.
2011/01/31
[ "https://softwareengineering.stackexchange.com/questions/41732", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/13514/" ]
* **An excellent IM tool**. My team uses MS Office Communicator (and are currently migrating to [Lync](http://lync.microsoft.com/en-us/launch/Pages/launch.aspx). You need something that's faster than email to ask those "QQ"s. * A **video/audio chat tool** (like Lync or the newest Skype) that supports **multiple** users having video/audio chat at the same time. This provides for faster meetings overall as there's less fumbling to switch who is presenter. * A **remote desktop** application. Many times you may be asked to look over someone's code, or vice versa. Having a quick remote desktop application integrated with audio is a must to quickly solve problems. We actually use this when my entire team is in the office because it's quicker and easier than walking to someone's desk. We can invite the whole team and do a quick tutorial.
As mentioned before, communication is the most important thing. Some of my hard learned lessons & tips: * You need some kind of non-obstructive instant messaging (IM) -- to get everybody in the loop and finger on the pulse (my preference is IRC) * Relay commit messages into IM-channel * Relay possible errors in continuous build process into IM-channel * Document in wiki (so everybody has easy access and the latest version) * Pick up a good issue tracking system (my preference is Jira) Those helps, but nothing beats face to face communication, so try to make some time for that also.
93,705
St. Thomas Aquinas, [*Summa Theologica* II-II q. 78 a. 1](https://isidore.co/aquinas/summa/SS/SS078.html#SSQ78A1THEP1) co., says that usury is to sell the use of a consumable good separately from the consumable good itself: > > To take usury for money lent is unjust in itself, because this is to sell what does not exist, and this evidently leads to inequality which is contrary to justice. In order to make this evident, we must observe that there are certain **things the use of which consists in their consumption**: thus we consume wine when we use it for drink and we consume wheat when we use it for food. Wherefore in such like things the use of the thing must not be reckoned apart from the thing itself, and whoever is granted the use of the thing, is granted the thing itself and for this reason, to lend things of this kin is to transfer the ownership. Accordingly if a man wanted to sell wine separately from the use of the wine, he would be selling the same thing twice, or he would be selling what does not exist, wherefore he would evidently commit a sin of injustice. On like manner he commits an injustice who lends wine or wheat, and asks for double payment, viz. one, the return of the thing in equal measure, the other, the price of the use, which is called usury. > > > On the other hand, there are **things the use of which does n̲o̲t̲ consist in their consumption**: thus to use a house is to dwell in it, not to destroy it. Wherefore in such things both may be granted: for instance, one man may hand over to another the ownership of his house while reserving to himself the use of it for a time, or vice versa, he may grant the use of the house, while retaining the ownership. For this reason a man may lawfully make a charge for the use of his house, and, besides this, revendicate the house from the person to whom he has granted its use, as happens in renting and letting a house. > > > But that explanation makes no sense to me. Just because the use of wine consists in its destruction, I do not see how this implies that the sale of the use of wine also implies the sale of the property itself. I see no significant difference between using a house as a dwelling and using wine for drinking. If the sale of the use of the house can be separated from the sale of the property itself, then the sale of the use of the wine can also be separated from the sale of the property itself.
2022/12/05
[ "https://christianity.stackexchange.com/questions/93705", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/60033/" ]
St. Thomas Aquinas gets of a lot of things right, but on this matter I believe he is simply incorrect. His argument has two parts. First, it is only okay to charge for the use of something when ownership can be separated from the use, such as with renting a house. If something is consumed (destroyed) by the use, then the ownership cannot be separated, and therefore it's not okay to charge for the use separately from the thing; you'd be double-dipping, and that's not good. I don't necessarily disagree with that idea. I'm not fully convinced of it, either, but I'd love to see the principal applied to certain software licensing regimes, for example. I also want to point out this doesn't strictly eliminate money-lending as a potential business venture. It would be okay under this rule to, say, lend $100 in exchange for receiving $110 when the loan is repaid (the balance plus $10 in reasonable profit). What this principal says is the charge for a monetary loan should be fixed up front, rather than grow the longer the loan (use) lasts. --- But there is still the second part of the argument (money is consumed in the use), and here is where I need to pose a question: *which type of thing is money, really?* Let's say I take small loan to buy food: say I visit a restaurant and pay by credit card. Clearly the money the was consumed by the purchase, and very soon so is the food. It seems like Mr Aquinas is right. But what if I take a larger loan to start a business? The business is still there after I spend the money, and (hopefully) very soon so is the money. Economically, we say money is **fungible**: that is, it is easily converted from one thing to another. There are many things one can purchase with money that are also **durable** and themselves (perhaps somewhat less) fungible. So I can take a loan to purchase (or rent) a thing in order to perform some service, then sell the thing to get the money back, and return the "same" money to lender. That is, money *can* be consumed from the use, but it is not *certain* to be. Now lets go back to restaurant example, and add another wrinkle. Let's say my bank balance is $0; I have no money of my own at this particular moment. However, I do have a steady job and am expecting a paycheck tomorrow, and we'll also say my current broke state is for expected reasons that don't particularly concern me. This helps us look at the nature of this small credit card loan in terms of a *time shift*, as well. Even for this most ephemeral use of the money, I still only need or want it *for a particular moment in time*, and then I return it, perhaps as soon as the next day. Even here, we see the loan was ultimately about use over time, rather than consumption. --- The nature of any loan, then, is the borrower must return to the lender the full the value of what was borrowed, and on top of this the lender may reasonably charge a fee for the **use** of the borrowed money, to make it worth his effort and inconvenience. The longer the duration of the loan, the longer the lender is deprived of the use of the money himself (to make other loans, for example), and therefore it is justifiable this fee can also be time-based. Where we should take exception is with **EXCESSIVE** usuary. --- For fun, let's further look at a basic idea for limiting excessive usury. What if we had legal limits in place to prevent finance charges beyond the value of the initial principal of any loan? The moment interest and fees have reach the value of the original principal, any outstanding balance is still owed, but the lender no longer has the ability to tack on additional charges. This seems like a great baseline protection for borrowers. It might even still allow excessive usury, but as a final backstop it's better than nothing. But now let's think deeper. How does one arrive at this situation? Either you agreed to (and signed for) a loan with excessive usury built in, or you failed at some point to meet your repayment obligations for the original loan, allowing the use fees (interested) to pile up. At this point, the lender could reasonably argue you are extending the loan to use periods, which justify new charges. I think doubling over the original principal is still excessive, but at some point holding onto the balance is depriving the lender of their property, and there needs to be a penalty. Perhaps a better idea is that at this point interest can no longer compound.
According to the Bible, usury (charging interest) is not a sin unless one requires this of a fellow believer (fellow Israelite). > > If thou lend money to any of my people that is poor by thee, thou > shalt not be to him as an usurer, neither shalt thou lay upon him > usury. (Exodus 22:25, KJV) > > > 36 Take thou no usury of him, or increase: but fear thy > God; that thy brother may live with thee. 37 Thou shalt not give him thy money upon usury, nor lend him thy victuals for increase. (Exodus > 25:36-37, KJV) > > > Notice the words "my people" and "thy brother." Compare those passages with the following that expands the message to others. > > 19 Thou shalt not lend upon usury to thy brother; usury of > money, usury of victuals, usury of any thing that is lent upon usury: > 20 **Unto a stranger thou mayest lend upon usury;** but unto > thy brother thou shalt not lend upon usury: that the LORD thy God may > bless thee in all that thou settest thine hand to in the land whither > thou goest to possess it. (Deuteronomy 23:19-20, KJV) > > > A little thought might suffice to understand the reason usury is allowed for the stranger. All that a believer owns is understood to belong to God, and the believer is just a steward of his Lord's resources. Lending to a stranger means those resources are, for the time, tied up, and are not directly prospering the Lord's work. The primary recompense for this loss is in the usury received back later, which can then be invested in God's work. A secondary recompense might come in the form of the witness, with respect to kindness in lending, that may attract the unbeliever to a knowledge of God. Beyond these goals, however, there is little benefit to lending to an unbeliever (a stranger); and the enemies of God would like very much to occupy all the Lord's resources. Aquinas' logic is a bit convoluted. I understand what he is saying, but I disagree with it. He is essentially saying that for a consumable, to lend it is to give it, because it will be consumed. To ask for an equal measure back is the only way in which it could be lent. But to ask for double back is to require that which was not given--and to his mind, this is unjust. I disagree, however, because when one goes without for a period of time, one loses the benefit that might have been conferred by the thing lent for that time, and the usury would be to cover this loss. Consider the rationale for demanding at the law reparations for "loss of consortium." Even being deprived for a period of time can result in tangible effects. Thus it is with lending--during the period something or someone is lent, the lender is deprived of that which is lent, and usury is the price for that. An interesting question would be whether or not Aquinas intends to be addressing believers only, or everyone. In any case, Biblically speaking, there is a difference between charging believers or unbelievers.
93,705
St. Thomas Aquinas, [*Summa Theologica* II-II q. 78 a. 1](https://isidore.co/aquinas/summa/SS/SS078.html#SSQ78A1THEP1) co., says that usury is to sell the use of a consumable good separately from the consumable good itself: > > To take usury for money lent is unjust in itself, because this is to sell what does not exist, and this evidently leads to inequality which is contrary to justice. In order to make this evident, we must observe that there are certain **things the use of which consists in their consumption**: thus we consume wine when we use it for drink and we consume wheat when we use it for food. Wherefore in such like things the use of the thing must not be reckoned apart from the thing itself, and whoever is granted the use of the thing, is granted the thing itself and for this reason, to lend things of this kin is to transfer the ownership. Accordingly if a man wanted to sell wine separately from the use of the wine, he would be selling the same thing twice, or he would be selling what does not exist, wherefore he would evidently commit a sin of injustice. On like manner he commits an injustice who lends wine or wheat, and asks for double payment, viz. one, the return of the thing in equal measure, the other, the price of the use, which is called usury. > > > On the other hand, there are **things the use of which does n̲o̲t̲ consist in their consumption**: thus to use a house is to dwell in it, not to destroy it. Wherefore in such things both may be granted: for instance, one man may hand over to another the ownership of his house while reserving to himself the use of it for a time, or vice versa, he may grant the use of the house, while retaining the ownership. For this reason a man may lawfully make a charge for the use of his house, and, besides this, revendicate the house from the person to whom he has granted its use, as happens in renting and letting a house. > > > But that explanation makes no sense to me. Just because the use of wine consists in its destruction, I do not see how this implies that the sale of the use of wine also implies the sale of the property itself. I see no significant difference between using a house as a dwelling and using wine for drinking. If the sale of the use of the house can be separated from the sale of the property itself, then the sale of the use of the wine can also be separated from the sale of the property itself.
2022/12/05
[ "https://christianity.stackexchange.com/questions/93705", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/60033/" ]
Catholic legal professor and usury expert [Brian McCall](https://works.bepress.com/brian_mccall/) describes the difference between 1. goods consumed/destroyed in their first use and 2. goods whose use does not result in their destruction, in [*To Build the City of God: Living as Catholics in a Secular Age*](https://isidore.co/calibre/#panel=book_details&book_id=7017) (2017), ch. 4 "The Details of Economics: Money, Debt, Just Price, and Usury", § "Usury: What Is It? How Do We Avoid It? Why Do Our Shepherds Ignore It?": > > To discern what Scripture and Tradition have taught, we need to define some terms. This is somewhat tedious but necessary in this complicated area. To begin, we will start with some statements from the last major papal document that focused exclusively on usury, [*Vix Pervenit*](https://www.papalencyclicals.net/ben14/b14vixpe.htm) [[Latin](http://www.domus-ecclesiae.de/magisterium/vix-pervenit.html)] of Benedict XIV [in 1745]. The pope writes, "The nature of the sin called usury has its proper place and origin in a *loan* [*mutuum*] contract." [*Peccati genus illud, quod usura vocatur, quodque in contractu mutui propriam suam sedem et locum habet*] He continues, "any *gain* which exceeds the amount he [the lender] gave is illicit and usurious." [*Omne propterea hujusmodi lucrum, quod sortem superet, illicitum, et usurarium est.*] The two highlighted terms are critical to this summary of the doctrine. If a particular transaction is not a loan, then any gain cannot be usury (although it may be licit or illicit as a result of a moral principal other than usury, as when, for example, a merchant sells a product for more than its just price). Secondly, only "gain" is usury. We need to examine carefully what these two terms signify. > > > In modern law and speech, the word "loan" has a broad meaning. It can be used to describe when a person gives money to another to buy food or medical care and expects repayment of that money at another date. It can refer to an investor who provides capital to a business for a time and expects the return of his capital and a profit. Further, it can describe when a person gives another a piece of property (like a car) to be used for a while and requires the return of that same property. The Roman law had distinct terms to identify all of these transactions, which are now signified by our word "loan." Since most of the examples of the infallible teaching of the Church on usury use these Roman law terms, we need to understand that the law of usury only applied to those situations designated by the Roman word for "loan" (*mutuum*) and not the modern term. > > > The *mutuum* involved the transfer of ownership of a fungible good that was consumed in first use and required that the borrower return at a later time property of the same kind and quantity provided to him. This definition only covers the first example we cited above. The other examples were identified by other terms, such as *societas*, *census commodatum*, and *conductio locatio re*. One could not commit usury when engaging in these other transactions (again, other sins were possible but not usury). > > > Before progressing, we need to understand the concept of "consumed in first use." The *mutuum* only applied to the transfer and retransfer of this type of property. It is something that cannot be used without its destruction or loss. Tangible property can be divided into three groups of things: (1) those that can be used without their total loss, (2) those that can only be used by their total loss, and (3) those things which have different possible uses, some of which consume the thing and some of which do not. A house can be lived in and not destroyed. Wine cannot be used (for drinking or cooking) without consuming it. A potato can be used without consuming it (for example, by planting it as a seed potato) or by consuming it (eating it). From about 325 through the fourteenth century, money was thought to be exclusively or almost always in the second category of things that are consumed in first use. Due to the expansion of commerce, more opportunities to use money in a productive way (like the seed potato) became common. Many theologians began to consider whether money was actually in the third category of things that can be used in first use or used productively. Money could be used without consuming it completely (like planting a seed potato to grow more potatoes). > > > The next important concept in the pope's statement is "gain." The sin of usury occurs when a lender of a fungible thing consumed in first use requires that he be put in a better position than he was in before the loan. It is licit to require equality in position. Now we must distinguish gain from compensation for a loss. If a man steals my car and crashes it, he then is obligated to give me a new car of similar quality in restitution. I do not gain; I merely return to my original position. The Roman law called the payment to compensate for loss *quod interest* or the "difference." The original meaning of our word "interest" was not payment of gain for a loan but payment in compensation for a loss. For example, Marcus borrows 100 ducats from Linus and promises to pay it back in two months. Linus needs the money back in two months to pay his son's tuition at the university. Linus pays the money back two months late, and as a result Linus has to pay a ten ducat fine for paying tuition late. Marcus should pay Linus ten ducats in "interest" to compensate him for that loss. This payment is not usury, as it is not a payment for the use (consummation of money) but merely compensation for the harm done by not returning the money when agreed. > > > See also his talk "[The Principal and Gross Injustice of Usury](https://www.youtube.com/watch?v=q9dJ3ojv2iA)".
According to the Bible, usury (charging interest) is not a sin unless one requires this of a fellow believer (fellow Israelite). > > If thou lend money to any of my people that is poor by thee, thou > shalt not be to him as an usurer, neither shalt thou lay upon him > usury. (Exodus 22:25, KJV) > > > 36 Take thou no usury of him, or increase: but fear thy > God; that thy brother may live with thee. 37 Thou shalt not give him thy money upon usury, nor lend him thy victuals for increase. (Exodus > 25:36-37, KJV) > > > Notice the words "my people" and "thy brother." Compare those passages with the following that expands the message to others. > > 19 Thou shalt not lend upon usury to thy brother; usury of > money, usury of victuals, usury of any thing that is lent upon usury: > 20 **Unto a stranger thou mayest lend upon usury;** but unto > thy brother thou shalt not lend upon usury: that the LORD thy God may > bless thee in all that thou settest thine hand to in the land whither > thou goest to possess it. (Deuteronomy 23:19-20, KJV) > > > A little thought might suffice to understand the reason usury is allowed for the stranger. All that a believer owns is understood to belong to God, and the believer is just a steward of his Lord's resources. Lending to a stranger means those resources are, for the time, tied up, and are not directly prospering the Lord's work. The primary recompense for this loss is in the usury received back later, which can then be invested in God's work. A secondary recompense might come in the form of the witness, with respect to kindness in lending, that may attract the unbeliever to a knowledge of God. Beyond these goals, however, there is little benefit to lending to an unbeliever (a stranger); and the enemies of God would like very much to occupy all the Lord's resources. Aquinas' logic is a bit convoluted. I understand what he is saying, but I disagree with it. He is essentially saying that for a consumable, to lend it is to give it, because it will be consumed. To ask for an equal measure back is the only way in which it could be lent. But to ask for double back is to require that which was not given--and to his mind, this is unjust. I disagree, however, because when one goes without for a period of time, one loses the benefit that might have been conferred by the thing lent for that time, and the usury would be to cover this loss. Consider the rationale for demanding at the law reparations for "loss of consortium." Even being deprived for a period of time can result in tangible effects. Thus it is with lending--during the period something or someone is lent, the lender is deprived of that which is lent, and usury is the price for that. An interesting question would be whether or not Aquinas intends to be addressing believers only, or everyone. In any case, Biblically speaking, there is a difference between charging believers or unbelievers.
93,705
St. Thomas Aquinas, [*Summa Theologica* II-II q. 78 a. 1](https://isidore.co/aquinas/summa/SS/SS078.html#SSQ78A1THEP1) co., says that usury is to sell the use of a consumable good separately from the consumable good itself: > > To take usury for money lent is unjust in itself, because this is to sell what does not exist, and this evidently leads to inequality which is contrary to justice. In order to make this evident, we must observe that there are certain **things the use of which consists in their consumption**: thus we consume wine when we use it for drink and we consume wheat when we use it for food. Wherefore in such like things the use of the thing must not be reckoned apart from the thing itself, and whoever is granted the use of the thing, is granted the thing itself and for this reason, to lend things of this kin is to transfer the ownership. Accordingly if a man wanted to sell wine separately from the use of the wine, he would be selling the same thing twice, or he would be selling what does not exist, wherefore he would evidently commit a sin of injustice. On like manner he commits an injustice who lends wine or wheat, and asks for double payment, viz. one, the return of the thing in equal measure, the other, the price of the use, which is called usury. > > > On the other hand, there are **things the use of which does n̲o̲t̲ consist in their consumption**: thus to use a house is to dwell in it, not to destroy it. Wherefore in such things both may be granted: for instance, one man may hand over to another the ownership of his house while reserving to himself the use of it for a time, or vice versa, he may grant the use of the house, while retaining the ownership. For this reason a man may lawfully make a charge for the use of his house, and, besides this, revendicate the house from the person to whom he has granted its use, as happens in renting and letting a house. > > > But that explanation makes no sense to me. Just because the use of wine consists in its destruction, I do not see how this implies that the sale of the use of wine also implies the sale of the property itself. I see no significant difference between using a house as a dwelling and using wine for drinking. If the sale of the use of the house can be separated from the sale of the property itself, then the sale of the use of the wine can also be separated from the sale of the property itself.
2022/12/05
[ "https://christianity.stackexchange.com/questions/93705", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/60033/" ]
St. Thomas Aquinas gets of a lot of things right, but on this matter I believe he is simply incorrect. His argument has two parts. First, it is only okay to charge for the use of something when ownership can be separated from the use, such as with renting a house. If something is consumed (destroyed) by the use, then the ownership cannot be separated, and therefore it's not okay to charge for the use separately from the thing; you'd be double-dipping, and that's not good. I don't necessarily disagree with that idea. I'm not fully convinced of it, either, but I'd love to see the principal applied to certain software licensing regimes, for example. I also want to point out this doesn't strictly eliminate money-lending as a potential business venture. It would be okay under this rule to, say, lend $100 in exchange for receiving $110 when the loan is repaid (the balance plus $10 in reasonable profit). What this principal says is the charge for a monetary loan should be fixed up front, rather than grow the longer the loan (use) lasts. --- But there is still the second part of the argument (money is consumed in the use), and here is where I need to pose a question: *which type of thing is money, really?* Let's say I take small loan to buy food: say I visit a restaurant and pay by credit card. Clearly the money the was consumed by the purchase, and very soon so is the food. It seems like Mr Aquinas is right. But what if I take a larger loan to start a business? The business is still there after I spend the money, and (hopefully) very soon so is the money. Economically, we say money is **fungible**: that is, it is easily converted from one thing to another. There are many things one can purchase with money that are also **durable** and themselves (perhaps somewhat less) fungible. So I can take a loan to purchase (or rent) a thing in order to perform some service, then sell the thing to get the money back, and return the "same" money to lender. That is, money *can* be consumed from the use, but it is not *certain* to be. Now lets go back to restaurant example, and add another wrinkle. Let's say my bank balance is $0; I have no money of my own at this particular moment. However, I do have a steady job and am expecting a paycheck tomorrow, and we'll also say my current broke state is for expected reasons that don't particularly concern me. This helps us look at the nature of this small credit card loan in terms of a *time shift*, as well. Even for this most ephemeral use of the money, I still only need or want it *for a particular moment in time*, and then I return it, perhaps as soon as the next day. Even here, we see the loan was ultimately about use over time, rather than consumption. --- The nature of any loan, then, is the borrower must return to the lender the full the value of what was borrowed, and on top of this the lender may reasonably charge a fee for the **use** of the borrowed money, to make it worth his effort and inconvenience. The longer the duration of the loan, the longer the lender is deprived of the use of the money himself (to make other loans, for example), and therefore it is justifiable this fee can also be time-based. Where we should take exception is with **EXCESSIVE** usuary. --- For fun, let's further look at a basic idea for limiting excessive usury. What if we had legal limits in place to prevent finance charges beyond the value of the initial principal of any loan? The moment interest and fees have reach the value of the original principal, any outstanding balance is still owed, but the lender no longer has the ability to tack on additional charges. This seems like a great baseline protection for borrowers. It might even still allow excessive usury, but as a final backstop it's better than nothing. But now let's think deeper. How does one arrive at this situation? Either you agreed to (and signed for) a loan with excessive usury built in, or you failed at some point to meet your repayment obligations for the original loan, allowing the use fees (interested) to pile up. At this point, the lender could reasonably argue you are extending the loan to use periods, which justify new charges. I think doubling over the original principal is still excessive, but at some point holding onto the balance is depriving the lender of their property, and there needs to be a penalty. Perhaps a better idea is that at this point interest can no longer compound.
Catholic legal professor and usury expert [Brian McCall](https://works.bepress.com/brian_mccall/) describes the difference between 1. goods consumed/destroyed in their first use and 2. goods whose use does not result in their destruction, in [*To Build the City of God: Living as Catholics in a Secular Age*](https://isidore.co/calibre/#panel=book_details&book_id=7017) (2017), ch. 4 "The Details of Economics: Money, Debt, Just Price, and Usury", § "Usury: What Is It? How Do We Avoid It? Why Do Our Shepherds Ignore It?": > > To discern what Scripture and Tradition have taught, we need to define some terms. This is somewhat tedious but necessary in this complicated area. To begin, we will start with some statements from the last major papal document that focused exclusively on usury, [*Vix Pervenit*](https://www.papalencyclicals.net/ben14/b14vixpe.htm) [[Latin](http://www.domus-ecclesiae.de/magisterium/vix-pervenit.html)] of Benedict XIV [in 1745]. The pope writes, "The nature of the sin called usury has its proper place and origin in a *loan* [*mutuum*] contract." [*Peccati genus illud, quod usura vocatur, quodque in contractu mutui propriam suam sedem et locum habet*] He continues, "any *gain* which exceeds the amount he [the lender] gave is illicit and usurious." [*Omne propterea hujusmodi lucrum, quod sortem superet, illicitum, et usurarium est.*] The two highlighted terms are critical to this summary of the doctrine. If a particular transaction is not a loan, then any gain cannot be usury (although it may be licit or illicit as a result of a moral principal other than usury, as when, for example, a merchant sells a product for more than its just price). Secondly, only "gain" is usury. We need to examine carefully what these two terms signify. > > > In modern law and speech, the word "loan" has a broad meaning. It can be used to describe when a person gives money to another to buy food or medical care and expects repayment of that money at another date. It can refer to an investor who provides capital to a business for a time and expects the return of his capital and a profit. Further, it can describe when a person gives another a piece of property (like a car) to be used for a while and requires the return of that same property. The Roman law had distinct terms to identify all of these transactions, which are now signified by our word "loan." Since most of the examples of the infallible teaching of the Church on usury use these Roman law terms, we need to understand that the law of usury only applied to those situations designated by the Roman word for "loan" (*mutuum*) and not the modern term. > > > The *mutuum* involved the transfer of ownership of a fungible good that was consumed in first use and required that the borrower return at a later time property of the same kind and quantity provided to him. This definition only covers the first example we cited above. The other examples were identified by other terms, such as *societas*, *census commodatum*, and *conductio locatio re*. One could not commit usury when engaging in these other transactions (again, other sins were possible but not usury). > > > Before progressing, we need to understand the concept of "consumed in first use." The *mutuum* only applied to the transfer and retransfer of this type of property. It is something that cannot be used without its destruction or loss. Tangible property can be divided into three groups of things: (1) those that can be used without their total loss, (2) those that can only be used by their total loss, and (3) those things which have different possible uses, some of which consume the thing and some of which do not. A house can be lived in and not destroyed. Wine cannot be used (for drinking or cooking) without consuming it. A potato can be used without consuming it (for example, by planting it as a seed potato) or by consuming it (eating it). From about 325 through the fourteenth century, money was thought to be exclusively or almost always in the second category of things that are consumed in first use. Due to the expansion of commerce, more opportunities to use money in a productive way (like the seed potato) became common. Many theologians began to consider whether money was actually in the third category of things that can be used in first use or used productively. Money could be used without consuming it completely (like planting a seed potato to grow more potatoes). > > > The next important concept in the pope's statement is "gain." The sin of usury occurs when a lender of a fungible thing consumed in first use requires that he be put in a better position than he was in before the loan. It is licit to require equality in position. Now we must distinguish gain from compensation for a loss. If a man steals my car and crashes it, he then is obligated to give me a new car of similar quality in restitution. I do not gain; I merely return to my original position. The Roman law called the payment to compensate for loss *quod interest* or the "difference." The original meaning of our word "interest" was not payment of gain for a loan but payment in compensation for a loss. For example, Marcus borrows 100 ducats from Linus and promises to pay it back in two months. Linus needs the money back in two months to pay his son's tuition at the university. Linus pays the money back two months late, and as a result Linus has to pay a ten ducat fine for paying tuition late. Marcus should pay Linus ten ducats in "interest" to compensate him for that loss. This payment is not usury, as it is not a payment for the use (consummation of money) but merely compensation for the harm done by not returning the money when agreed. > > > See also his talk "[The Principal and Gross Injustice of Usury](https://www.youtube.com/watch?v=q9dJ3ojv2iA)".
58,013,886
I use ngx-cookieconsent module for an angular app, I need to manually set the cookie's status after a specific event but I didn't find a public method to do that in the injectable NgcCookieConsentService. Does anybody know if it is possible or if there is a workaround?
2019/09/19
[ "https://Stackoverflow.com/questions/58013886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5635645/" ]
Yes, by default it takes `HEAD`, but you could feed it any ref : ``` git log --graph --oneline # outputs history backwards from HEAD git log --graph --oneline branch-1 # outputs only branch-1 history git log --graph --oneline --all # outputs all branch histories ``` To address your comment below : for the case of `--all`, it doesn't mean it takes all commits, but all refs. So all the `refs/` dir will be explored (and `HEAD` also) --- Edit after new scope : To find lost (dangling) commits, use `fsck` ``` git fsck --lost-found ``` --- Finally, to link the two, you can nest commands. ``` git log --graph --oneline $(git fsck --lost-found | sed -E 's/dangling (tree|commit|blob|tag) //') ```
> > is there any way to see the log of every commit (including dangling commits i.e those not associated with any branch/tag ) > > > Usually adding `--reflog` to your command is enough to see every commit you've made or abandoned in the last month or so, regardless of whether it's in any current history. It's possible to generate and abandon commits without making reflog entries, but it's harder to imagine why you'd be hunting for these. The way to find all the ghost tips, the ones `--reflogs` doesn't reach because they were abandoned long ago or were generated by homegrown workflows/scripts that think they don't need no stinking reflogs is ``` git fsck --connectivity-only --unreachable --no-dangling ```
58,013,886
I use ngx-cookieconsent module for an angular app, I need to manually set the cookie's status after a specific event but I didn't find a public method to do that in the injectable NgcCookieConsentService. Does anybody know if it is possible or if there is a workaround?
2019/09/19
[ "https://Stackoverflow.com/questions/58013886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5635645/" ]
It's a little unclear, but after your update it seems your main question is: > > So is there any way to see the log of every commit (including dangling commits i.e those not associated with any branch/tag ) either with git log or any other alternate command/tool. > > > The short (and still mostly accurate) answer is: not really. If you have a dangling commit checked out (i.e. `HEAD` is detached and diverged from all refs) then you can see that history. You can see history from the `reflogs` (a local record of where your repo's branches and `HEAD` have pointed in the past) to see a history that might not be reachable from any current ref. And there are other similar exceptions. You could even give git a specific commit ID to see the history leading to that commit. But one way or other you do have to tell `git log` where to start its walk; it's not designed to go looking for dangling commits and starting a walk there. Before I follow that to its conclusion - and the reason why "not really" is only *mostly* correct - I'd like to point out that if you have a commit that can't be reached by `--all`, then it's a matter of time before `gc` pulls the carpet out from under that commit - because as far as it can tell, such commits are unused. Most `git` commands make the same assumption log does: that useful commits are reachable from refs (branches, tags, etc.), so even if you disabled `gc` to avoid such commits being deleted (not a good idea) you would still be forever trying to convince git to work with them. So the only reasonable advice is, don't get in the habit of working in detached head state when authoring code that you want to persist; and if you are writing new changes you want to keep and then realize that you're in detached head, create a branch. But for a *technically* more complete answer, I will note that git has one command whose job *is* to find dangling commits. You could use `git fsck` to locate the unreachable objects (assuming they haven't already been cleaned up by `gc`), and then feed the resulting SHA ID values to `log`. You might even be able to rig up a script to do it.
> > is there any way to see the log of every commit (including dangling commits i.e those not associated with any branch/tag ) > > > Usually adding `--reflog` to your command is enough to see every commit you've made or abandoned in the last month or so, regardless of whether it's in any current history. It's possible to generate and abandon commits without making reflog entries, but it's harder to imagine why you'd be hunting for these. The way to find all the ghost tips, the ones `--reflogs` doesn't reach because they were abandoned long ago or were generated by homegrown workflows/scripts that think they don't need no stinking reflogs is ``` git fsck --connectivity-only --unreachable --no-dangling ```
58,013,886
I use ngx-cookieconsent module for an angular app, I need to manually set the cookie's status after a specific event but I didn't find a public method to do that in the injectable NgcCookieConsentService. Does anybody know if it is possible or if there is a workaround?
2019/09/19
[ "https://Stackoverflow.com/questions/58013886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5635645/" ]
I'm afraid this is a bit ramble-y at this point as the question itself got a bit unfocused. You started with `git log` and wandered into `git gc` territory. :-) Git has *visible* references, such as `HEAD`, branch names, and tag names. But Git also has *less-visible* references such as reflogs, and *invisible* references. The last one is especially tricky: * Ignoring `git worktree add` for a moment, let's look at the invisible references. These are the entries in the index! They refer directly to blob objects (only) but they keep those blobs alive for `git gc` purposes. * Now let's throw in `git worktree add`. When you add a work-tree, the added work-tree gets its own index, its own `HEAD`, and its own set of work-tree-specific special references (`ORIG_HEAD`, `git bisect` refs, and so on). The `git gc` and `git fsck` commands must inspect all of these references. In Git 2.5, when `git worktree` first went in, they didn't! This went unfixed until Git 2.15. The result of this was that when `git gc` ran, it could throw away data being used in some of the added work-trees: objects stored only in an added work-tree's index, or commits reachable only from an added work-tree's detached HEAD, were missed, and could be GCed after the prune expiry (default = 14 days). You can have `git log` walk the reflogs with `-g`, or you can have it walk all the normal references with `--all`. However, the `--all` flag only looks at *this* work-tree's work-tree-specific refs. Meanwhile `git fsck` and `git gc` must look at all references, including the reflogs and the invisible and per-work-tree references. If you have a Git between 2.5 and 2.15, this is broken, so beware of using added work-trees for too long. (I was bitten by this particular bug myself. Fortunately the added work-tree had nothing important in it.) Exercise (discoverable without peeking at the source): is `refs/stash` per-work-tree, or global? (I don't know the answer myself.)
> > is there any way to see the log of every commit (including dangling commits i.e those not associated with any branch/tag ) > > > Usually adding `--reflog` to your command is enough to see every commit you've made or abandoned in the last month or so, regardless of whether it's in any current history. It's possible to generate and abandon commits without making reflog entries, but it's harder to imagine why you'd be hunting for these. The way to find all the ghost tips, the ones `--reflogs` doesn't reach because they were abandoned long ago or were generated by homegrown workflows/scripts that think they don't need no stinking reflogs is ``` git fsck --connectivity-only --unreachable --no-dangling ```
35,571,752
I can't get the lower and upper bound of y. ``` library(ggplot2) ggplot(data,aes(x=n,y=value,color=variable)) + geom_line()+ labs(color="Legend")+ scale_x_continuous("x",expand=c(0,0), breaks=c(1,2,5,10,30,60))+ scale_y_continuous("y",expand=c(0,0), breaks=round(seq(0,max(data[,3]),by=0.1),1)) ``` Data (there will be more variables later): ``` n variable value 1 1 0.2339010 2 1 0.2625115 5 1 0.2781600 10 1 0.2776770 30 1 0.3344481 60 1 0.4810225 ``` 1. I want the upper bound of y to be the highest value of y (0.4810225) rounded up to the highest second decimal (0.5). How do I show '0.5' as maximum y-value on the plot? (Much like how 60 is the maximum x-value.) 2. How do I show y=0.0 at the beginning of the axis? [![enter image description here](https://i.stack.imgur.com/M9suy.jpg)](https://i.stack.imgur.com/M9suy.jpg)
2016/02/23
[ "https://Stackoverflow.com/questions/35571752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`Box* a;` declares a *pointer* to a `Box` object. You don't ever *create* a `Box` object so `a` doesn't point to anything. The behaviour writing `a->data` is therefore *undefined*. Either drop the pointer so you get `Box a;`, or use `Box* a = new Box();`. In the latter case, don't forget to call `delete a;` at some point else you'll leak memory. Finally, writing `a->data = "Hello World";` could be problematic: `a->data` will then be a pointer to a *read-only* string literal; the behaviour on attempting to modify the contents of that buffer is *undefined*. It's far better to use a `std::string` as the type for `a`.
`a` isn't initialized (or assigned), it's just a dangled pointer. Any dereference on it will be [Undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). You could `Box* a = new Box`, or `Box b; Box* a = &b` to make the pointer valid. e.g. ``` Box* a = new Box; a->data = "Hello World"; ... delete a; ```
35,571,752
I can't get the lower and upper bound of y. ``` library(ggplot2) ggplot(data,aes(x=n,y=value,color=variable)) + geom_line()+ labs(color="Legend")+ scale_x_continuous("x",expand=c(0,0), breaks=c(1,2,5,10,30,60))+ scale_y_continuous("y",expand=c(0,0), breaks=round(seq(0,max(data[,3]),by=0.1),1)) ``` Data (there will be more variables later): ``` n variable value 1 1 0.2339010 2 1 0.2625115 5 1 0.2781600 10 1 0.2776770 30 1 0.3344481 60 1 0.4810225 ``` 1. I want the upper bound of y to be the highest value of y (0.4810225) rounded up to the highest second decimal (0.5). How do I show '0.5' as maximum y-value on the plot? (Much like how 60 is the maximum x-value.) 2. How do I show y=0.0 at the beginning of the axis? [![enter image description here](https://i.stack.imgur.com/M9suy.jpg)](https://i.stack.imgur.com/M9suy.jpg)
2016/02/23
[ "https://Stackoverflow.com/questions/35571752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A *pointer* to a `Box` object is *not* a `Box` object. The pointer `Box* a` points to a non-existing object, that's why you get an error when you try to assign "Hello World" to a member. You should create a `Box` object either by creating it "on the stack" with *automatic storage duration*: ``` Box a; ``` or by creating it "on the heap" with *dynamic storage duration*: ``` Box* a = new Box; ``` and delete it after use: ``` delete a; ```
`a` isn't initialized (or assigned), it's just a dangled pointer. Any dereference on it will be [Undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). You could `Box* a = new Box`, or `Box b; Box* a = &b` to make the pointer valid. e.g. ``` Box* a = new Box; a->data = "Hello World"; ... delete a; ```
35,571,752
I can't get the lower and upper bound of y. ``` library(ggplot2) ggplot(data,aes(x=n,y=value,color=variable)) + geom_line()+ labs(color="Legend")+ scale_x_continuous("x",expand=c(0,0), breaks=c(1,2,5,10,30,60))+ scale_y_continuous("y",expand=c(0,0), breaks=round(seq(0,max(data[,3]),by=0.1),1)) ``` Data (there will be more variables later): ``` n variable value 1 1 0.2339010 2 1 0.2625115 5 1 0.2781600 10 1 0.2776770 30 1 0.3344481 60 1 0.4810225 ``` 1. I want the upper bound of y to be the highest value of y (0.4810225) rounded up to the highest second decimal (0.5). How do I show '0.5' as maximum y-value on the plot? (Much like how 60 is the maximum x-value.) 2. How do I show y=0.0 at the beginning of the axis? [![enter image description here](https://i.stack.imgur.com/M9suy.jpg)](https://i.stack.imgur.com/M9suy.jpg)
2016/02/23
[ "https://Stackoverflow.com/questions/35571752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A pointer just points to a (hopefully) allocated chunk of memory. In your example, the pointer is uninitialized, and so you're trying to set memory which you don't have access to. You should ensure that it points to something valid, like this: ``` int Main() { Box box; // stack allocation Box* a = &box; // you could also call new Box; here a->data = "Hello World"; return 0; } ```
`a` isn't initialized (or assigned), it's just a dangled pointer. Any dereference on it will be [Undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). You could `Box* a = new Box`, or `Box b; Box* a = &b` to make the pointer valid. e.g. ``` Box* a = new Box; a->data = "Hello World"; ... delete a; ```
35,571,752
I can't get the lower and upper bound of y. ``` library(ggplot2) ggplot(data,aes(x=n,y=value,color=variable)) + geom_line()+ labs(color="Legend")+ scale_x_continuous("x",expand=c(0,0), breaks=c(1,2,5,10,30,60))+ scale_y_continuous("y",expand=c(0,0), breaks=round(seq(0,max(data[,3]),by=0.1),1)) ``` Data (there will be more variables later): ``` n variable value 1 1 0.2339010 2 1 0.2625115 5 1 0.2781600 10 1 0.2776770 30 1 0.3344481 60 1 0.4810225 ``` 1. I want the upper bound of y to be the highest value of y (0.4810225) rounded up to the highest second decimal (0.5). How do I show '0.5' as maximum y-value on the plot? (Much like how 60 is the maximum x-value.) 2. How do I show y=0.0 at the beginning of the axis? [![enter image description here](https://i.stack.imgur.com/M9suy.jpg)](https://i.stack.imgur.com/M9suy.jpg)
2016/02/23
[ "https://Stackoverflow.com/questions/35571752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The value of `a` is undefined because you never set it to anything. Therefore, anything can happen. The most likely thing is that you access memory that is not yours, triggering a segmentation fault or a similar access exception. This is what happened. Don't do this. Define your address in terms of the address of a variable of the same type that is already defined.
`a` isn't initialized (or assigned), it's just a dangled pointer. Any dereference on it will be [Undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). You could `Box* a = new Box`, or `Box b; Box* a = &b` to make the pointer valid. e.g. ``` Box* a = new Box; a->data = "Hello World"; ... delete a; ```
35,571,752
I can't get the lower and upper bound of y. ``` library(ggplot2) ggplot(data,aes(x=n,y=value,color=variable)) + geom_line()+ labs(color="Legend")+ scale_x_continuous("x",expand=c(0,0), breaks=c(1,2,5,10,30,60))+ scale_y_continuous("y",expand=c(0,0), breaks=round(seq(0,max(data[,3]),by=0.1),1)) ``` Data (there will be more variables later): ``` n variable value 1 1 0.2339010 2 1 0.2625115 5 1 0.2781600 10 1 0.2776770 30 1 0.3344481 60 1 0.4810225 ``` 1. I want the upper bound of y to be the highest value of y (0.4810225) rounded up to the highest second decimal (0.5). How do I show '0.5' as maximum y-value on the plot? (Much like how 60 is the maximum x-value.) 2. How do I show y=0.0 at the beginning of the axis? [![enter image description here](https://i.stack.imgur.com/M9suy.jpg)](https://i.stack.imgur.com/M9suy.jpg)
2016/02/23
[ "https://Stackoverflow.com/questions/35571752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`Box* a;` declares a *pointer* to a `Box` object. You don't ever *create* a `Box` object so `a` doesn't point to anything. The behaviour writing `a->data` is therefore *undefined*. Either drop the pointer so you get `Box a;`, or use `Box* a = new Box();`. In the latter case, don't forget to call `delete a;` at some point else you'll leak memory. Finally, writing `a->data = "Hello World";` could be problematic: `a->data` will then be a pointer to a *read-only* string literal; the behaviour on attempting to modify the contents of that buffer is *undefined*. It's far better to use a `std::string` as the type for `a`.
A *pointer* to a `Box` object is *not* a `Box` object. The pointer `Box* a` points to a non-existing object, that's why you get an error when you try to assign "Hello World" to a member. You should create a `Box` object either by creating it "on the stack" with *automatic storage duration*: ``` Box a; ``` or by creating it "on the heap" with *dynamic storage duration*: ``` Box* a = new Box; ``` and delete it after use: ``` delete a; ```
35,571,752
I can't get the lower and upper bound of y. ``` library(ggplot2) ggplot(data,aes(x=n,y=value,color=variable)) + geom_line()+ labs(color="Legend")+ scale_x_continuous("x",expand=c(0,0), breaks=c(1,2,5,10,30,60))+ scale_y_continuous("y",expand=c(0,0), breaks=round(seq(0,max(data[,3]),by=0.1),1)) ``` Data (there will be more variables later): ``` n variable value 1 1 0.2339010 2 1 0.2625115 5 1 0.2781600 10 1 0.2776770 30 1 0.3344481 60 1 0.4810225 ``` 1. I want the upper bound of y to be the highest value of y (0.4810225) rounded up to the highest second decimal (0.5). How do I show '0.5' as maximum y-value on the plot? (Much like how 60 is the maximum x-value.) 2. How do I show y=0.0 at the beginning of the axis? [![enter image description here](https://i.stack.imgur.com/M9suy.jpg)](https://i.stack.imgur.com/M9suy.jpg)
2016/02/23
[ "https://Stackoverflow.com/questions/35571752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`Box* a;` declares a *pointer* to a `Box` object. You don't ever *create* a `Box` object so `a` doesn't point to anything. The behaviour writing `a->data` is therefore *undefined*. Either drop the pointer so you get `Box a;`, or use `Box* a = new Box();`. In the latter case, don't forget to call `delete a;` at some point else you'll leak memory. Finally, writing `a->data = "Hello World";` could be problematic: `a->data` will then be a pointer to a *read-only* string literal; the behaviour on attempting to modify the contents of that buffer is *undefined*. It's far better to use a `std::string` as the type for `a`.
A pointer just points to a (hopefully) allocated chunk of memory. In your example, the pointer is uninitialized, and so you're trying to set memory which you don't have access to. You should ensure that it points to something valid, like this: ``` int Main() { Box box; // stack allocation Box* a = &box; // you could also call new Box; here a->data = "Hello World"; return 0; } ```
35,571,752
I can't get the lower and upper bound of y. ``` library(ggplot2) ggplot(data,aes(x=n,y=value,color=variable)) + geom_line()+ labs(color="Legend")+ scale_x_continuous("x",expand=c(0,0), breaks=c(1,2,5,10,30,60))+ scale_y_continuous("y",expand=c(0,0), breaks=round(seq(0,max(data[,3]),by=0.1),1)) ``` Data (there will be more variables later): ``` n variable value 1 1 0.2339010 2 1 0.2625115 5 1 0.2781600 10 1 0.2776770 30 1 0.3344481 60 1 0.4810225 ``` 1. I want the upper bound of y to be the highest value of y (0.4810225) rounded up to the highest second decimal (0.5). How do I show '0.5' as maximum y-value on the plot? (Much like how 60 is the maximum x-value.) 2. How do I show y=0.0 at the beginning of the axis? [![enter image description here](https://i.stack.imgur.com/M9suy.jpg)](https://i.stack.imgur.com/M9suy.jpg)
2016/02/23
[ "https://Stackoverflow.com/questions/35571752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`Box* a;` declares a *pointer* to a `Box` object. You don't ever *create* a `Box` object so `a` doesn't point to anything. The behaviour writing `a->data` is therefore *undefined*. Either drop the pointer so you get `Box a;`, or use `Box* a = new Box();`. In the latter case, don't forget to call `delete a;` at some point else you'll leak memory. Finally, writing `a->data = "Hello World";` could be problematic: `a->data` will then be a pointer to a *read-only* string literal; the behaviour on attempting to modify the contents of that buffer is *undefined*. It's far better to use a `std::string` as the type for `a`.
The value of `a` is undefined because you never set it to anything. Therefore, anything can happen. The most likely thing is that you access memory that is not yours, triggering a segmentation fault or a similar access exception. This is what happened. Don't do this. Define your address in terms of the address of a variable of the same type that is already defined.
25,330,425
I am trying to set up an onClickListener to my ListView in my AlertDialog, but I keep getting errors. When using this code I get an error under "setOnClickListener" stating `The method setOnClickListener(View.OnClickListener) in the type AdapterView<ListAdapter> is not applicable for the arguments (new DialogInterface.OnClickListener(){})` Here's my code, hopefully someone could help me out, thanks. ``` String names[] ={"A","B","C","D"}; AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View convertView = (View) inflater.inflate(R.layout.customdialog, null); alertDialog.setView(convertView); alertDialog.setTitle("List"); ListView lv = (ListView) convertView.findViewById(R.id.listView1); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,names); lv.setAdapter(adapter); alertDialog.show(); lv.setOnClickListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub switch(which){ case 0: Toast.makeText(getActivity(), "clicked 1", Toast.LENGTH_SHORT).show(); break; } } }); ```
2014/08/15
[ "https://Stackoverflow.com/questions/25330425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657363/" ]
Use `OnItemClickListener`. There is param (third one) `int position` which gives you the index of list item click. Based on index you can do what you want. ``` lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3) { switch(position){ case 0: Toast.makeText(getActivity(), "clicked 1", Toast.LENGTH_SHORT).show(); break; } } }); ```
Instead on Dialog.OnClickListener you need to use [View.OnClickListener](http://developer.android.com/reference/android/view/View.OnClickListener.html) Do the following changes: ``` lv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub switch(which){ case 0: Toast.makeText(getActivity(), "clicked 1", Toast.LENGTH_SHORT).show(); break; } } }); ```
70,356,210
I am fetching data from a text file where I need to match the substring to get the matched line. Once, I have that, I need to get the third 8 digit value in the line which comes after the delimiter "|". Basically, all the values have varying lengths and are separated by a delimiter "|". Except the first substring (id) which is of fixed length and has a fix starting and end position. Text file data example: ``` 0123456|BHKAHHHHkk|12345678|JuiKKK121255 9100450|HHkk|12348888|JuiKKK10000000021sdadad255 ``` ``` $file = 'file.txt'; // the following line prevents the browser from parsing this as HTML. header('Content-Type: text/plain'); // get the file contents, assuming the file to be readable (and exist) $contents = file_get_contents($file); // escape special characters in the query $txt = explode("\n",$contents); $counter = 0; foreach($txt as $key => $line){ $subbedString = substr($line,2,6); // $searchfor = '123456'; //echo strpos($subbedString,$searchfor); if(strpos($subbedString,$searchfor) === 0){ $matches[$key] = $searchfor; $matchesLine[$key] = substr($line,2,50); echo "<p>" . $matchesLine[$key] . "</p>"; $counter += 1; if($counter==10) break; } ```
2021/12/14
[ "https://Stackoverflow.com/questions/70356210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15691137/" ]
You just need to do a strict search. See 3rd parameter of array\_search. ``` function decode($cypher,$dict){ $sepp = explode(" ",$cypher); foreach($sepp as $char){ echo array_search($char,$dict,true); } } ``` The reason it doesn't work without is because php thinks 1 and 1. is the same number.
This line would help you. Set third parameter to `true`. This causes the comparison to run in strict mode. `echo array_search($char, $dict, true);` ``` function decode($cypher, $dict) { $sepp = explode(" ",$cypher); foreach ($sepp as $char) { echo array_search($char, $dict, true); } } ```
70,356,210
I am fetching data from a text file where I need to match the substring to get the matched line. Once, I have that, I need to get the third 8 digit value in the line which comes after the delimiter "|". Basically, all the values have varying lengths and are separated by a delimiter "|". Except the first substring (id) which is of fixed length and has a fix starting and end position. Text file data example: ``` 0123456|BHKAHHHHkk|12345678|JuiKKK121255 9100450|HHkk|12348888|JuiKKK10000000021sdadad255 ``` ``` $file = 'file.txt'; // the following line prevents the browser from parsing this as HTML. header('Content-Type: text/plain'); // get the file contents, assuming the file to be readable (and exist) $contents = file_get_contents($file); // escape special characters in the query $txt = explode("\n",$contents); $counter = 0; foreach($txt as $key => $line){ $subbedString = substr($line,2,6); // $searchfor = '123456'; //echo strpos($subbedString,$searchfor); if(strpos($subbedString,$searchfor) === 0){ $matches[$key] = $searchfor; $matchesLine[$key] = substr($line,2,50); echo "<p>" . $matchesLine[$key] . "</p>"; $counter += 1; if($counter==10) break; } ```
2021/12/14
[ "https://Stackoverflow.com/questions/70356210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15691137/" ]
By default, `array_search` performs the same comparison as the `==` operator, which will attempt to ["type juggle"](https://www.php.net/manual/en/language.types.type-juggling.php) certain values. For instance, `'1' == 1`, `'1.' == 1`, and `'1.' == '1'` are all true. That means that `'1'` and `'1.'` will always match the same element in your lookup table. Luckily, the function takes a third argument, which [the manual describes](https://www.php.net/array_search) as: > > If the third parameter `strict` is set to `true` then the `array_search()` function will search for identical elements in the `haystack`. This means it will also perform a strict type comparison of the `needle` in the `haystack`, and objects must be the same instance. > > > This makes it equivalent to the `===` operator instead. Note that `'1' === 1`, `'1.' === 1`, and `'1.' === '1'` are all false. So you just need to add that argument: ``` echo array_search($char,$dict,true); ```
You just need to do a strict search. See 3rd parameter of array\_search. ``` function decode($cypher,$dict){ $sepp = explode(" ",$cypher); foreach($sepp as $char){ echo array_search($char,$dict,true); } } ``` The reason it doesn't work without is because php thinks 1 and 1. is the same number.
70,356,210
I am fetching data from a text file where I need to match the substring to get the matched line. Once, I have that, I need to get the third 8 digit value in the line which comes after the delimiter "|". Basically, all the values have varying lengths and are separated by a delimiter "|". Except the first substring (id) which is of fixed length and has a fix starting and end position. Text file data example: ``` 0123456|BHKAHHHHkk|12345678|JuiKKK121255 9100450|HHkk|12348888|JuiKKK10000000021sdadad255 ``` ``` $file = 'file.txt'; // the following line prevents the browser from parsing this as HTML. header('Content-Type: text/plain'); // get the file contents, assuming the file to be readable (and exist) $contents = file_get_contents($file); // escape special characters in the query $txt = explode("\n",$contents); $counter = 0; foreach($txt as $key => $line){ $subbedString = substr($line,2,6); // $searchfor = '123456'; //echo strpos($subbedString,$searchfor); if(strpos($subbedString,$searchfor) === 0){ $matches[$key] = $searchfor; $matchesLine[$key] = substr($line,2,50); echo "<p>" . $matchesLine[$key] . "</p>"; $counter += 1; if($counter==10) break; } ```
2021/12/14
[ "https://Stackoverflow.com/questions/70356210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15691137/" ]
You just need to do a strict search. See 3rd parameter of array\_search. ``` function decode($cypher,$dict){ $sepp = explode(" ",$cypher); foreach($sepp as $char){ echo array_search($char,$dict,true); } } ``` The reason it doesn't work without is because php thinks 1 and 1. is the same number.
If you have a one-one map, you can just flip your map, and use the array to translate your cipher directly. ``` <?php $dict = array( 'I'=>'1', 'L'=>'1.', 'O'=>'0', 'Q'=>'0.', 'Z'=>'2', '?'=>'2.' ); $cipher = "1. 0. 2."; $decode = strtr($cipher, array_flip($dict)); var_dump($decode); ``` Output: ``` string(5) "L Q ?" ```
70,356,210
I am fetching data from a text file where I need to match the substring to get the matched line. Once, I have that, I need to get the third 8 digit value in the line which comes after the delimiter "|". Basically, all the values have varying lengths and are separated by a delimiter "|". Except the first substring (id) which is of fixed length and has a fix starting and end position. Text file data example: ``` 0123456|BHKAHHHHkk|12345678|JuiKKK121255 9100450|HHkk|12348888|JuiKKK10000000021sdadad255 ``` ``` $file = 'file.txt'; // the following line prevents the browser from parsing this as HTML. header('Content-Type: text/plain'); // get the file contents, assuming the file to be readable (and exist) $contents = file_get_contents($file); // escape special characters in the query $txt = explode("\n",$contents); $counter = 0; foreach($txt as $key => $line){ $subbedString = substr($line,2,6); // $searchfor = '123456'; //echo strpos($subbedString,$searchfor); if(strpos($subbedString,$searchfor) === 0){ $matches[$key] = $searchfor; $matchesLine[$key] = substr($line,2,50); echo "<p>" . $matchesLine[$key] . "</p>"; $counter += 1; if($counter==10) break; } ```
2021/12/14
[ "https://Stackoverflow.com/questions/70356210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15691137/" ]
By default, `array_search` performs the same comparison as the `==` operator, which will attempt to ["type juggle"](https://www.php.net/manual/en/language.types.type-juggling.php) certain values. For instance, `'1' == 1`, `'1.' == 1`, and `'1.' == '1'` are all true. That means that `'1'` and `'1.'` will always match the same element in your lookup table. Luckily, the function takes a third argument, which [the manual describes](https://www.php.net/array_search) as: > > If the third parameter `strict` is set to `true` then the `array_search()` function will search for identical elements in the `haystack`. This means it will also perform a strict type comparison of the `needle` in the `haystack`, and objects must be the same instance. > > > This makes it equivalent to the `===` operator instead. Note that `'1' === 1`, `'1.' === 1`, and `'1.' === '1'` are all false. So you just need to add that argument: ``` echo array_search($char,$dict,true); ```
This line would help you. Set third parameter to `true`. This causes the comparison to run in strict mode. `echo array_search($char, $dict, true);` ``` function decode($cypher, $dict) { $sepp = explode(" ",$cypher); foreach ($sepp as $char) { echo array_search($char, $dict, true); } } ```
70,356,210
I am fetching data from a text file where I need to match the substring to get the matched line. Once, I have that, I need to get the third 8 digit value in the line which comes after the delimiter "|". Basically, all the values have varying lengths and are separated by a delimiter "|". Except the first substring (id) which is of fixed length and has a fix starting and end position. Text file data example: ``` 0123456|BHKAHHHHkk|12345678|JuiKKK121255 9100450|HHkk|12348888|JuiKKK10000000021sdadad255 ``` ``` $file = 'file.txt'; // the following line prevents the browser from parsing this as HTML. header('Content-Type: text/plain'); // get the file contents, assuming the file to be readable (and exist) $contents = file_get_contents($file); // escape special characters in the query $txt = explode("\n",$contents); $counter = 0; foreach($txt as $key => $line){ $subbedString = substr($line,2,6); // $searchfor = '123456'; //echo strpos($subbedString,$searchfor); if(strpos($subbedString,$searchfor) === 0){ $matches[$key] = $searchfor; $matchesLine[$key] = substr($line,2,50); echo "<p>" . $matchesLine[$key] . "</p>"; $counter += 1; if($counter==10) break; } ```
2021/12/14
[ "https://Stackoverflow.com/questions/70356210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15691137/" ]
This line would help you. Set third parameter to `true`. This causes the comparison to run in strict mode. `echo array_search($char, $dict, true);` ``` function decode($cypher, $dict) { $sepp = explode(" ",$cypher); foreach ($sepp as $char) { echo array_search($char, $dict, true); } } ```
If you have a one-one map, you can just flip your map, and use the array to translate your cipher directly. ``` <?php $dict = array( 'I'=>'1', 'L'=>'1.', 'O'=>'0', 'Q'=>'0.', 'Z'=>'2', '?'=>'2.' ); $cipher = "1. 0. 2."; $decode = strtr($cipher, array_flip($dict)); var_dump($decode); ``` Output: ``` string(5) "L Q ?" ```
70,356,210
I am fetching data from a text file where I need to match the substring to get the matched line. Once, I have that, I need to get the third 8 digit value in the line which comes after the delimiter "|". Basically, all the values have varying lengths and are separated by a delimiter "|". Except the first substring (id) which is of fixed length and has a fix starting and end position. Text file data example: ``` 0123456|BHKAHHHHkk|12345678|JuiKKK121255 9100450|HHkk|12348888|JuiKKK10000000021sdadad255 ``` ``` $file = 'file.txt'; // the following line prevents the browser from parsing this as HTML. header('Content-Type: text/plain'); // get the file contents, assuming the file to be readable (and exist) $contents = file_get_contents($file); // escape special characters in the query $txt = explode("\n",$contents); $counter = 0; foreach($txt as $key => $line){ $subbedString = substr($line,2,6); // $searchfor = '123456'; //echo strpos($subbedString,$searchfor); if(strpos($subbedString,$searchfor) === 0){ $matches[$key] = $searchfor; $matchesLine[$key] = substr($line,2,50); echo "<p>" . $matchesLine[$key] . "</p>"; $counter += 1; if($counter==10) break; } ```
2021/12/14
[ "https://Stackoverflow.com/questions/70356210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15691137/" ]
By default, `array_search` performs the same comparison as the `==` operator, which will attempt to ["type juggle"](https://www.php.net/manual/en/language.types.type-juggling.php) certain values. For instance, `'1' == 1`, `'1.' == 1`, and `'1.' == '1'` are all true. That means that `'1'` and `'1.'` will always match the same element in your lookup table. Luckily, the function takes a third argument, which [the manual describes](https://www.php.net/array_search) as: > > If the third parameter `strict` is set to `true` then the `array_search()` function will search for identical elements in the `haystack`. This means it will also perform a strict type comparison of the `needle` in the `haystack`, and objects must be the same instance. > > > This makes it equivalent to the `===` operator instead. Note that `'1' === 1`, `'1.' === 1`, and `'1.' === '1'` are all false. So you just need to add that argument: ``` echo array_search($char,$dict,true); ```
If you have a one-one map, you can just flip your map, and use the array to translate your cipher directly. ``` <?php $dict = array( 'I'=>'1', 'L'=>'1.', 'O'=>'0', 'Q'=>'0.', 'Z'=>'2', '?'=>'2.' ); $cipher = "1. 0. 2."; $decode = strtr($cipher, array_flip($dict)); var_dump($decode); ``` Output: ``` string(5) "L Q ?" ```
44,618,935
I've been trying out to solve the [monty hall problem](https://en.wikipedia.org/wiki/Monty_Hall_problem) in Python in order to advance in coding, which is why I tried to randomize everything. The thing is: I've been running into some trouble. As most of you probably know the monty problem is supposed to show that changing the door has a higher winrate (66%) than staying on the chosen door (33%). For some odd reason though my simulation shows a 33% winrate for both cases and I am not really sure why. Here's the code: ``` from random import * def doorPriceRandomizer(): door1 = randint(0,2) #If a door is defined 0, it has a price in it door2 = randint(0,2) #If a door is defined either 1 or 2, it has a goat in it. door3 = randint(0,2) while door2 == door1: door2 = randint(0,2) while door3 == door2 or door3 == door1: door3 = randint(0,2) return door1,door2,door3 #This random placement generator seems to be working fine. while True: loopStart = 0 amountWin = 0 amountLose = 0 try: loopEnd = int(input("How often would you like to run this simulation: ")) if loopEnd < 0: raise ValueError doorChangeUser = int(input("[0] = Do not change door; [1] = Change door: ")) if doorChangeUser not in range(0,2): raise ValueError except ValueError: print("Invalid input. Try again.\n") else: while loopStart != loopEnd: gameDoors = doorPriceRandomizer() inputUser = randint(0,2) if doorChangeUser == 0: if gameDoors[inputUser] == 0: amountWin += 1 loopStart += 1 else: amountLose += 1 loopStart += 1 elif doorChangeUser == 1: ChangeRandom = 0 while gameDoors[ChangeRandom] == gameDoors[inputUser]: ChangeRandom = randint(0,2) if gameDoors[ChangeRandom] == 0: amountWin += 1 loopStart += 1 else: amountLose += 1 loopStart += 1 print("Win amount: ",amountWin,"\tLose amount: ",amountLose) ``` What am I doing wrong? I really appreciate all help! Thanks in advance!
2017/06/18
[ "https://Stackoverflow.com/questions/44618935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8179999/" ]
``` ChangeRandom = 0 while gameDoors[ChangeRandom] == gameDoors[inputUser]: ChangeRandom = randint(0,2) ``` This doesn't do what you think it does. Instead of checking if the `ChangeRandom` door is the same as the `inputUser` door, this checks if the `ChangeRandom` door and the `inputUser` door have the same value -- that is to say they're either both winners or both losers. That said, that's not even what you want to do. What you want to do is to find a door that's not the user's input that IS a loser door, then switch to the OTHER one that isn't the user's input. This could be implemented with minimal change to your code as: ``` other_wrong_door = next(c for c, v in enumerate(gameDoors) if v != 0 and c != inputUser) new_door = next(c for c, _ in enumerate(gameDoors) if c != inputUser and c != other_wrong_door) ``` But honestly this merits a re-examining of your code's structure. Give me a few minutes to work something up, and I'll edit this answer to give you an idea of how I'd implement this. ``` import random DOORS = [1, 0, 0] def runonce(switch=False): user_choice = random.choice(DOORS) if user_choice == 1: # immediate winner if switch: # if you won before and switch doors, you must lose now return False else: new_doors = [0, 0] # remove the user-selected winner new_doors = [0] # remove another loser return bool(random.choice(new_doors)) # of course, this is always `0`, but # sometimes it helps to show it. In production you # wouldn't bother writing the extra lines and just return False else: if switch: new_doors = [1, 0] # remove the user-selected loser new_doors = [1] # remove another loser return bool(random.choice(new_doors)) # as above: this is always True, but.... else: return False # if you lost before and don't switch, well, you lost. num_trials = int(input("How many trials?")) no_switch_raw = [run_once(switch=False) for _ in range(num_trials)] switch_raw = [run_once(switch=True) for _ in range(num_trials)] no_switch_wins = sum(1 for r in no_switch_raw if r) switch_wins = sum(1 for r in switch_raw if r) no_switch_prob = no_switch_wins / num_trials * 100.0 switch_prob = switch_wins / num_trials * 100.0 print( " WINS LOSSES %\n" f"SWITCH: {switch_wins:>4} {num_trials-switch_wins:>6} {switch_prob:.02f}\n" f"NOSWITCH:{no_switch_wins:>4} {num_trials-no_switch_wins:>6} {no_switch_prob:.02f}") ```
You have gotten the mechanics of the problem wrong so you are getting the wrong result. I have rewritten the choice mechanics, but I am leaving the user input stuff to you so that you can continue to learn python. This is one of many ways to solve the problem, but hopefully it demonstrates some things to you. ``` def get_choices(): valid_choices = [0, 1, 2] # these are the values for a valid sample shuffle(valid_choices) # now randomly shuffle that list return valid_choices # return the shuffled list def get_door(user_choice): return user_choice.index(0) def monty_sim(n, kind): """ :param n: number of runs in this simulation :param kind: whether to change the door or not, 0 - don't change, 1 = change door :return: (win_rate, 1 - win_rate) """ wins = 0 for i in range(0, n): game_doors = get_choices() user_choice = get_door(get_choices()) # use the same method and find user door choice # so there are two branches. # In both, a door with a goat (game_door = 1) is chosen, which reduce the result to # a choice between two doors, rather than 3. if kind == 0: if user_choice == game_doors.index(0): wins += 1 elif kind == 1: # so now, the user chooses to change the door if user_choice != game_doors.index(0): wins += 1 # Because the original choice wasn't the right one, then the new # must be correct because the host already chose the other wrong one. win_rate = (wins / n) * 100 return win_rate, 100 - win_rate if __name__ == '__main__': n = 1000 kind = 1 wins, loses = monty_sim(n, kind) print(f'In a simulation of {n} experiments, of type {kind} user won {wins:02f} of the time, lost {loses:02f} of the time') ```
43,691,884
We are covering the topic of classes at my school. I am supposed create a class called Student that we can use to hold different test scores in a dynamically allocated array. I'm struggling to figure out why when I print out the array of a specific instance of this class, it gives me completely incorrect values. I know my setter function for the class is setting the correct values but whenever I go to print them out they are completely wrong. Below is my code. The commented out portion in main() was just being used to test my logic for the makeArray() function. ``` #include <iostream> using namespace std; class Student { private: string name; int id; int* testptr; int num; void makeArray() { int array[num]; testptr = &array[num]; for (int i = 0; i < num; i++) { array[i] = 0; } } public: Student() { setName("None"); setID(10); num = 3; makeArray(); } Student(int n) { setName("None"); setID(10); if (n > 0) num = n; else num = 3; makeArray(); } Student(string nm, int i, int n) { setName(nm); setID(i); if (n > 0) num = n; else num = 3; makeArray(); } void setName(string nm) { name = nm; } void setID(int i) { if (i >= 10 && i <= 99){ id = i; } else { cout << "Error: Cannot set id to " << i << " for " << getName(); id = 10; } } void setScore(int i, int s) { if ((i >= 0 && i <= num) && (s >= 0 && s <= 100)) { //Here is where I set the values for the array. They come out correct in the console. testptr[i] = s; cout << testptr[i] << endl; } else { cout << "The test " << i << " cannot be set to " << s << " for " << getName() << endl; } } string getName() const { return name; } int getID() const { return id; } void showScore() { //This is where I print out the values of the array. They come out incorrect here. for (int i = 0; i < num; i++) { cout << "Test " << i << " had a score of " << testptr[i] << endl; } } void display() { cout << "Calling the display function" << endl; cout << "The Name: " << getName() << endl; cout << "The ID: " << getID() << endl; showScore(); } ~Student() { } }; int main() { Student c("Joe", 40, 5); c.setScore(0, 90); c.setScore(1, 91); c.setScore(2, 92); c.setScore(3, 93); c.setScore(4, 94); c.display(); /**int* testpointer; int num = 3; int array[num]; testpointer = &array[0]; for (int i = 0; i < num; i++) { testpointer[i] = i; cout << testpointer[i] << endl; }**/ } ```
2017/04/29
[ "https://Stackoverflow.com/questions/43691884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730420/" ]
``` find . -type d -exec function.sh "{}" \; ```
I think this should work for you: find -type d; do; function "$dirs"; done;
43,691,884
We are covering the topic of classes at my school. I am supposed create a class called Student that we can use to hold different test scores in a dynamically allocated array. I'm struggling to figure out why when I print out the array of a specific instance of this class, it gives me completely incorrect values. I know my setter function for the class is setting the correct values but whenever I go to print them out they are completely wrong. Below is my code. The commented out portion in main() was just being used to test my logic for the makeArray() function. ``` #include <iostream> using namespace std; class Student { private: string name; int id; int* testptr; int num; void makeArray() { int array[num]; testptr = &array[num]; for (int i = 0; i < num; i++) { array[i] = 0; } } public: Student() { setName("None"); setID(10); num = 3; makeArray(); } Student(int n) { setName("None"); setID(10); if (n > 0) num = n; else num = 3; makeArray(); } Student(string nm, int i, int n) { setName(nm); setID(i); if (n > 0) num = n; else num = 3; makeArray(); } void setName(string nm) { name = nm; } void setID(int i) { if (i >= 10 && i <= 99){ id = i; } else { cout << "Error: Cannot set id to " << i << " for " << getName(); id = 10; } } void setScore(int i, int s) { if ((i >= 0 && i <= num) && (s >= 0 && s <= 100)) { //Here is where I set the values for the array. They come out correct in the console. testptr[i] = s; cout << testptr[i] << endl; } else { cout << "The test " << i << " cannot be set to " << s << " for " << getName() << endl; } } string getName() const { return name; } int getID() const { return id; } void showScore() { //This is where I print out the values of the array. They come out incorrect here. for (int i = 0; i < num; i++) { cout << "Test " << i << " had a score of " << testptr[i] << endl; } } void display() { cout << "Calling the display function" << endl; cout << "The Name: " << getName() << endl; cout << "The ID: " << getID() << endl; showScore(); } ~Student() { } }; int main() { Student c("Joe", 40, 5); c.setScore(0, 90); c.setScore(1, 91); c.setScore(2, 92); c.setScore(3, 93); c.setScore(4, 94); c.display(); /**int* testpointer; int num = 3; int array[num]; testpointer = &array[0]; for (int i = 0; i < num; i++) { testpointer[i] = i; cout << testpointer[i] << endl; }**/ } ```
2017/04/29
[ "https://Stackoverflow.com/questions/43691884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730420/" ]
``` find . -type d -exec function.sh "{}" \; ```
This should work ``` #! /bin/bash shopt -s nullglob f() { for d in $1/* do [ -d $d ] && f $d done } [ -d $1 ] && f $1 ``` save it as `script.sh` and try ``` bash -x script.sh . ``` should show the dirs.
43,691,884
We are covering the topic of classes at my school. I am supposed create a class called Student that we can use to hold different test scores in a dynamically allocated array. I'm struggling to figure out why when I print out the array of a specific instance of this class, it gives me completely incorrect values. I know my setter function for the class is setting the correct values but whenever I go to print them out they are completely wrong. Below is my code. The commented out portion in main() was just being used to test my logic for the makeArray() function. ``` #include <iostream> using namespace std; class Student { private: string name; int id; int* testptr; int num; void makeArray() { int array[num]; testptr = &array[num]; for (int i = 0; i < num; i++) { array[i] = 0; } } public: Student() { setName("None"); setID(10); num = 3; makeArray(); } Student(int n) { setName("None"); setID(10); if (n > 0) num = n; else num = 3; makeArray(); } Student(string nm, int i, int n) { setName(nm); setID(i); if (n > 0) num = n; else num = 3; makeArray(); } void setName(string nm) { name = nm; } void setID(int i) { if (i >= 10 && i <= 99){ id = i; } else { cout << "Error: Cannot set id to " << i << " for " << getName(); id = 10; } } void setScore(int i, int s) { if ((i >= 0 && i <= num) && (s >= 0 && s <= 100)) { //Here is where I set the values for the array. They come out correct in the console. testptr[i] = s; cout << testptr[i] << endl; } else { cout << "The test " << i << " cannot be set to " << s << " for " << getName() << endl; } } string getName() const { return name; } int getID() const { return id; } void showScore() { //This is where I print out the values of the array. They come out incorrect here. for (int i = 0; i < num; i++) { cout << "Test " << i << " had a score of " << testptr[i] << endl; } } void display() { cout << "Calling the display function" << endl; cout << "The Name: " << getName() << endl; cout << "The ID: " << getID() << endl; showScore(); } ~Student() { } }; int main() { Student c("Joe", 40, 5); c.setScore(0, 90); c.setScore(1, 91); c.setScore(2, 92); c.setScore(3, 93); c.setScore(4, 94); c.display(); /**int* testpointer; int num = 3; int array[num]; testpointer = &array[0]; for (int i = 0; i < num; i++) { testpointer[i] = i; cout << testpointer[i] << endl; }**/ } ```
2017/04/29
[ "https://Stackoverflow.com/questions/43691884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730420/" ]
``` find . -type d -exec function.sh "{}" \; ```
here is a fully expanded example of a tree walker pattern ``` #!/usr/bin/env bash read -d '' help <<EOF usage: $(basename $0) <parameter> this is an example of a tree walker pattern -v Verbose -h Help -p pattern pattern to find -f file the file to process EOF # preset error for param validation OPTERR=0 # presets for variables verbose="" pattern="" file="" # colours Red='\033[31m' Off='\033[0m' # iterate through getopts on options while getopts vhp:f: opt do case $opt in v) verbose="-v";; h) echo -e "$help"; exit 0;; p) pattern=$OPTARG;; f) file=$OPTARG;; \?) echo -e "\nInvalid - $opt\n\n$help\n" >&2; exit 1;; esac done # remove found args leaving the parameter behind shift $((OPTIND-1)) parameter="$1" if [ -z "$file" ] then # no file passed do a find if [ -z "$pattern" ] then echo -e "$help\n\n${Red}please specifiy find pattern with -p${Off}" exit 1 fi find . -iname "$pattern" -exec $0 -f "{}" "$parameter" \; else # file specified, do the work echo $(ls "$file")" -> "$(cat $file) fi ``` where a tree structure like this ``` $ tree one one ├── README.md └── two ├── README.md └── three └── README.md ``` would be traversed like this ``` $ ./traveler.sh -p "*.md" ./one/README.md -> 1 ./one/two/README.md -> 2 ./one/two/three/README.md -> 3 ```
50,342,462
I'm looking for help finding Python functions that allow me to take a list of strings, such as `["I like ", " and ", " because "]` and a single target string, such as `"I like lettuce and carrots and onions because I do"`, and finds all the ways the characters in the target string can be grouped such that each of the strings in the list comes in order. For example: ``` solution(["I like ", " and ", " because ", "do"], "I like lettuce and carrots and onions because I do") ``` should return: ``` [("I like ", "lettuce", " and ", "carrots and onions", " because ", "I ", "do"), ("I like ", "lettuce and carrots", " and ", "onions", " because ", "I ", "do")] ``` Notice that in each of the tuples, the strings in the list parameter are there in order, and the function returns each of the possible ways to split up the target string in order to achieve this. Another example, this time with only one possible way of organizing the characters: ``` solution(["take ", " to the park"], "take Alice to the park") ``` should give the result: ``` [("take ", "Alice", " to the park")] ``` Here's an example where there is no way to organize the characters correctly: ``` solution(["I like ", " because ", ""], "I don't like cheese because I'm lactose-intolerant") ``` should give back: ``` [] ``` because there is no way to do it. Notice that the `"I like "` in the first parameter cannot be split up. The target string doesn't have the string `"I like "` in it, so there's no way it could match. Here's a final example, again with multiple options: ``` solution(["I", "want", "or", "done"], "I want my sandwich or I want my pizza or salad done") ``` should return ``` [("I", " ", "want", " my sandwich ", "or", " I want my pizza or salad ", "done"), ("I", " ", "want", " my sandwich or I want my pizza ", "or", " salad ", "done"), ("I", " want my sandwich or I", "want", " my pizza ", "or", " salad ", "done")]` ``` Notice that, again, each of the strings `["I", "want", "or", "done"]` is included in each of the tuples, in order, and that the rest of the characters are reordered around those strings in any way possible. The list of all the possible reorderings is what is returned. Note that it's also assumed that the first string in the list will appear at the start of the target string, and the last string in the list will appear at the end of the target string. (If they don't, the function should return an empty list.) **What Python functions will allow me to do this?** I've tried using regex functions, but it seems to fail in the cases where there's more than one option.
2018/05/15
[ "https://Stackoverflow.com/questions/50342462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5049813/" ]
I have a solution, it needs a fair bit of refactoring but it seems to work, I hope this helps, it was quite an interesting problem. ``` import itertools import re from collections import deque def solution(search_words, search_string): found = deque() for search_word in search_words: found.append([(m.start()) for m in re.compile(search_word).finditer(search_string)]) if len(found) != len(search_words) or len(found) == 0: return [] # no search words or not all words found word_positions_lst = [list(i) for i in itertools.product(*found) if sorted(list(i)) == list(i)] ret_lst = [] for word_positions in word_positions_lst: split_positions = list(itertools.chain.from_iterable( (split_position, split_position + len(search_word)) for split_position, search_word in zip(word_positions, search_words))) last_seach_word = search_string[split_positions[-1]:] ret_strs = [search_string[a:b] for a, b in zip(split_positions, split_positions[1:])] if last_seach_word: ret_strs.append(last_seach_word) if len(search_string) == sum(map(len,ret_strs)): ret_lst.append(tuple(ret_strs)) return ret_lst print(solution(["I like ", " and ", " because ", "do"], "I like lettuce and carrots and onions because I do")) print([("I like ", "lettuce", " and ", "carrots and onions", " because ", "I ", "do"), ("I like ", "lettuce and carrots", " and ", "onions", " because ", "I ", "do")]) print() print(solution(["take ", " to the park"], "take Alice to the park")) print([("take ", "Alice", " to the park")]) print() print(solution(["I like ", " because "], "I don't like cheese because I'm lactose-intolerant")) print([]) print() ``` Outputs: ``` [('I like ', 'lettuce', ' and ', 'carrots and onions', ' because ', 'I ', 'do'), ('I like ', 'lettuce and carrots', ' and ', 'onions', ' because ', 'I ', 'do')] [('I like ', 'lettuce', ' and ', 'carrots and onions', ' because ', 'I ', 'do'), ('I like ', 'lettuce and carrots', ' and ', 'onions', ' because ', 'I ', 'do')] [('take ', 'Alice', ' to the park')] [('take ', 'Alice', ' to the park')] [] [] [('I', ' ', 'want', ' my sandwich ', 'or', ' I want my pizza or salad ', 'done'), ('I', ' ', 'want', ' my sandwich or I want my pizza ', 'or', ' salad ', 'done'), ('I', ' want my sandwich or I ', 'want', ' my pizza ', 'or', ' salad ', 'done')] [('I', ' ', 'want', ' my sandwich ', 'or', ' I want my pizza or salad ', 'done'), ('I', ' ', 'want', ' my sandwich or I want my pizza ', 'or', ' salad ', 'done'), ('I', ' want my sandwich or I', 'want', ' my pizza ', 'or', ' salad ', 'done')] ``` *Edit: refactored code to have meaningful variable names.* *Edit2: added the last case i forgot about.*
EDIT: I've since learned some programming tactics and redone my answer to this problem. To answer my question, you don't need any special functions. If you'd like a version that's relatively easy to code, look below for a different answer. This solution is also less documented compared to the solution below, but it uses dynamic programming and memoization, so it should be faster than the previous solution, and less memory intensive. It also deals with regex characters (such as `|`) correctly. (The "previous answer" solution below does not.) ``` def solution(fixed_strings, target_string): def get_middle_matches(s, fixed_strings): ''' Gets the fixed strings matches without the first and last first strings Example the parameter tuple ("ABCBD", ["B"]) should give back [["A", "B", "CBD"], ["ABC", "B", "D"]] ''' # in the form {(s, s_index, fixed_string_index, fixed_character_index): return value of recursive_get_middle_matches called with those parameters} lookup = {} def memoized_get_middle_matches(*args): '''memoize the recursive function''' try: ans = lookup[args] return ans except KeyError: ans = recursive_get_middle_matches(*args) lookup[args] = ans return ans def recursive_get_middle_matches(s, s_index, fixed_string_index, fixed_character_index): ''' Takes a string, an index into that string, a index into the list of middle fixed strings, ...and an index into that middle fixed string. Returns what fixed_string_matches(s, fixed_strings[fixed_string_index:-1]) would return, and deals with edge cases. ''' # base case: there's no fixed strings left to match try: fixed_string = fixed_strings[fixed_string_index] except IndexError: # we just finished matching the last fixed string, but there's some stuff left over return [[s]] # recursive case: we've finished matching a fixed string # note that this needs to go before the end of the string base case # ...because otherwise the matched fixed string may not be added to the answer, # ...since getting to the end of the main string will short-circuit it try: fixed_character = fixed_string[fixed_character_index] except IndexError: # finished matching this fixed string upper_slice = s_index lower_slice = upper_slice - len(fixed_string) prefix = s[:lower_slice] match = s[lower_slice:upper_slice] postfix = s[upper_slice:] match_ans = [prefix, match] recursive_answers = memoized_get_middle_matches(postfix, 0, fixed_string_index + 1, 0) if fixed_string == '' and s_index < len(s): recursive_skip_answers = memoized_get_middle_matches(s, s_index + 1, fixed_string_index, fixed_character_index) return [match_ans + recursive_ans for recursive_ans in recursive_answers] + recursive_skip_answers else: return [match_ans + recursive_ans for recursive_ans in recursive_answers] # base cases: we've reached the end of the string try: character = s[s_index] except IndexError: # nothing left to match in the main string if fixed_string_index >= len(fixed_strings): # it completed matching everything it needed to return [[""]] else: # it didn't finish matching everything it needed to return [] # recursive cases: either we match this character or we don't character_matched = (character == fixed_character) starts_fixed_string = (fixed_character_index == 0) if starts_fixed_string: # if this character starts the fixed string, we're still searching for this same fixed string recursive_skip_answers = memoized_get_middle_matches(s, s_index + 1, fixed_string_index, fixed_character_index) if character_matched: recursive_take_answers = memoized_get_middle_matches(s, s_index + 1, fixed_string_index, fixed_character_index + 1) if starts_fixed_string: # we have the option to either take the character as a match, or skip over it return recursive_skip_answers + recursive_take_answers else: # this character is past the start of the fixed string; we can no longer match this fixed string # since we can't match one of the fixed strings, this is a failed path if we don't match this character # thus, we're forced to take this character as a match return recursive_take_answers else: if starts_fixed_string: # we can't match it here, so we skip over and continue return recursive_skip_answers else: # this character is past the start of the fixed string; we can no longer match this fixed string # since we can't match one of the fixed strings, there are no possible matches here return [] ## main code return memoized_get_middle_matches(s, 0, 0, 0) ## main code # doing the one fixed string case first because it happens a lot if len(fixed_strings) == 1: # if it matches, then there's just that one match, otherwise, there's none. if target_string == fixed_strings[0]: return [target_string] else: return [] if len(fixed_strings) == 0: # there's no matches because there are no fixed strings return [] # separate the first and last from the middle first_fixed_string = fixed_strings[0] middle_fixed_strings = fixed_strings[1:-1] last_fixed_string = fixed_strings[-1] prefix = target_string[:len(first_fixed_string)] middle = target_string[len(first_fixed_string):len(target_string)-len(last_fixed_string)] postfix = target_string[len(target_string)-len(last_fixed_string):] # make sure the first and last fixed strings match the target string # if not, the target string does not match if not (prefix == first_fixed_string and postfix == last_fixed_string): return [] else: # now, do the check for the middle fixed strings return [[prefix] + middle + [postfix] for middle in get_middle_matches(middle, middle_fixed_strings)] print(solution(["I like ", " and ", " because ", "do"], "I like lettuce and carrots and onions because I do")) print([("I like ", "lettuce", " and ", "carrots and onions", " because ", "I ", "do"), ("I like ", "lettuce and carrots", " and ", "onions", " because ", "I ", "do")]) print() print(solution(["take ", " to the park"], "take Alice to the park")) print([("take ", "Alice", " to the park")]) print() # Courtesy of @ktzr print(solution(["I like ", " because "], "I don't like cheese because I'm lactose-intolerant")) print([]) print() print(solution(["I", "want", "or", "done"], "I want my sandwich or I want my pizza or salad done")) print([("I", " ", "want", " my sandwich ", "or", " I want my pizza or salad ", "done"), ("I", " ", "want", " my sandwich or I want my pizza ", "or", " salad ", "done"), ("I", " want my sandwich or I", "want", " my pizza ", "or", " salad ", "done")]) ``` **Previous answer:** To answer my question, the **`itertools.product`** function and **`regex.finditer`** with the `overlapped` parameter were the two key functions to this solution. I figured I'd include my final code in case it helps someone else in a similar situation. I really care about my code being super readable, so I ended up coding my own solution based on @ktzr's solution. (Thank you!) My solution uses a couple of weird things. First, it uses a `overlapped` parameter, which is only available through the `regex` module, and must be installed (most likely via `pip install regex`). Then, include it at the top with `import regex as re`. This makes it easy to search for overlapped matches in a string. Second, my solution makes use of an itertools function that isn't explicitly included in the library, which you have to define as such: ``` import itertools def itertools_pairwise(iterable): '''s -> (s0,s1), (s1,s2), (s2, s3), ...''' a, b = itertools.tee(iterable) next(b, None) return zip(a, b) ``` This function simply lets me iterate pairwise through a list, making sure each element (except for the first and last) in the list is encountered twice. With those two things in place, here's my solution: ``` def solution(fixed_strings, target_string): # doing the one fixed string case first because it happens a lot if len(fixed_strings) == 1: # if it matches, then there's just that one match, otherwise, there's none. if target_string == fixed_strings[0]: return [target_string] else: return [] # make sure the first and last fixed strings match the target string # if not, the target string does not match if not (target_string.startswith(fixed_strings[0]) and target_string.endswith(fixed_strings[-1])): return [] # get the fixed strings in the middle that it now needs to search for in the middle of the target string middle_fixed_strings = fixed_strings[1:-1] # where in the target string it found the middle fixed strings. # middle_fixed_strings_placements is in the form: [[where it found the 1st middle fixed string], ...] # [where it found the xth middle fixed string] is in the form: [(start index, end index), ...] middle_fixed_strings_placements = [[match.span() for match in re.finditer(string, target_string, overlapped=True)] for string in middle_fixed_strings] # if any of the fixed strings couldn't be found in the target string, there's no matches if [] in middle_fixed_strings_placements: return [] # get all of the possible ways each of the middle strings could be found once within the target string all_placements = itertools.product(*middle_fixed_strings_placements) # remove the cases where the middle strings overlap or are out of order good_placements = [placement for placement in all_placements if not (True in [placement[index][1] > placement[index + 1][0] for index in range(len(placement) - 1)])] # create a list of all the possible final matches matches = [] target_string_len = len(target_string) # cache for later # save the start and end spans which are predetermined by their length and placement start_span = (0, len(fixed_strings[0])) end_span = (target_string_len - len(fixed_strings[-1]), target_string_len) for placement in good_placements: placement = list(placement) # add in the spans for the first and last fixed strings # this makes it so each placement is in the form: [1st fixed string span, ..., last fixed string span] placement.insert(0, start_span) placement.append(end_span) # flatten the placements list to get the places where we need to cut up the string. # we want to cut the string at the span values to get out the fixed strings cuts = [cut for span in placement for cut in span] match = [] # go through the cuts and make them to create the list for start_cut, end_cut in itertools_pairwise(cuts): match.append(target_string[start_cut:end_cut]) matches.append(match) return matches ```
13,444,551
I have been staring at this all night now. I am trying to make a simple interactive ball game for Android, but I just can't seem to get the onFling method working. My logs that are in onFling don't appear in LogCat, and there is no response to a fling gesture. I think I'm doing something wrong with the gesturedetector or gesturelistener. Please help me out so I can finally go to sleep :) . This is my code: This is outside of onCreate, but still in the Activity: ``` @Override public boolean onTouchEvent(MotionEvent me) { return gestureDetector.onTouchEvent(me); } SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { ballSpeed.x = velocityX; ballSpeed.y = velocityY; Log.d("TAG", "----> velocityX: " + velocityX); Log.d("TAG", "----> velocityY: " + velocityY); return true; } }; GestureDetector gestureDetector = new GestureDetector(null, simpleOnGestureListener); ``` **EDIT:** Apparently the above code does work. That means that the mistake is somewhere else. @bobnoble says that I should post my onCreate() method: ``` @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); // hide title bar getWindow().setFlags(0xFFFFFFFF,LayoutParams.FLAG_FULLSCREEN| LayoutParams.FLAG_KEEP_SCREEN_ON); super.onCreate(savedInstanceState); setContentView(R.layout.main); // create pointer to main screen final FrameLayout mainView = (android.widget.FrameLayout) findViewById(R.id.main_view); // get screen dimensions Display display = getWindowManager().getDefaultDisplay(); try { display.getSize(size); screenWidth = size.x; screenHeight = size.y; } catch (NoSuchMethodError e) { screenWidth = display.getWidth(); screenHeight = display.getHeight(); } ballPosition = new android.graphics.PointF(); ballSpeed = new android.graphics.PointF(); // create variables for ball position and speed ballPosition.x = 4 * screenWidth / 5; ballPosition.y = 2 * screenHeight / 3; ballSpeed.x = 0; ballSpeed.y = 0; // create initial ball ballView = new BallView(this, ballPosition.x, ballPosition.y, 20); mainView.addView(ballView); // add ball to main screen ballView.invalidate(); // call onDraw in BallView //listener for touch event mainView.setOnTouchListener(new android.view.View.OnTouchListener() { public boolean onTouch(android.view.View v, android.view.MotionEvent e) { //set ball position based on screen touch ballPosition.x = e.getX(); ballPosition.y = e.getY(); ballSpeed.y = 0; ballSpeed.x = 0; //timer event will redraw ball return true; }}); } ```
2012/11/18
[ "https://Stackoverflow.com/questions/13444551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270930/" ]
I put the code you provided into an `Activity`, commenting out the `ballSpeed` lines and added `Log` output. Works as expected. The logcat showing the output is at the end. If this does not work for you, the issue is somewhere else in your `Activity` code. You may want to post your `onCreate` method. ``` @Override public boolean onTouchEvent(MotionEvent me) { Log.i(TAG, "onTouchEvent occurred..."); return gestureDetector.onTouchEvent(me); } SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { Log.i(TAG, "onDown event occurred..."); return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // ballSpeed.x = velocityX; // ballSpeed.y = velocityY; Log.d("TAG", "----> velocityX: " + velocityX); Log.d("TAG", "----> velocityY: " + velocityY); return true; } }; GestureDetector gestureDetector = new GestureDetector(null, simpleOnGestureListener); ``` Logcat shows multiple `onTouchEvent`s, the `onDown` and the `onFling` ``` 11-18 15:51:25.364: I/SO_MainActivity(13415): onTouchEvent occurred... 11-18 15:51:25.364: I/SO_MainActivity(13415): onDown event occurred... ... 11-18 15:51:25.584: I/SO_MainActivity(13415): onTouchEvent occurred... 11-18 15:51:25.604: I/SO_MainActivity(13415): onTouchEvent occurred... 11-18 15:51:25.664: D/TAG(13415): ----> velocityX: 3198.8127 11-18 15:51:25.664: D/TAG(13415): ----> velocityY: -1447.966 ``` Edit based on looking at the `onCreate` method: The `mainView.setOnTouchListener` `onTouch` method is consuming the touches by returning true. By returning true, the `onTouch` method is indicating it has completely handled the touch event, and not to propagate it further. Change it to `return false;` will cause it to propagate the touch event and you should see the other touch event methods getting called.
Do you have `implements OnGestureListener' on your Activity declaration? See this snippet <http://www.androidsnippets.com/gesturedetector-and-gesturedetectorongesturelistener>
3,982,456
> > **Possible Duplicate:** > > [FindBugs for .Net](https://stackoverflow.com/questions/397641/findbugs-for-net) > > > I need something like [FindBugs](http://findbugs.sourceforge.net/) for C#/.NET ... Could you tell me where I can find something like this ? Thanks.
2010/10/20
[ "https://Stackoverflow.com/questions/3982456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/272774/" ]
[FxCop](http://msdn.microsoft.com/en-us/library/bb429476.aspx) is a static analysis tool for .NET that has the ability to detect various possible bugs as well as advise you of good programming practices and Microsoft naming conventions. It seems like Microsoft have stopped development on the standalone FxCop tool now in favour of encouraging you to buy a version of Visual Studio with the static code analysis built in (which I think for VS2010 is the "Premium" edition and above).
You might want to have a look at FxCop. It's probably the most popular static code analysis tool for .NET.
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
This problem, in my case, wasn't related to the Insert key. It was related to Vrapper being enabled and editing like Vim, without my knowledge. I just toggled the Vrapper Icon in Eclipse top bar of menus and then pressed the Insert Key and the problem was solved. Hopefully this answer will help someone in the future.
This issue can happen not only in [eclipse](/questions/tagged/eclipse "show questions tagged 'eclipse'") but also in any of the [text-editor](/questions/tagged/text-editor "show questions tagged 'text-editor'"). On [windows](/questions/tagged/windows "show questions tagged 'windows'") systems, [windows-10](/questions/tagged/windows-10 "show questions tagged 'windows-10'") in my case, this issue arose when the `shift` and `insert` key was pressed in tandem unintentionally which takes the user to the **overwrite** mode. To get back to **insert** mode you need to press `shift` and `insert` in tandem again.
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
The problem is also identified in your status bar at the bottom: [![overwrite label in status bar](https://i.stack.imgur.com/LeaRC.png)](https://i.stack.imgur.com/LeaRC.png) You are in overwrite mode instead of insert mode. **The “Insert” key toggles between insert and overwrite modes.**
It sounds like you hit the "Insert" key .. in most applications this results in a fat (solid rectangle) cursor being displayed, as your screenshot suggests. This indicates that you are in *overwrite* mode rather than the default *insert* mode. Just hit the "insert" key on your keyboard once more... it's usually near the 'delete' (not backspace), scroll lock and 'Print Screen' (often above the cursor keys in a full size keyboard.) This will switch back to insert mode and turn your cursor into a vertical line rather than a rectangle.
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
It sounds like you hit the "Insert" key .. in most applications this results in a fat (solid rectangle) cursor being displayed, as your screenshot suggests. This indicates that you are in *overwrite* mode rather than the default *insert* mode. Just hit the "insert" key on your keyboard once more... it's usually near the 'delete' (not backspace), scroll lock and 'Print Screen' (often above the cursor keys in a full size keyboard.) This will switch back to insert mode and turn your cursor into a vertical line rather than a rectangle.
This problem, in my case, wasn't related to the Insert key. It was related to Vrapper being enabled and editing like Vim, without my knowledge. I just toggled the Vrapper Icon in Eclipse top bar of menus and then pressed the Insert Key and the problem was solved. Hopefully this answer will help someone in the future.
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
You might have pressed `0` (also used for insert, shortcut `INS`) key, which is on the right side of your right scroll button. To solve the problem, just press it again or double click on 'overwrite'.
This issue can happen not only in [eclipse](/questions/tagged/eclipse "show questions tagged 'eclipse'") but also in any of the [text-editor](/questions/tagged/text-editor "show questions tagged 'text-editor'"). On [windows](/questions/tagged/windows "show questions tagged 'windows'") systems, [windows-10](/questions/tagged/windows-10 "show questions tagged 'windows-10'") in my case, this issue arose when the `shift` and `insert` key was pressed in tandem unintentionally which takes the user to the **overwrite** mode. To get back to **insert** mode you need to press `shift` and `insert` in tandem again.
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
It sounds like you hit the "Insert" key .. in most applications this results in a fat (solid rectangle) cursor being displayed, as your screenshot suggests. This indicates that you are in *overwrite* mode rather than the default *insert* mode. Just hit the "insert" key on your keyboard once more... it's usually near the 'delete' (not backspace), scroll lock and 'Print Screen' (often above the cursor keys in a full size keyboard.) This will switch back to insert mode and turn your cursor into a vertical line rather than a rectangle.
This issue can happen not only in [eclipse](/questions/tagged/eclipse "show questions tagged 'eclipse'") but also in any of the [text-editor](/questions/tagged/text-editor "show questions tagged 'text-editor'"). On [windows](/questions/tagged/windows "show questions tagged 'windows'") systems, [windows-10](/questions/tagged/windows-10 "show questions tagged 'windows-10'") in my case, this issue arose when the `shift` and `insert` key was pressed in tandem unintentionally which takes the user to the **overwrite** mode. To get back to **insert** mode you need to press `shift` and `insert` in tandem again.
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
You might have pressed `0` (also used for insert, shortcut `INS`) key, which is on the right side of your right scroll button. To solve the problem, just press it again or double click on 'overwrite'.
In my case, it's related to the **Toggle Vrapper Icon** in the Eclipse. If you are getting the bold black cursor, then the icon must be enabled. So, click on the Toggle Vrapper Icon to disable. It's located in the Eclipse's Toolbar. Please see the attached image for the clarity. [![enter image description here](https://i.stack.imgur.com/tAX21.jpg)](https://i.stack.imgur.com/tAX21.jpg)
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
This issue can happen not only in [eclipse](/questions/tagged/eclipse "show questions tagged 'eclipse'") but also in any of the [text-editor](/questions/tagged/text-editor "show questions tagged 'text-editor'"). On [windows](/questions/tagged/windows "show questions tagged 'windows'") systems, [windows-10](/questions/tagged/windows-10 "show questions tagged 'windows-10'") in my case, this issue arose when the `shift` and `insert` key was pressed in tandem unintentionally which takes the user to the **overwrite** mode. To get back to **insert** mode you need to press `shift` and `insert` in tandem again.
In my case, it's related to the **Toggle Vrapper Icon** in the Eclipse. If you are getting the bold black cursor, then the icon must be enabled. So, click on the Toggle Vrapper Icon to disable. It's located in the Eclipse's Toolbar. Please see the attached image for the clarity. [![enter image description here](https://i.stack.imgur.com/tAX21.jpg)](https://i.stack.imgur.com/tAX21.jpg)
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
It sounds like you hit the "Insert" key .. in most applications this results in a fat (solid rectangle) cursor being displayed, as your screenshot suggests. This indicates that you are in *overwrite* mode rather than the default *insert* mode. Just hit the "insert" key on your keyboard once more... it's usually near the 'delete' (not backspace), scroll lock and 'Print Screen' (often above the cursor keys in a full size keyboard.) This will switch back to insert mode and turn your cursor into a vertical line rather than a rectangle.
You might have pressed `0` (also used for insert, shortcut `INS`) key, which is on the right side of your right scroll button. To solve the problem, just press it again or double click on 'overwrite'.
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
You might have pressed `0` (also used for insert, shortcut `INS`) key, which is on the right side of your right scroll button. To solve the problem, just press it again or double click on 'overwrite'.
This problem, in my case, wasn't related to the Insert key. It was related to Vrapper being enabled and editing like Vim, without my knowledge. I just toggled the Vrapper Icon in Eclipse top bar of menus and then pressed the Insert Key and the problem was solved. Hopefully this answer will help someone in the future.
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
The problem is also identified in your status bar at the bottom: [![overwrite label in status bar](https://i.stack.imgur.com/LeaRC.png)](https://i.stack.imgur.com/LeaRC.png) You are in overwrite mode instead of insert mode. **The “Insert” key toggles between insert and overwrite modes.**
This issue can happen not only in [eclipse](/questions/tagged/eclipse "show questions tagged 'eclipse'") but also in any of the [text-editor](/questions/tagged/text-editor "show questions tagged 'text-editor'"). On [windows](/questions/tagged/windows "show questions tagged 'windows'") systems, [windows-10](/questions/tagged/windows-10 "show questions tagged 'windows-10'") in my case, this issue arose when the `shift` and `insert` key was pressed in tandem unintentionally which takes the user to the **overwrite** mode. To get back to **insert** mode you need to press `shift` and `insert` in tandem again.
54,588,347
I am encrypting a changeset with a bunch of optional fields, but I am currently using a ton of If statements to see if a changeset contains a field before trying to encrypt it. I have a feeling there is an Enum function (like reduce) that would do this in a way that is idiomatically more Elixir, but none of what I have come up with is more performant than a ton of ugly If statements. ``` def encrypt(changeset) do if changeset.changes["address"] do {:ok, encrypted_address} = EncryptedField.dump(changeset.changes.address, key_id) changeset |> put_change(:address, encrypted_address) end if changeset.changes["dob"] do {:ok, encrypted_dob} = EncryptedField.dump(changeset.changes.dob, key_id) changeset |> put_change(:address, encrypted_dob) end if changeset.changes["email"] do {:ok, encrypted_email} = EncryptedField.dump(changeset.changes.email, key_id) changeset |> put_change(:email, encrypted_email) end ... end ```
2019/02/08
[ "https://Stackoverflow.com/questions/54588347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10350915/" ]
All you need is to iterate through fields, conditionally updating the changeset: ```rb def encrypt(changeset) do Enum.reduce(~w[address dob email]a, changeset, fn field, changeset -> if changeset.changes[field] do {:ok, encrypted} = EncryptedField.dump(changeset.changes[field], key_id) put_change(changeset, field, encrypted) else changeset # unlike your implementation this works end end) end ``` --- Another way would be to [`Enum.filter/2`](https://hexdocs.pm/elixir/Enum.html#filter/2) the fields in the first place: ```rb def encrypt(changeset) do ~w[address dob email]a |> Enum.filter(&changeset.changes[&1]) |> Enum.reduce(changeset, fn field, changeset -> {:ok, encrypted} = EncryptedField.dump(changeset.changes[field], key_id) put_change(changeset, field, encrypted) end) end ``` --- *Sidenote:* according to style guidelines by the core team, pipes are to be used if and only there are many links in the chain. --- *Reply to the second answer:* Idiomatic code using `with` would be: ```rb def encrypt(changeset) do ~w[address dob email] |> Enum.reduce(changeset, fn field -> with %{^field => value} <- changeset.changes, {:ok, encrypted} <- EncryptedField.dump(value, key_id) do put_change(changeset, field, encrypted) else _ -> changeset end end) end ```
Agree with Aleksei's answer. Another pattern in elixir is that if you have a series of checks before running an expression, you can use `with`. Aleksei's code using `with` would be something like ``` def encrypt(changeset) do ~w[address dob email] |> Enum.reduce(changeset, fn field -> with \ true <- Map.has_key?(changeset.changes, field), {:ok, encrypted} <- EncryptedField.dump(changeset.changes[field], key_id) do put_change(changeset, field, encrypted) else _ -> changeset end end) end ``` Here, if `EncryptedField.dump` returns an `:error`, changeset is returned instead of throwing an exception if you do `{:ok, val} = EncryptedField.dump(...)`. P.S: also recommend using `Map.has_key?`
3,532,587
> > If $p,q,r,x,y,z$ are non zero real number such that > > > $px+qy+rz+\sqrt{(p^2+q^2+r^2)(x^2+y^2+z^2)}=0$ > > > Then $\displaystyle \frac{py}{qx}+\frac{qz}{ry}+\frac{rx}{pz}$ is > > > what try $(px+qy+rz)^2=(p^2+q^2+r^2)(x^2+y^2+z^2)$ $p^2x^2+q^2y^2+r^2z^2+2pqxy+2qryz+2prxz=p^2x^2+p^2y^2+p^2z^2+q^2x^2+q^2y^2+q^2z^2+r^2x^2+r^2y^2+r^2z^2$ $2pqxy+2qryz+2prxz=p^2y^2+p^2z^2+q^2x^2+q^2z^2+r^2x^2+r^2y^2$ How do i solve it Help me please
2020/02/03
[ "https://math.stackexchange.com/questions/3532587", "https://math.stackexchange.com", "https://math.stackexchange.com/users/14096/" ]
Write $v=(p,q,r)$ and $w=(x,y,z)$. Then the given relation states $$v\cdot w+|v||w|=0$$ But $v\cdot w=|v||w|\cos\theta$ where $\theta$ is the angle between them, so $$|v||w|(\cos\theta+1)=0$$ Since none of the scalars are zero, we get $\cos\theta=-1$, so $v=kw$ for some nonzero $k\in\mathbb R$ and $$\frac{py}{qx}+\frac{qz}{ry}+\frac{rx}{pz}=\frac{kxy}{kyx}+\frac{kyz}{kzy}+\frac{kzx}{kxz}=3$$
By C-S $$0=px+qy+rz+\sqrt{(p^2+q^2+r^2)(x^2+y^2+z^2)}\geq px+qy+rz+|px+qy+rz|$$ and since $$px+qy+rz+|px+qy+rz|\geq0,$$ we obtain $$px+qy+rz+|px+qy+rz|=0,$$ which gives $$px+qy+rz\leq0.$$ Also, the equality occurs for $$(x,y,z)||(p,q,r),$$ which says that there is $k<0$, for which $$(p,q,r)=k(x,y,z).$$ Thus, $$\sum\_{cyc}\frac{py}{qx}=\sum\_{cyc}\frac{kxy}{kyx}=3.$$
2,285,472
``` class User < ActiveRecord::Base has_one :location, :dependent => :destroy, :as => :locatable has_one :ideal_location, :dependent => :destroy, :as => :locatable has_one :birthplace, :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end class IdealLocation < ActiveRecord::Base end class Birthplace < ActiveRecord::Base end ``` I can't really see any reason to have subclasses in this situation. The behavior of the location objects are identical, the only point of them is to make the associations easy. I also would prefer to store the data as an int and not a string as it will allow the database indexes to be smaller. I envision something like the following, but I can't complete the thought: ``` class User < ActiveRecord::Base LOCATION_TYPES = { :location => 1, :ideal_location => 2, :birthplace => 3 } has_one :location, :conditions => ["type = ?", LOCATION_TYPES[:location]], :dependent => :destroy, :as => :locatable has_one :ideal_location, :conditions => ["type = ?", LOCATION_TYPES[:ideal_location]], :dependent => :destroy, :as => :locatable has_one :birthplace, :conditions => ["type = ?", LOCATION_TYPES[:birthplace]], :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end ``` With this code the following fails, basically making it useless: ``` user = User.first location = user.build_location location.city = "Cincinnati" location.state = "Ohio" location.save! location.type # => nil ``` This is obvious because there is no way to translate the :conditions options on the has\_one declaration into the type equaling 1. I could embed the id in the view anywhere these fields appear, but this seems wrong too: ``` <%= f.hidden_field :type, LOCATION_TYPES[:location] %> ``` Is there any way to avoid the extra subclasses or make the LOCATION\_TYPES approach work? In our particular case the application is very location aware and objects can have many different types of locations. Am I just being weird not wanting all those subclasses? Any suggestions you have are appreciated, tell me I'm crazy if you want, but would you want to see 10+ different location models floating around app/models?
2010/02/18
[ "https://Stackoverflow.com/questions/2285472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86820/" ]
Why not use named\_scopes? Something like: ``` class User has_many :locations end class Location named_scope :ideal, :conditions => "type = 'ideal'" named_scope :birthplace, :conditions => "type = 'birthplace" # or whatever end ``` Then in your code: ``` user.locations.ideal => # list of ideal locations user.locations.birthplace => # list of birthplace locations ``` You'd still have to handle setting the type on creation, I think.
Try adding before\_save hooks ``` class Location def before_save self.type = 1 end end ``` and likewise for the other types of location
2,285,472
``` class User < ActiveRecord::Base has_one :location, :dependent => :destroy, :as => :locatable has_one :ideal_location, :dependent => :destroy, :as => :locatable has_one :birthplace, :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end class IdealLocation < ActiveRecord::Base end class Birthplace < ActiveRecord::Base end ``` I can't really see any reason to have subclasses in this situation. The behavior of the location objects are identical, the only point of them is to make the associations easy. I also would prefer to store the data as an int and not a string as it will allow the database indexes to be smaller. I envision something like the following, but I can't complete the thought: ``` class User < ActiveRecord::Base LOCATION_TYPES = { :location => 1, :ideal_location => 2, :birthplace => 3 } has_one :location, :conditions => ["type = ?", LOCATION_TYPES[:location]], :dependent => :destroy, :as => :locatable has_one :ideal_location, :conditions => ["type = ?", LOCATION_TYPES[:ideal_location]], :dependent => :destroy, :as => :locatable has_one :birthplace, :conditions => ["type = ?", LOCATION_TYPES[:birthplace]], :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end ``` With this code the following fails, basically making it useless: ``` user = User.first location = user.build_location location.city = "Cincinnati" location.state = "Ohio" location.save! location.type # => nil ``` This is obvious because there is no way to translate the :conditions options on the has\_one declaration into the type equaling 1. I could embed the id in the view anywhere these fields appear, but this seems wrong too: ``` <%= f.hidden_field :type, LOCATION_TYPES[:location] %> ``` Is there any way to avoid the extra subclasses or make the LOCATION\_TYPES approach work? In our particular case the application is very location aware and objects can have many different types of locations. Am I just being weird not wanting all those subclasses? Any suggestions you have are appreciated, tell me I'm crazy if you want, but would you want to see 10+ different location models floating around app/models?
2010/02/18
[ "https://Stackoverflow.com/questions/2285472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86820/" ]
As far as I can see it, a Location is a location is a Location. The different "subclasses" you're referring to (IdealLocation, Birthplace) seem to just be describing the location's relationship to a particular User. Stop me if I've got that part wrong. Knowing that, I can see two solutions to this. The first is to treat locations as value objects rather than entities. (For more on the terms: [Value vs Entity objects (Domain Driven Design)](https://stackoverflow.com/questions/75446/value-vs-entity-objects-domain-driven-design)). In the example above, you seem to be setting the location to "Cincinnati, OH", rather than finding a "Cincinnati, OH" object from the database. In that case, if many different users existed in Cincinnati, you'd have just as many identical "Cincinnati, OH" locations in your database, though there's only one Cincinnati, OH. To me, that's a clear sign that you're working with a value object, not an entity. How would this solution look? Likely using a simple Location object like this: ``` class Location attr_accessor :city, :state def initialize(options={}) @city = options[:city] @state = options[:state] end end class User < ActiveRecord::Base serialize :location serialize :ideal_location serialize :birthplace end @user.ideal_location = Location.new(:city => "Cincinnati", :state => "OH") @user.birthplace = Location.new(:city => "Detroit", :state => "MI") @user.save! @user.ideal_location.state # => "OH" ``` The other solution I can see is to use your existing Location ActiveRecord model, but simply use the relationship with User to define the relationship "type", like so: ``` class User < ActiveRecord::Base belongs_to :location, :dependent => :destroy belongs_to :ideal_location, :class_name => "Location", :dependent => :destroy belongs_to :birthplace, :class_name => "Location", :dependent => :destroy end class Location < ActiveRecord::Base end ``` All you'd need to do to make this work is include location\_id, ideal\_location\_id, and birthplace\_id attributes in your User model.
Try adding before\_save hooks ``` class Location def before_save self.type = 1 end end ``` and likewise for the other types of location
2,285,472
``` class User < ActiveRecord::Base has_one :location, :dependent => :destroy, :as => :locatable has_one :ideal_location, :dependent => :destroy, :as => :locatable has_one :birthplace, :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end class IdealLocation < ActiveRecord::Base end class Birthplace < ActiveRecord::Base end ``` I can't really see any reason to have subclasses in this situation. The behavior of the location objects are identical, the only point of them is to make the associations easy. I also would prefer to store the data as an int and not a string as it will allow the database indexes to be smaller. I envision something like the following, but I can't complete the thought: ``` class User < ActiveRecord::Base LOCATION_TYPES = { :location => 1, :ideal_location => 2, :birthplace => 3 } has_one :location, :conditions => ["type = ?", LOCATION_TYPES[:location]], :dependent => :destroy, :as => :locatable has_one :ideal_location, :conditions => ["type = ?", LOCATION_TYPES[:ideal_location]], :dependent => :destroy, :as => :locatable has_one :birthplace, :conditions => ["type = ?", LOCATION_TYPES[:birthplace]], :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end ``` With this code the following fails, basically making it useless: ``` user = User.first location = user.build_location location.city = "Cincinnati" location.state = "Ohio" location.save! location.type # => nil ``` This is obvious because there is no way to translate the :conditions options on the has\_one declaration into the type equaling 1. I could embed the id in the view anywhere these fields appear, but this seems wrong too: ``` <%= f.hidden_field :type, LOCATION_TYPES[:location] %> ``` Is there any way to avoid the extra subclasses or make the LOCATION\_TYPES approach work? In our particular case the application is very location aware and objects can have many different types of locations. Am I just being weird not wanting all those subclasses? Any suggestions you have are appreciated, tell me I'm crazy if you want, but would you want to see 10+ different location models floating around app/models?
2010/02/18
[ "https://Stackoverflow.com/questions/2285472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86820/" ]
Why not use named\_scopes? Something like: ``` class User has_many :locations end class Location named_scope :ideal, :conditions => "type = 'ideal'" named_scope :birthplace, :conditions => "type = 'birthplace" # or whatever end ``` Then in your code: ``` user.locations.ideal => # list of ideal locations user.locations.birthplace => # list of birthplace locations ``` You'd still have to handle setting the type on creation, I think.
You can encapsulate the behavior of Location objects using modules, and use some macro to create the relationship: ``` has_one <location_class>,: conditions => [ "type =?" LOCATION_TYPES [: location]],: dependent =>: destroy,: as =>: locatable ``` You can use something like this in your module: ``` module Orders def self.included(base) base.extend(ClassMethods) end module ClassMethods def some_class_method(param) end def some_other_class_method(param) end module InstanceMethods def some_instance_method end end end end ``` [Rails guides: add-an-acts-as-method-to-active-record](http://guides.rubyonrails.org/plugins.html#add-an-acts-as-method-to-active-record)
2,285,472
``` class User < ActiveRecord::Base has_one :location, :dependent => :destroy, :as => :locatable has_one :ideal_location, :dependent => :destroy, :as => :locatable has_one :birthplace, :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end class IdealLocation < ActiveRecord::Base end class Birthplace < ActiveRecord::Base end ``` I can't really see any reason to have subclasses in this situation. The behavior of the location objects are identical, the only point of them is to make the associations easy. I also would prefer to store the data as an int and not a string as it will allow the database indexes to be smaller. I envision something like the following, but I can't complete the thought: ``` class User < ActiveRecord::Base LOCATION_TYPES = { :location => 1, :ideal_location => 2, :birthplace => 3 } has_one :location, :conditions => ["type = ?", LOCATION_TYPES[:location]], :dependent => :destroy, :as => :locatable has_one :ideal_location, :conditions => ["type = ?", LOCATION_TYPES[:ideal_location]], :dependent => :destroy, :as => :locatable has_one :birthplace, :conditions => ["type = ?", LOCATION_TYPES[:birthplace]], :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end ``` With this code the following fails, basically making it useless: ``` user = User.first location = user.build_location location.city = "Cincinnati" location.state = "Ohio" location.save! location.type # => nil ``` This is obvious because there is no way to translate the :conditions options on the has\_one declaration into the type equaling 1. I could embed the id in the view anywhere these fields appear, but this seems wrong too: ``` <%= f.hidden_field :type, LOCATION_TYPES[:location] %> ``` Is there any way to avoid the extra subclasses or make the LOCATION\_TYPES approach work? In our particular case the application is very location aware and objects can have many different types of locations. Am I just being weird not wanting all those subclasses? Any suggestions you have are appreciated, tell me I'm crazy if you want, but would you want to see 10+ different location models floating around app/models?
2010/02/18
[ "https://Stackoverflow.com/questions/2285472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86820/" ]
As far as I can see it, a Location is a location is a Location. The different "subclasses" you're referring to (IdealLocation, Birthplace) seem to just be describing the location's relationship to a particular User. Stop me if I've got that part wrong. Knowing that, I can see two solutions to this. The first is to treat locations as value objects rather than entities. (For more on the terms: [Value vs Entity objects (Domain Driven Design)](https://stackoverflow.com/questions/75446/value-vs-entity-objects-domain-driven-design)). In the example above, you seem to be setting the location to "Cincinnati, OH", rather than finding a "Cincinnati, OH" object from the database. In that case, if many different users existed in Cincinnati, you'd have just as many identical "Cincinnati, OH" locations in your database, though there's only one Cincinnati, OH. To me, that's a clear sign that you're working with a value object, not an entity. How would this solution look? Likely using a simple Location object like this: ``` class Location attr_accessor :city, :state def initialize(options={}) @city = options[:city] @state = options[:state] end end class User < ActiveRecord::Base serialize :location serialize :ideal_location serialize :birthplace end @user.ideal_location = Location.new(:city => "Cincinnati", :state => "OH") @user.birthplace = Location.new(:city => "Detroit", :state => "MI") @user.save! @user.ideal_location.state # => "OH" ``` The other solution I can see is to use your existing Location ActiveRecord model, but simply use the relationship with User to define the relationship "type", like so: ``` class User < ActiveRecord::Base belongs_to :location, :dependent => :destroy belongs_to :ideal_location, :class_name => "Location", :dependent => :destroy belongs_to :birthplace, :class_name => "Location", :dependent => :destroy end class Location < ActiveRecord::Base end ``` All you'd need to do to make this work is include location\_id, ideal\_location\_id, and birthplace\_id attributes in your User model.
You can encapsulate the behavior of Location objects using modules, and use some macro to create the relationship: ``` has_one <location_class>,: conditions => [ "type =?" LOCATION_TYPES [: location]],: dependent =>: destroy,: as =>: locatable ``` You can use something like this in your module: ``` module Orders def self.included(base) base.extend(ClassMethods) end module ClassMethods def some_class_method(param) end def some_other_class_method(param) end module InstanceMethods def some_instance_method end end end end ``` [Rails guides: add-an-acts-as-method-to-active-record](http://guides.rubyonrails.org/plugins.html#add-an-acts-as-method-to-active-record)
2,285,472
``` class User < ActiveRecord::Base has_one :location, :dependent => :destroy, :as => :locatable has_one :ideal_location, :dependent => :destroy, :as => :locatable has_one :birthplace, :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end class IdealLocation < ActiveRecord::Base end class Birthplace < ActiveRecord::Base end ``` I can't really see any reason to have subclasses in this situation. The behavior of the location objects are identical, the only point of them is to make the associations easy. I also would prefer to store the data as an int and not a string as it will allow the database indexes to be smaller. I envision something like the following, but I can't complete the thought: ``` class User < ActiveRecord::Base LOCATION_TYPES = { :location => 1, :ideal_location => 2, :birthplace => 3 } has_one :location, :conditions => ["type = ?", LOCATION_TYPES[:location]], :dependent => :destroy, :as => :locatable has_one :ideal_location, :conditions => ["type = ?", LOCATION_TYPES[:ideal_location]], :dependent => :destroy, :as => :locatable has_one :birthplace, :conditions => ["type = ?", LOCATION_TYPES[:birthplace]], :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end ``` With this code the following fails, basically making it useless: ``` user = User.first location = user.build_location location.city = "Cincinnati" location.state = "Ohio" location.save! location.type # => nil ``` This is obvious because there is no way to translate the :conditions options on the has\_one declaration into the type equaling 1. I could embed the id in the view anywhere these fields appear, but this seems wrong too: ``` <%= f.hidden_field :type, LOCATION_TYPES[:location] %> ``` Is there any way to avoid the extra subclasses or make the LOCATION\_TYPES approach work? In our particular case the application is very location aware and objects can have many different types of locations. Am I just being weird not wanting all those subclasses? Any suggestions you have are appreciated, tell me I'm crazy if you want, but would you want to see 10+ different location models floating around app/models?
2010/02/18
[ "https://Stackoverflow.com/questions/2285472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86820/" ]
Why not use named\_scopes? Something like: ``` class User has_many :locations end class Location named_scope :ideal, :conditions => "type = 'ideal'" named_scope :birthplace, :conditions => "type = 'birthplace" # or whatever end ``` Then in your code: ``` user.locations.ideal => # list of ideal locations user.locations.birthplace => # list of birthplace locations ``` You'd still have to handle setting the type on creation, I think.
Maybe I'm missing something important here, but I thought you could name your relationships like this: ``` class User < ActiveRecord::Base has_one :location, :dependent => :destroy #ideal_location_id has_one :ideal_location, :class_name => "Location", :dependent => :destroy #birthplace_id has_one :birthplace, :class_name => "Location", :dependent => :destroy end class Location < ActiveRecord::Base belongs_to :user # user_id end ```
2,285,472
``` class User < ActiveRecord::Base has_one :location, :dependent => :destroy, :as => :locatable has_one :ideal_location, :dependent => :destroy, :as => :locatable has_one :birthplace, :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end class IdealLocation < ActiveRecord::Base end class Birthplace < ActiveRecord::Base end ``` I can't really see any reason to have subclasses in this situation. The behavior of the location objects are identical, the only point of them is to make the associations easy. I also would prefer to store the data as an int and not a string as it will allow the database indexes to be smaller. I envision something like the following, but I can't complete the thought: ``` class User < ActiveRecord::Base LOCATION_TYPES = { :location => 1, :ideal_location => 2, :birthplace => 3 } has_one :location, :conditions => ["type = ?", LOCATION_TYPES[:location]], :dependent => :destroy, :as => :locatable has_one :ideal_location, :conditions => ["type = ?", LOCATION_TYPES[:ideal_location]], :dependent => :destroy, :as => :locatable has_one :birthplace, :conditions => ["type = ?", LOCATION_TYPES[:birthplace]], :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end ``` With this code the following fails, basically making it useless: ``` user = User.first location = user.build_location location.city = "Cincinnati" location.state = "Ohio" location.save! location.type # => nil ``` This is obvious because there is no way to translate the :conditions options on the has\_one declaration into the type equaling 1. I could embed the id in the view anywhere these fields appear, but this seems wrong too: ``` <%= f.hidden_field :type, LOCATION_TYPES[:location] %> ``` Is there any way to avoid the extra subclasses or make the LOCATION\_TYPES approach work? In our particular case the application is very location aware and objects can have many different types of locations. Am I just being weird not wanting all those subclasses? Any suggestions you have are appreciated, tell me I'm crazy if you want, but would you want to see 10+ different location models floating around app/models?
2010/02/18
[ "https://Stackoverflow.com/questions/2285472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86820/" ]
As far as I can see it, a Location is a location is a Location. The different "subclasses" you're referring to (IdealLocation, Birthplace) seem to just be describing the location's relationship to a particular User. Stop me if I've got that part wrong. Knowing that, I can see two solutions to this. The first is to treat locations as value objects rather than entities. (For more on the terms: [Value vs Entity objects (Domain Driven Design)](https://stackoverflow.com/questions/75446/value-vs-entity-objects-domain-driven-design)). In the example above, you seem to be setting the location to "Cincinnati, OH", rather than finding a "Cincinnati, OH" object from the database. In that case, if many different users existed in Cincinnati, you'd have just as many identical "Cincinnati, OH" locations in your database, though there's only one Cincinnati, OH. To me, that's a clear sign that you're working with a value object, not an entity. How would this solution look? Likely using a simple Location object like this: ``` class Location attr_accessor :city, :state def initialize(options={}) @city = options[:city] @state = options[:state] end end class User < ActiveRecord::Base serialize :location serialize :ideal_location serialize :birthplace end @user.ideal_location = Location.new(:city => "Cincinnati", :state => "OH") @user.birthplace = Location.new(:city => "Detroit", :state => "MI") @user.save! @user.ideal_location.state # => "OH" ``` The other solution I can see is to use your existing Location ActiveRecord model, but simply use the relationship with User to define the relationship "type", like so: ``` class User < ActiveRecord::Base belongs_to :location, :dependent => :destroy belongs_to :ideal_location, :class_name => "Location", :dependent => :destroy belongs_to :birthplace, :class_name => "Location", :dependent => :destroy end class Location < ActiveRecord::Base end ``` All you'd need to do to make this work is include location\_id, ideal\_location\_id, and birthplace\_id attributes in your User model.
Maybe I'm missing something important here, but I thought you could name your relationships like this: ``` class User < ActiveRecord::Base has_one :location, :dependent => :destroy #ideal_location_id has_one :ideal_location, :class_name => "Location", :dependent => :destroy #birthplace_id has_one :birthplace, :class_name => "Location", :dependent => :destroy end class Location < ActiveRecord::Base belongs_to :user # user_id end ```
15,074,078
I am using GNU Make and would like it to add a prefix to each recipe command as it's echoed. For example, given this makefile: ``` foo: echo bar echo baz ``` Actual behavior: ``` $ make -B foo echo bar bar echo baz baz ``` Desired behavior: ``` $ make -B foo + echo bar bar + echo baz baz ``` (In this case, `+` is the prefix.) It would be nice if I could configure what the prefix is, but that's not essential.
2013/02/25
[ "https://Stackoverflow.com/questions/15074078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396038/" ]
The easiest way is to change the `SHELL` make variable. In this case, running the shell with the `-x` parameter should do the trick. Something like ``` $ make SHELL:='bash -x' ``` Or even ``` $ make .SHELLFLAGS:='-x -c' ``` in this case. For more sophisticated output a quick shell script fits the bill: ``` $ cat script #!/bin/bash echo "EXECUTING [$*]" $* ``` followed by ``` $ make SHELL:=./script .SHELLFLAGS:= ```
This isn't something Make does very naturally. I don't think you can do better than a horrible kludge: ``` define trick @echo + $(1) @$(1) endef foo: $(call trick, echo bar) $(call trick, echo baz) ```
41,612,974
I have a clock written with pure Javascript and CSS. Every time when new minute begins, my const which is responsible for rotating clocks hands is recalculated to first value (90deg). It causes problem because the clock's hand should rotate back to the first position from the end. I would like that my rotate value will not restart and always go on new minute\hour with current rotate value. [Check my demo](http://codepen.io/Zharkov/pen/dNMJZM) What I do? **CSS** ``` .clock { width: 20rem; height: 20rem; border: 1px solid rgba(0, 0, 0, .3); background: #ffafbd; /* Old browsers */ background: -moz-linear-gradient(top, #ffafbd 0%, #ffc3a0 100%); /* FF3.6-15 */ background: -webkit-linear-gradient(top, #ffafbd 0%, #ffc3a0 100%); /* Chrome10-25,Safari5.1-6 */ background: linear-gradient(to bottom, #ffafbd 0%, #ffc3a0 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#ffafbd', endColorstr='#ffc3a0', GradientType=0); /* IE6-9 */ border-radius: 50%; margin: 50px auto; position: relative; padding: 2rem; } .clock-face { position: relative; width: 100%; height: 100%; transform: translateY(-3px); /* account for the height of the clock hands */ } .hand { width: 50%; height: 2px; background: #4568dc; /* Old browsers */ background: -moz-linear-gradient(top, #4568dc 0%, #b06ab3 100%); /* FF3.6-15 */ background: -webkit-linear-gradient(top, #4568dc 0%, #b06ab3 100%); /* Chrome10-25,Safari5.1-6 */ background: linear-gradient(to bottom, #4568dc 0%, #b06ab3 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#4568dc', endColorstr='#b06ab3', GradientType=0); /* IE6-9 */ position: absolute; top: 50%; transform: rotate(90deg); transform-origin: 100%; transition: transform .2s cubic-bezier(0, 2.48, 0.72, 0.66); } .hour-hand { top: 45%; left: 32.5%; width: 35%; transform-origin: 75%; } ``` **JavaScript** ``` const secondHand = document.querySelector(".second-hand"); const minutesHand = document.querySelector(".min-hand"); const hourHand = document.querySelector(".hour-hand"); function getDate() { const now = new Date(); const seconds = now.getSeconds(); const secondsRotate = ((seconds / 60) * 360) + 90; secondHand.style.transform = `rotate(${secondsRotate}deg)`; const minutes = now.getMinutes(); const minutesRotate = ((minutes / 60) * 360) + 90; minutesHand.style.transform = `rotate(${minutesRotate}deg)`; const hours = now.getHours(); const hoursRotate = ((hours / 12) * 360) + 90; hourHand.style.transform = `rotate(${hoursRotate}deg)`; console.log(hours); } setInterval(getDate, 1000); ```
2017/01/12
[ "https://Stackoverflow.com/questions/41612974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6182081/" ]
Why do you want to use a list of dataframes? You can easily put all data in one dataframe: ``` library(dplyr) df = bind_rows(myList, .id="name") # new Variable threshold df %>% mutate(threshold = ifelse(pos.score >=18, "good", "bad")) ``` now you can filter and select your data within this dataframe (or even split it into a list of dataframes.)
Write `hotan.good.csv`, `hotan.bad.csv`, `aksu.good.csv`,... to existing `./out/` folder: ``` library(magrittr) l <- unlist(rslt, recursive = FALSE) l %>% names() %>% lapply(FUN = function(f) write.csv(l[[f]], paste0("out/", f, ".csv"), row.names = FALSE)) %>% invisible() ```
41,612,974
I have a clock written with pure Javascript and CSS. Every time when new minute begins, my const which is responsible for rotating clocks hands is recalculated to first value (90deg). It causes problem because the clock's hand should rotate back to the first position from the end. I would like that my rotate value will not restart and always go on new minute\hour with current rotate value. [Check my demo](http://codepen.io/Zharkov/pen/dNMJZM) What I do? **CSS** ``` .clock { width: 20rem; height: 20rem; border: 1px solid rgba(0, 0, 0, .3); background: #ffafbd; /* Old browsers */ background: -moz-linear-gradient(top, #ffafbd 0%, #ffc3a0 100%); /* FF3.6-15 */ background: -webkit-linear-gradient(top, #ffafbd 0%, #ffc3a0 100%); /* Chrome10-25,Safari5.1-6 */ background: linear-gradient(to bottom, #ffafbd 0%, #ffc3a0 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#ffafbd', endColorstr='#ffc3a0', GradientType=0); /* IE6-9 */ border-radius: 50%; margin: 50px auto; position: relative; padding: 2rem; } .clock-face { position: relative; width: 100%; height: 100%; transform: translateY(-3px); /* account for the height of the clock hands */ } .hand { width: 50%; height: 2px; background: #4568dc; /* Old browsers */ background: -moz-linear-gradient(top, #4568dc 0%, #b06ab3 100%); /* FF3.6-15 */ background: -webkit-linear-gradient(top, #4568dc 0%, #b06ab3 100%); /* Chrome10-25,Safari5.1-6 */ background: linear-gradient(to bottom, #4568dc 0%, #b06ab3 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#4568dc', endColorstr='#b06ab3', GradientType=0); /* IE6-9 */ position: absolute; top: 50%; transform: rotate(90deg); transform-origin: 100%; transition: transform .2s cubic-bezier(0, 2.48, 0.72, 0.66); } .hour-hand { top: 45%; left: 32.5%; width: 35%; transform-origin: 75%; } ``` **JavaScript** ``` const secondHand = document.querySelector(".second-hand"); const minutesHand = document.querySelector(".min-hand"); const hourHand = document.querySelector(".hour-hand"); function getDate() { const now = new Date(); const seconds = now.getSeconds(); const secondsRotate = ((seconds / 60) * 360) + 90; secondHand.style.transform = `rotate(${secondsRotate}deg)`; const minutes = now.getMinutes(); const minutesRotate = ((minutes / 60) * 360) + 90; minutesHand.style.transform = `rotate(${minutesRotate}deg)`; const hours = now.getHours(); const hoursRotate = ((hours / 12) * 360) + 90; hourHand.style.transform = `rotate(${hoursRotate}deg)`; console.log(hours); } setInterval(getDate, 1000); ```
2017/01/12
[ "https://Stackoverflow.com/questions/41612974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6182081/" ]
Why do you want to use a list of dataframes? You can easily put all data in one dataframe: ``` library(dplyr) df = bind_rows(myList, .id="name") # new Variable threshold df %>% mutate(threshold = ifelse(pos.score >=18, "good", "bad")) ``` now you can filter and select your data within this dataframe (or even split it into a list of dataframes.)
If I continue @MarkusN' solution (thanks for his help) : ``` library(dplyr) DF <- bind_rows(myList, .id="sample") %>% mutate(threshold = ifelse(pos.score >=18, "good", "bad")) %>% split(list(.$threshold,.$sample)) mapply(write.csv, DF, paste0(getwd(), names(DF), ".csv")) ``` In this way, exporting data.frame in the nested list can be much easier and efficient.
5,174,860
could please anybody provide a sample how to do this ? I'm not talking about form validation, but for instance when a user clicks a button in an auction system and it is too late - a fancy message pops up. Is there anything like this in YUI api, or some widget ?
2011/03/02
[ "https://Stackoverflow.com/questions/5174860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306488/" ]
Y.Overlay is the widget to use here. <http://developer.yahoo.com/yui/3/overlay/> ``` var overlay = new Y.Overlay({ width:"40em", visible:false, center: true, zIndex:10, headerContent: "Uh oh!" }).render("#somewhere"); ``` This will create the Overlay in the DOM, but it will be hidden. In response to an error, you would then do ``` overlay.set('bodyContent', "The error message"); overlay.show(); ``` Overlay does not come with a default skin, so you'll need to include css to style it like your app. Check out the user guide or just inspect the rendered Overlay in FireBug or Web Inspector to see the DOM and class structure for skinning.
Depending on how 'fancy' you really want to get, you could just use click handler with a simple alert box in your js like so: ``` YUI().use('node', function(Y) { Y.one('#clickme').on('click', function(e) { e.preventDefault(); alert('You Clicked!'); }); }); ``` With the following in your html: ``` <a id="clickme" href="#">Click Me</a> ``` --- **More Fancy:** Are you working with YUI2 or YUI3? YUI2 has some built-in overlays they call panels that act kind of like a window on your desktop. This, combined with the YUI sam skin lets you do something a little more 'fancy' without any more work if you're using YUI2: ``` <head> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/fonts/fonts-min.css" /> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/container/assets/skins/sam/container.css" /> <script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script> <script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/dragdrop/dragdrop-min.js"></script> <script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/container/container-min.js"></script> </head> <script type="text/javascript"> YAHOO.util.Event.addListener(window, 'load', function() { panel = new YAHOO.widget.Panel('mypanel', { width:"200px", visible:false, constraintoviewport:true } ); panel.render(); YAHOO.util.Event.addListener('clickme', 'click', panel.show, panel, true); }); </script> <body class="yui-skin-sam"> <a id="clickme" href="#">Click Me</a> <div id="mypanel"> <div class="hd">Nifty Panel</div> <div class="bd">Nifty Content.</div> <div class="ft">Nifty Footer#1</div> </div> </body> ``` Note the *class="yui-skim-sam"* in the body tag. This gives all the YUI elements a nice, pretty look and feel. More on YUI panels: <http://developer.yahoo.com/yui/container/panel/> More on YUI skins: <http://developer.yahoo.com/yui/articles/skinning/>
3,957,082
I have a class that takes many arguments to create. It’s a sort of an audio processor that needs a sample rate, sample resolution, number of channels etc. Most of the parameters have sane defaults. And most of them should be only settable in the initializer (constructor), because it makes no sense to change them afterwards. I do not want to create a gargantuan initializer with all the parameters because (1) it would be huge and essentially it would only copy the passed values, doing no real work, and (2) the user would have to specify values for all the parameters. What’s a good way to solve this? I’ve tried writing getters and setters for the params. This means that I could not create the “real” audio processing unit in the constructor, since the parameter values are not known then. I had to introduce a new method (say `prepareForWork`) so that the users can do something like: ``` AudioProcessor *box = [[AudioProcessor alloc] init]; [box setSampleRate:…]; [box setNumberOfChannels:…]; [box prepareForWork]; [box doSomeProcessing]; ``` This is nice because it does not require an unwieldy constructor. Also the defaults are set in the initializer which means that I can take a fresh `AudioProcessor` instance and it could still do some work. The flip side is that (1) there is an extra method that has to be called before the instance can do any real work and (2) the class should refuse to change any of the parameters after `prepareForWork` was called. Guarding both these invariants would take some boilerplate code that I don’t like. I thought I could create a special “preset” class that would look like this: ``` @interface SoundConfig : NSObject { NSUInteger numberOfChannels; NSUInteger sampleResolution; float sampleRate; } ``` And then require an instance of this class in the `AudioProcessor` initializer: ``` @interface AudioProcessor : NSObject {…} - (id) initWithConfig: (SoundConfig*) config; ``` Default values would be set in the `SoundConfig` initializer, the `AudioProcessor` constructor would be simple and there would be no invariants to keep watching by hand. Another approach I thought of was a kind of `AudioProcessorBuilder` class. You would create an instance of that, set the audio params through accessors and then finally it would build an `AudioProcessor` instance for you, setting all the properties through a non-public setters so that you could not change them later (and break the invariant). Now that I write this I favour the `SoundConfig` approach. How do you solve this, is there a better approach?
2010/10/18
[ "https://Stackoverflow.com/questions/3957082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17279/" ]
See how `NSURLConnection` is implemented and [used](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html). It uses an `NSURLRequest` object to parameterise it, similarly to the way your `SoundConfig` object parameterises the `AudioProcessor` object.
Usually, when you have class with many constructor parameters, especially when some or most of them are optional, you want to use [Builder Pattern](http://en.wikipedia.org/wiki/Builder_pattern). Funny thing, I cannot find examples for objective-c, so I am not sure if it could be easily applied here...
3,957,082
I have a class that takes many arguments to create. It’s a sort of an audio processor that needs a sample rate, sample resolution, number of channels etc. Most of the parameters have sane defaults. And most of them should be only settable in the initializer (constructor), because it makes no sense to change them afterwards. I do not want to create a gargantuan initializer with all the parameters because (1) it would be huge and essentially it would only copy the passed values, doing no real work, and (2) the user would have to specify values for all the parameters. What’s a good way to solve this? I’ve tried writing getters and setters for the params. This means that I could not create the “real” audio processing unit in the constructor, since the parameter values are not known then. I had to introduce a new method (say `prepareForWork`) so that the users can do something like: ``` AudioProcessor *box = [[AudioProcessor alloc] init]; [box setSampleRate:…]; [box setNumberOfChannels:…]; [box prepareForWork]; [box doSomeProcessing]; ``` This is nice because it does not require an unwieldy constructor. Also the defaults are set in the initializer which means that I can take a fresh `AudioProcessor` instance and it could still do some work. The flip side is that (1) there is an extra method that has to be called before the instance can do any real work and (2) the class should refuse to change any of the parameters after `prepareForWork` was called. Guarding both these invariants would take some boilerplate code that I don’t like. I thought I could create a special “preset” class that would look like this: ``` @interface SoundConfig : NSObject { NSUInteger numberOfChannels; NSUInteger sampleResolution; float sampleRate; } ``` And then require an instance of this class in the `AudioProcessor` initializer: ``` @interface AudioProcessor : NSObject {…} - (id) initWithConfig: (SoundConfig*) config; ``` Default values would be set in the `SoundConfig` initializer, the `AudioProcessor` constructor would be simple and there would be no invariants to keep watching by hand. Another approach I thought of was a kind of `AudioProcessorBuilder` class. You would create an instance of that, set the audio params through accessors and then finally it would build an `AudioProcessor` instance for you, setting all the properties through a non-public setters so that you could not change them later (and break the invariant). Now that I write this I favour the `SoundConfig` approach. How do you solve this, is there a better approach?
2010/10/18
[ "https://Stackoverflow.com/questions/3957082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17279/" ]
See how `NSURLConnection` is implemented and [used](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html). It uses an `NSURLRequest` object to parameterise it, similarly to the way your `SoundConfig` object parameterises the `AudioProcessor` object.
The usual way is indeed to create a gargantuan initializer together with several initializers for non default values or sets of values. ``` -initWithSampleRate:numberOfChannels:sampleResolution: -initWithSampleRate:sampleResolution: -initWithSampleRate:numberOfChannels: -initWithNumberOfChannels:sampleResolution: -initWithNumberOfChannels: -initWithSampleResolution: -initWithSampleRate: -init ``` But the `SoundConfig` approach looks simpler.
3,957,082
I have a class that takes many arguments to create. It’s a sort of an audio processor that needs a sample rate, sample resolution, number of channels etc. Most of the parameters have sane defaults. And most of them should be only settable in the initializer (constructor), because it makes no sense to change them afterwards. I do not want to create a gargantuan initializer with all the parameters because (1) it would be huge and essentially it would only copy the passed values, doing no real work, and (2) the user would have to specify values for all the parameters. What’s a good way to solve this? I’ve tried writing getters and setters for the params. This means that I could not create the “real” audio processing unit in the constructor, since the parameter values are not known then. I had to introduce a new method (say `prepareForWork`) so that the users can do something like: ``` AudioProcessor *box = [[AudioProcessor alloc] init]; [box setSampleRate:…]; [box setNumberOfChannels:…]; [box prepareForWork]; [box doSomeProcessing]; ``` This is nice because it does not require an unwieldy constructor. Also the defaults are set in the initializer which means that I can take a fresh `AudioProcessor` instance and it could still do some work. The flip side is that (1) there is an extra method that has to be called before the instance can do any real work and (2) the class should refuse to change any of the parameters after `prepareForWork` was called. Guarding both these invariants would take some boilerplate code that I don’t like. I thought I could create a special “preset” class that would look like this: ``` @interface SoundConfig : NSObject { NSUInteger numberOfChannels; NSUInteger sampleResolution; float sampleRate; } ``` And then require an instance of this class in the `AudioProcessor` initializer: ``` @interface AudioProcessor : NSObject {…} - (id) initWithConfig: (SoundConfig*) config; ``` Default values would be set in the `SoundConfig` initializer, the `AudioProcessor` constructor would be simple and there would be no invariants to keep watching by hand. Another approach I thought of was a kind of `AudioProcessorBuilder` class. You would create an instance of that, set the audio params through accessors and then finally it would build an `AudioProcessor` instance for you, setting all the properties through a non-public setters so that you could not change them later (and break the invariant). Now that I write this I favour the `SoundConfig` approach. How do you solve this, is there a better approach?
2010/10/18
[ "https://Stackoverflow.com/questions/3957082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17279/" ]
The usual way is indeed to create a gargantuan initializer together with several initializers for non default values or sets of values. ``` -initWithSampleRate:numberOfChannels:sampleResolution: -initWithSampleRate:sampleResolution: -initWithSampleRate:numberOfChannels: -initWithNumberOfChannels:sampleResolution: -initWithNumberOfChannels: -initWithSampleResolution: -initWithSampleRate: -init ``` But the `SoundConfig` approach looks simpler.
Usually, when you have class with many constructor parameters, especially when some or most of them are optional, you want to use [Builder Pattern](http://en.wikipedia.org/wiki/Builder_pattern). Funny thing, I cannot find examples for objective-c, so I am not sure if it could be easily applied here...
7,288,222
I want to inject a DLL into a process. Once this DLL is in there, it should catch & properly handle **all** access violation exceptions which occur in the process. Is there any way to accomplish this?
2011/09/02
[ "https://Stackoverflow.com/questions/7288222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How about SetUnhandledExceptionFilter( **function** )? **function**'s prototype is: ``` LONG __stdcall ExceptionHandler(EXCEPTION_POINTERS *ExceptionInfo); ``` I've used this function to create crash dumps, etc.
You can use Structured Exception Handling (SEH) to catch such exceptions. Specifically, [this](http://msdn.microsoft.com/en-us/library/ms679274%28v=VS.85%29.aspx) Windows function seems to be what you want to do.
7,288,222
I want to inject a DLL into a process. Once this DLL is in there, it should catch & properly handle **all** access violation exceptions which occur in the process. Is there any way to accomplish this?
2011/09/02
[ "https://Stackoverflow.com/questions/7288222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use Structured Exception Handling (SEH) to catch such exceptions. Specifically, [this](http://msdn.microsoft.com/en-us/library/ms679274%28v=VS.85%29.aspx) Windows function seems to be what you want to do.
To complete the collection, you can also use [AddVectoredExceptionHandler](http://msdn.microsoft.com/en-us/library/ms679274%28v=vs.85%29.aspx).
7,288,222
I want to inject a DLL into a process. Once this DLL is in there, it should catch & properly handle **all** access violation exceptions which occur in the process. Is there any way to accomplish this?
2011/09/02
[ "https://Stackoverflow.com/questions/7288222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use Structured Exception Handling (SEH) to catch such exceptions. Specifically, [this](http://msdn.microsoft.com/en-us/library/ms679274%28v=VS.85%29.aspx) Windows function seems to be what you want to do.
Pre XP, you cannot catch all exceptions. XP or later, you should use [`AddVectoredExceptionHandler(1, handler)`](http://msdn.microsoft.com/en-us/library/ms679274%28v=vs.85%29.aspx), although you are not guaranteed that you will always be the first vectored exception handler.
7,288,222
I want to inject a DLL into a process. Once this DLL is in there, it should catch & properly handle **all** access violation exceptions which occur in the process. Is there any way to accomplish this?
2011/09/02
[ "https://Stackoverflow.com/questions/7288222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How about SetUnhandledExceptionFilter( **function** )? **function**'s prototype is: ``` LONG __stdcall ExceptionHandler(EXCEPTION_POINTERS *ExceptionInfo); ``` I've used this function to create crash dumps, etc.
To complete the collection, you can also use [AddVectoredExceptionHandler](http://msdn.microsoft.com/en-us/library/ms679274%28v=vs.85%29.aspx).
7,288,222
I want to inject a DLL into a process. Once this DLL is in there, it should catch & properly handle **all** access violation exceptions which occur in the process. Is there any way to accomplish this?
2011/09/02
[ "https://Stackoverflow.com/questions/7288222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How about SetUnhandledExceptionFilter( **function** )? **function**'s prototype is: ``` LONG __stdcall ExceptionHandler(EXCEPTION_POINTERS *ExceptionInfo); ``` I've used this function to create crash dumps, etc.
Pre XP, you cannot catch all exceptions. XP or later, you should use [`AddVectoredExceptionHandler(1, handler)`](http://msdn.microsoft.com/en-us/library/ms679274%28v=vs.85%29.aspx), although you are not guaranteed that you will always be the first vectored exception handler.
961,256
How would I increase the child index of a movie clip by 1?
2009/06/07
[ "https://Stackoverflow.com/questions/961256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115182/" ]
Do you mean move it one level higher in its parent's stacking order? Then you do it by swapping it with the clip above it. Like this: ``` var index:int = myMC.parent.getChildIndex( myMC ); myMC.parent.swapChildrenAt( index, index+1 ); ``` If that's not what you want to do, maybe you could expand on what you mean by child index?
fenomas is correct. It is also important to note that in AS3 there are no gaps in the child display lists so in order to move it higher in the stacking order there must be other children in the display list to swap with. A good resource is here -> <http://livedocs.adobe.com/flex/3/html/help.html?content=05_Display_Programming_04.html>
66,706,905
I have a shell script below. This already works by doing sh start\_script.sh But I want this to work automatically using cron jobs. Already made it executable using **chmod +x** Below is shell script and the cron job: ``` 2 * * * * /home/glenn/projects/database_dump/backup/script_backupMongoDB.sh ``` ``` #!/bin/sh TIMESTAMP=`date +%F-%H%M%S` FILENAME=configurator_`date +%m%d%y%H`_$TIMESTAMP.tar.gz DEST=/home/glenn/projects/database_dump/backup SERVER=127.0.0.1:27017 DBNAME=siaphaji-cms DUMPFOLDER=$DEST/$DBNAME DAYSTORETAINBACKUP="7" # DUMP TO DEST FOLDER mongodump -h $SERVER -d $DBNAME --out $DEST; # COMPRESS THE DUMPFOLDER AND NAME IT FILENAME tar -zcvf $FILENAME $DUMPFOLDER # DELETE DUMP FOLDER rm -rf $DUMPFOLDER find $DEST -type f -name '*.tar.gz' -mtime +$DAYSTORETAINBACKUP -exec rm {} + ```
2021/03/19
[ "https://Stackoverflow.com/questions/66706905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9352676/" ]
The solution was to use the `api.selfasserted.profileupdate` content definition (instead of `api.localaccountpasswordreset`) for the `LocalAccountDiscoveryUsingEmailAddress` technical profile. ```xml <TechnicalProfile Id="LocalAccountDiscoveryUsingEmailAddress"> <DisplayName>Reset password using email address</DisplayName> <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> <Metadata> <Item Key="IpAddressClaimReferenceId">IpAddress</Item> <Item Key="ContentDefinitionReferenceId">api.selfasserted.profileupdate</Item> <Item Key="UserMessageIfClaimsTransformationBooleanValueIsNotEqual">Your account has been locked. Contact your support person to unlock it, then try again.</Item> <Item Key="EnforceEmailVerification">false</Item> </Metadata> <CryptographicKeys> <Key Id="issuer_secret" StorageReferenceId="B2C_1A_TokenSigningKeyContainer" /> </CryptographicKeys> <IncludeInSso>false</IncludeInSso> <OutputClaims> <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="Verified.Email" Required="true" /> <OutputClaim ClaimTypeReferenceId="verificationCode" Required="true" /> <OutputClaim ClaimTypeReferenceId="objectId" /> <OutputClaim ClaimTypeReferenceId="userPrincipalName" /> <OutputClaim ClaimTypeReferenceId="authenticationSource" /> </OutputClaims> <ValidationTechnicalProfiles> <ValidationTechnicalProfile ReferenceId="REST-EmailVerification" /> <ValidationTechnicalProfile ReferenceId="AAD-UserReadUsingEmailAddress" /> </ValidationTechnicalProfiles> </TechnicalProfile> ``` It looks mostly as a workaround, but it's the only option not to use the preview features of the display controls. To further protect the validation, there is an API-side check in the REST-EmailVerification validation technical profile, that re-checks the code previously validated client-side: ```xml <ValidationTechnicalProfiles> <ValidationTechnicalProfile ReferenceId="REST-EmailVerification" /> <ValidationTechnicalProfile ReferenceId="AAD-UserReadUsingEmailAddress" /> </ValidationTechnicalProfiles> ``` Additionally I'm currently adding a captcha to avoid abuses of the sending logics. As soon as the display controls will be generally available, I'll reccomend my client to use them. The reason why it didn't work with the password-reset-specific content definition, is that it doesn't support other custom fields: <https://learn.microsoft.com/it-it/azure/active-directory-b2c/contentdefinitions> [![enter image description here](https://i.stack.imgur.com/5fN2W.png)](https://i.stack.imgur.com/5fN2W.png)
Swap `verified.email` output claim with the reference to your displayControl in the technical profile for password reset, which is `LocalAccountDiscoveryUsingEmailAddress`. <https://learn.microsoft.com/en-us/azure/active-directory-b2c/custom-email-sendgrid#make-a-reference-to-the-displaycontrol> Its essentially the exact same steps, except you make the "make a reference" change to the `LocalAccountDiscoveryUsingEmailAddress` technical profile to show the display control on this specific page, which is referenced in Step 1 of the password reset journey to collect and verify the users email. ```xml <TechnicalProfile Id="LocalAccountDiscoveryUsingEmailAddress"> <DisplayName>Reset password using email address</DisplayName> <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> <Metadata> <Item Key="IpAddressClaimReferenceId">IpAddress</Item> <Item Key="ContentDefinitionReferenceId">api.localaccountpasswordreset</Item> <Item Key="UserMessageIfClaimsTransformationBooleanValueIsNotEqual">Your account has been locked. Contact your support person to unlock it, then try again.</Item> </Metadata> <CryptographicKeys> <Key Id="issuer_secret" StorageReferenceId="B2C_1A_TokenSigningKeyContainer" /> </CryptographicKeys> <IncludeInSso>false</IncludeInSso> <DisplayClaims> <DisplayClaim DisplayControlReferenceId="emailVerificationControl" /> </DisplayClaims> <OutputClaims> <!--<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="Verified.Email" Required="true" />--> <OutputClaim ClaimTypeReferenceId="email" /> <OutputClaim ClaimTypeReferenceId="objectId" /> <OutputClaim ClaimTypeReferenceId="userPrincipalName" /> <OutputClaim ClaimTypeReferenceId="authenticationSource" /> ``` And if you want a different email template for password reset compared to Sign Up, recreate a new displayControl and reference a different template.
36,166,205
I want to have a single line of code with an `if` and the result on the same line. Example ``` if(_count > 0) return; ``` If I add a breakpoint on the line, it is set on the `if(_count > 0)`: [![Breakpoint on the if statement](https://i.stack.imgur.com/aNRcf.jpg)](https://i.stack.imgur.com/aNRcf.jpg) but what I want is to have the breakpoint on the `return;` like so: [![Breakpoint on return](https://i.stack.imgur.com/dBv9E.jpg)](https://i.stack.imgur.com/dBv9E.jpg) Is this doable? NOTE: The closest question I could find on SO was [this](https://stackoverflow.com/q/15942830/1467396) (which is not the same thing).
2016/03/22
[ "https://Stackoverflow.com/questions/36166205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467396/" ]
Just click on a part of the line and press F9. This will set breakpoint in the middle of the line.
*EDIT* mareko posted a 3rd option that seems to work just fine and is much easier than messing around with all this line-and-character stuff. I'm going to leave this answer for completeness, but mareko's is much more practical in general. --- Yes, but unfortunately, there is no drag-and-drop or anything like that. You have 2 options: **OPTION 1** Move your return to a new line: [![enter image description here](https://i.stack.imgur.com/ShCr7.jpg)](https://i.stack.imgur.com/ShCr7.jpg) obviously, you can leave it like that, but if you want to keep the `return` on the same line as the `if`, you can simply delete the new line and the whitespace between the `if` and the `return` -- the breakpoint should "stick" to the `return` as you move it around. This is probably the easier way to do it unless you are currently debugging code that does not have edit-and-continue for whatever reason. In that case, you'll need option 2... --- **OPTION 2** Alternately, you can place the cursor just before the r in 'return' and then look in your status bar to see which character ("Ch") you are on. In my case, I'm on 20 [![enter image description here](https://i.stack.imgur.com/I1t0M.jpg)](https://i.stack.imgur.com/I1t0M.jpg) now right click on the breakpoint and choose "Location..." [![enter image description here](https://i.stack.imgur.com/6cpSX.png)](https://i.stack.imgur.com/6cpSX.png) In the dialog box that pops up, set `Character:` to whatever the status bar was (20 in our example). [![enter image description here](https://i.stack.imgur.com/Z2R6x.jpg)](https://i.stack.imgur.com/Z2R6x.jpg)
65,522,968
how do you make this box fade out on a click in javascript? . Button 3 is where I am having a bit of difficulty. I'm a neophyte to coding please be patient. ```js document.getElementById("button1").addEventListener("click", function(){ document.getElementById("box").style.height = "250px"; }); document.getElementById("button2").addEventListener("click", function(){ document.getElementById("box").style.backgroundColor = "blue"; }); document.getElementById("button3").addEventListener("click", function(){ document.getElementById("box").style.opacity = "0" }); document.getElementById("button4").addEventListener("click", function(){ document.getElementById("box").style.height = "150px"; }); ``` ```html <p>Press the buttons to change the box!</p> <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"></div> <button id="button1">Grow</button> <button id="button2">Blue</button> <button id="button3">Fade</button> <button id="button4">Reset</button> ```
2020/12/31
[ "https://Stackoverflow.com/questions/65522968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14851946/" ]
The code you've provided won't make anything "fade", it will cause the `height` to immediately change. If you want the height to decrease to nothing, causing an effect over time, you can use [CSS transitions](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) like this: ```js // Just get your references once. const box = document.getElementById("box"); document.getElementById("button1").addEventListener("click", function(){ box.classList.add("bigBox"); // Just add/remove the desired class }); document.getElementById("button2").addEventListener("click", function(){ box.classList.add("blue"); }); document.getElementById("button3").addEventListener("click", function(){ box.classList.add("transparent"); box.classList.add("noSize"); }); document.getElementById("button4").addEventListener("click", function(){ // When you remove a class, the prior settings that were // overridden by the class are reinstated. box.classList.remove("bigBox"); box.classList.remove("transparent"); box.classList.remove("blue"); box.classList.remove("noSize"); }); ``` ```css #box { /* You must declare that you want transitions to apply to the element and then you must set initial property values for the properties you'll want the transition to apply to. If you only want certain properties to transition name them on the next line instead of "all" */ transition: all 3s ease; height:150px; width:150px; background-color:orange; margin:25px; opacity:1; } /* These will be added (thus triggering the transition) and removed through JavaScript. It's better to use classes than to use inline styles in HTML. */ #box.transparent { opacity:0; } #box.bigBox { height:250px; } #box.blue { background-color:blue; } #box.noSize { height:0; width:0; } ``` ```html <div id="box"></div> <button id="button1">Grow</button> <button id="button2">Blue</button> <button id="button3">Fade</button> <button id="button4">Reset</button> ```
You could use jQuery in your script <https://api.jquery.com/fadeOut/> with their fadeout method. You could use something like ```js document.getElementById("button3").addEventListener("click", function(){ $("#box").fadeOut(); // You can optionally add a duration parameter which defaults at 400 ms } ```
65,522,968
how do you make this box fade out on a click in javascript? . Button 3 is where I am having a bit of difficulty. I'm a neophyte to coding please be patient. ```js document.getElementById("button1").addEventListener("click", function(){ document.getElementById("box").style.height = "250px"; }); document.getElementById("button2").addEventListener("click", function(){ document.getElementById("box").style.backgroundColor = "blue"; }); document.getElementById("button3").addEventListener("click", function(){ document.getElementById("box").style.opacity = "0" }); document.getElementById("button4").addEventListener("click", function(){ document.getElementById("box").style.height = "150px"; }); ``` ```html <p>Press the buttons to change the box!</p> <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"></div> <button id="button1">Grow</button> <button id="button2">Blue</button> <button id="button3">Fade</button> <button id="button4">Reset</button> ```
2020/12/31
[ "https://Stackoverflow.com/questions/65522968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14851946/" ]
You could just add the [transition](https://developer.mozilla.org/en-US/docs/Web/CSS/transition) property to your box element: ``` transition: opacity 1s ease-out; ``` You code also has some syntax errors. You can see a working snippet below: ```html <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; transition: opacity 1s ease-out;"></div> <button id="button1">Grow</button> <button id="button2">Blue</button> <button id="button3">Fade</button> <button id="button4">Reset</button> <script type="text/javascript"> document.getElementById("button1").addEventListener("click", function(){ document.getElementById("box").style.height = "250px"; }); document.getElementById("button2").addEventListener("click", function(){ document.getElementById("box").style.backgroundColor = "blue"; }); document.getElementById("button3").addEventListener("click", function(){ document.getElementById("box").style.opacity = "0" }); document.getElementById("button4").addEventListener("click", function(){ document.getElementById("box").style.height = "150px"; }); </script> ``` **Note:** If your project gets bigger, I would recommend to have an external css file for your styles.
You could use jQuery in your script <https://api.jquery.com/fadeOut/> with their fadeout method. You could use something like ```js document.getElementById("button3").addEventListener("click", function(){ $("#box").fadeOut(); // You can optionally add a duration parameter which defaults at 400 ms } ```
65,522,968
how do you make this box fade out on a click in javascript? . Button 3 is where I am having a bit of difficulty. I'm a neophyte to coding please be patient. ```js document.getElementById("button1").addEventListener("click", function(){ document.getElementById("box").style.height = "250px"; }); document.getElementById("button2").addEventListener("click", function(){ document.getElementById("box").style.backgroundColor = "blue"; }); document.getElementById("button3").addEventListener("click", function(){ document.getElementById("box").style.opacity = "0" }); document.getElementById("button4").addEventListener("click", function(){ document.getElementById("box").style.height = "150px"; }); ``` ```html <p>Press the buttons to change the box!</p> <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"></div> <button id="button1">Grow</button> <button id="button2">Blue</button> <button id="button3">Fade</button> <button id="button4">Reset</button> ```
2020/12/31
[ "https://Stackoverflow.com/questions/65522968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14851946/" ]
You could just add the [transition](https://developer.mozilla.org/en-US/docs/Web/CSS/transition) property to your box element: ``` transition: opacity 1s ease-out; ``` You code also has some syntax errors. You can see a working snippet below: ```html <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; transition: opacity 1s ease-out;"></div> <button id="button1">Grow</button> <button id="button2">Blue</button> <button id="button3">Fade</button> <button id="button4">Reset</button> <script type="text/javascript"> document.getElementById("button1").addEventListener("click", function(){ document.getElementById("box").style.height = "250px"; }); document.getElementById("button2").addEventListener("click", function(){ document.getElementById("box").style.backgroundColor = "blue"; }); document.getElementById("button3").addEventListener("click", function(){ document.getElementById("box").style.opacity = "0" }); document.getElementById("button4").addEventListener("click", function(){ document.getElementById("box").style.height = "150px"; }); </script> ``` **Note:** If your project gets bigger, I would recommend to have an external css file for your styles.
The code you've provided won't make anything "fade", it will cause the `height` to immediately change. If you want the height to decrease to nothing, causing an effect over time, you can use [CSS transitions](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) like this: ```js // Just get your references once. const box = document.getElementById("box"); document.getElementById("button1").addEventListener("click", function(){ box.classList.add("bigBox"); // Just add/remove the desired class }); document.getElementById("button2").addEventListener("click", function(){ box.classList.add("blue"); }); document.getElementById("button3").addEventListener("click", function(){ box.classList.add("transparent"); box.classList.add("noSize"); }); document.getElementById("button4").addEventListener("click", function(){ // When you remove a class, the prior settings that were // overridden by the class are reinstated. box.classList.remove("bigBox"); box.classList.remove("transparent"); box.classList.remove("blue"); box.classList.remove("noSize"); }); ``` ```css #box { /* You must declare that you want transitions to apply to the element and then you must set initial property values for the properties you'll want the transition to apply to. If you only want certain properties to transition name them on the next line instead of "all" */ transition: all 3s ease; height:150px; width:150px; background-color:orange; margin:25px; opacity:1; } /* These will be added (thus triggering the transition) and removed through JavaScript. It's better to use classes than to use inline styles in HTML. */ #box.transparent { opacity:0; } #box.bigBox { height:250px; } #box.blue { background-color:blue; } #box.noSize { height:0; width:0; } ``` ```html <div id="box"></div> <button id="button1">Grow</button> <button id="button2">Blue</button> <button id="button3">Fade</button> <button id="button4">Reset</button> ```
1,134,370
In my application, I want the user to be able to select a directory to store stuff in. I have a text field that I'm using to display the directory they've chosen. If they just click on a directory (don't browse it), everything is fine. However, if they double click on the directory and look inside it, the directory name is duplicated. Ex. They're in the home directory, single click the folder Desktop...path returned is ~/Desktop. On the other hand, if they're in the home directory, double click the folder Desktop, and now are in the Desktop folder, path returned is ~/Desktop/Destkop. Here's what I'm doing: ``` JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); loadField.setText(f.getPath()); } ``` I've also tried to do something like `chooser.getCurrentDirectory()` but that doesn't really work either. Edit: Using Mac OS X, Java 1.6
2009/07/15
[ "https://Stackoverflow.com/questions/1134370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122358/" ]
Seems to work for me. ``` import javax.swing.JFileChooser; public class FChoose { public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { java.io.File f = chooser.getSelectedFile(); System.err.println(f.getPath()); } }}); } } ``` 6u13 on Vista. Is there something strange about your setup or what you are doing? If there's a specific bug in a Mac OS X implementation of Java, you may want to, say, check if the file exists and if not de-dupe the last to elements of the path.
The problem occurs when you use chooser.showDialog or chooser.showSaveDialog instead of chooser.showOpenDialog. On XP chooser.showDialog returns the correct path under the example given by the OP, but on Mac OS 10.5.7 (and probably earlier versions as well) you'll get ~/Desktop/Desktop . (In my case I need to use showSaveDialog because I want users to have the option to create a new folder, so it looks like I'll have to de-dupe the path manually. It sure looks like this is a bug in the Apple Java implementation.)
1,041,457
We have a new project for a web app that will display banners ads on websites (as a network) and our estimate is for it to handle 20 to 40 billion impressions a month. Our current language is in ASP...but are moving to PHP. Does PHP 5 has its limit with scaling web application? Or, should I have our team invest in picking up JSP? Or, is it a matter of the app server and/or DB? We plan to use Oracle 10g as the database.
2009/06/24
[ "https://Stackoverflow.com/questions/1041457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51281/" ]
You do realize that 40 billion per month is roughly 15,500 *per second*, right? Scaling isn't going to be your problem - infrastructure *period* is going to be your problem. No matter what technology stack you choose, you are going to need an enormous amount of hardware - as others have said in the form of a farm or cloud.
I think that it is not matter of language, but it can be be a matter of database speed as CPU processing speed. Have you considered a web farm? In this way you can have more than one machine serving your application. There are some ways to implement this solution. You can start with two server and add more server as the app request more processing volume. In other point, Oracle 10g is a very good database server, in my humble opinion you only need a stand alone Oracle server to commit the volume of request. Remember that a SQL server is faster as the people request more or less the same things each time and it happens in web application if you plan your database schema carefully. You also have to check all the Ad Server application solutions and there are a very good ones, just try Google with "Open Source AD servers".
1,041,457
We have a new project for a web app that will display banners ads on websites (as a network) and our estimate is for it to handle 20 to 40 billion impressions a month. Our current language is in ASP...but are moving to PHP. Does PHP 5 has its limit with scaling web application? Or, should I have our team invest in picking up JSP? Or, is it a matter of the app server and/or DB? We plan to use Oracle 10g as the database.
2009/06/24
[ "https://Stackoverflow.com/questions/1041457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51281/" ]
This question (and the entire subject) is a bit subjective. You can write a dog slow program in any language, and host it on anything. I think your best bet is to see how your current implementation works under load. Maybe just a few tweaks will make things work for you - but changing your underlying framework seems a bit much. That being said - your infrastructure team will also have to be involved as it seems you have some serious load requirements. Good luck!
I think that it is not matter of language, but it can be be a matter of database speed as CPU processing speed. Have you considered a web farm? In this way you can have more than one machine serving your application. There are some ways to implement this solution. You can start with two server and add more server as the app request more processing volume. In other point, Oracle 10g is a very good database server, in my humble opinion you only need a stand alone Oracle server to commit the volume of request. Remember that a SQL server is faster as the people request more or less the same things each time and it happens in web application if you plan your database schema carefully. You also have to check all the Ad Server application solutions and there are a very good ones, just try Google with "Open Source AD servers".
1,041,457
We have a new project for a web app that will display banners ads on websites (as a network) and our estimate is for it to handle 20 to 40 billion impressions a month. Our current language is in ASP...but are moving to PHP. Does PHP 5 has its limit with scaling web application? Or, should I have our team invest in picking up JSP? Or, is it a matter of the app server and/or DB? We plan to use Oracle 10g as the database.
2009/06/24
[ "https://Stackoverflow.com/questions/1041457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51281/" ]
No offense, but I strongly suspect you're **vastly overestimating** how many impressions you'll serve. That said: PHP or other languages used in the application tier really have little to do with scalability. Since the application tier delegates it's state to the database or equivalent, it's straightforward to add as much capacity as you need behind appropriate load balancing. Choice of language does influence per server efficiency and hence costs, but that's different than scalability. It's scaling the state/data storage that gets more complicated. For your app, you have three basic jobs: 1. what ad do we show? 2. serving the add 3. logging the impression Each of these will require thought and likely different tools. The second, serving the add, is most simple: use a [CDN](http://en.wikipedia.org/wiki/Content_delivery_network). If you actually serve the volume you claim, you should be able to negotiate favorable rates. Deciding which ad to show is going to be very specific to your network. It may be as simple as reading a few rows from a database that give ad placements for a given property for a given calendar period. Or it may be complex contextual advertising like google. Assuming it's more the former, and that the database of placements is small, then this is the simple task of scaling database reads. You can use replication trees or alternately a caching layer like [memcached](http://www.danga.com/memcached/). The last will ultimately be the most difficult: how to scale the writes. A common approach would be to still use databases, but to adopt a sharding scaling strategy. More exotic options might be to use a key/value store supporting counter instructions, such as [Redis](http://code.google.com/p/redis/), or a scalable OLAP database such as [Vertica](http://www.vertica.com/). All of the above assumes that you're able to secure data center space and network provisioning capable of serving this load, which is not trivial at the numbers you're talking.
I think that it is not matter of language, but it can be be a matter of database speed as CPU processing speed. Have you considered a web farm? In this way you can have more than one machine serving your application. There are some ways to implement this solution. You can start with two server and add more server as the app request more processing volume. In other point, Oracle 10g is a very good database server, in my humble opinion you only need a stand alone Oracle server to commit the volume of request. Remember that a SQL server is faster as the people request more or less the same things each time and it happens in web application if you plan your database schema carefully. You also have to check all the Ad Server application solutions and there are a very good ones, just try Google with "Open Source AD servers".
1,041,457
We have a new project for a web app that will display banners ads on websites (as a network) and our estimate is for it to handle 20 to 40 billion impressions a month. Our current language is in ASP...but are moving to PHP. Does PHP 5 has its limit with scaling web application? Or, should I have our team invest in picking up JSP? Or, is it a matter of the app server and/or DB? We plan to use Oracle 10g as the database.
2009/06/24
[ "https://Stackoverflow.com/questions/1041457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51281/" ]
You do realize that 40 billion per month is roughly 15,500 *per second*, right? Scaling isn't going to be your problem - infrastructure *period* is going to be your problem. No matter what technology stack you choose, you are going to need an enormous amount of hardware - as others have said in the form of a farm or cloud.
This question (and the entire subject) is a bit subjective. You can write a dog slow program in any language, and host it on anything. I think your best bet is to see how your current implementation works under load. Maybe just a few tweaks will make things work for you - but changing your underlying framework seems a bit much. That being said - your infrastructure team will also have to be involved as it seems you have some serious load requirements. Good luck!
1,041,457
We have a new project for a web app that will display banners ads on websites (as a network) and our estimate is for it to handle 20 to 40 billion impressions a month. Our current language is in ASP...but are moving to PHP. Does PHP 5 has its limit with scaling web application? Or, should I have our team invest in picking up JSP? Or, is it a matter of the app server and/or DB? We plan to use Oracle 10g as the database.
2009/06/24
[ "https://Stackoverflow.com/questions/1041457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51281/" ]
You do realize that 40 billion per month is roughly 15,500 *per second*, right? Scaling isn't going to be your problem - infrastructure *period* is going to be your problem. No matter what technology stack you choose, you are going to need an enormous amount of hardware - as others have said in the form of a farm or cloud.
PHP will be capable of serving your needs. However, as others have said, your first limits will be your network infrastructure. But your second limits will be writing scalable code. You will need good abstraction and isolation so that resources can easily be added at any level. Things like a fast data-object mapper, multiple data caching mechanisms, separate configuration files, and so on.
1,041,457
We have a new project for a web app that will display banners ads on websites (as a network) and our estimate is for it to handle 20 to 40 billion impressions a month. Our current language is in ASP...but are moving to PHP. Does PHP 5 has its limit with scaling web application? Or, should I have our team invest in picking up JSP? Or, is it a matter of the app server and/or DB? We plan to use Oracle 10g as the database.
2009/06/24
[ "https://Stackoverflow.com/questions/1041457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51281/" ]
This question (and the entire subject) is a bit subjective. You can write a dog slow program in any language, and host it on anything. I think your best bet is to see how your current implementation works under load. Maybe just a few tweaks will make things work for you - but changing your underlying framework seems a bit much. That being said - your infrastructure team will also have to be involved as it seems you have some serious load requirements. Good luck!
PHP will be capable of serving your needs. However, as others have said, your first limits will be your network infrastructure. But your second limits will be writing scalable code. You will need good abstraction and isolation so that resources can easily be added at any level. Things like a fast data-object mapper, multiple data caching mechanisms, separate configuration files, and so on.
1,041,457
We have a new project for a web app that will display banners ads on websites (as a network) and our estimate is for it to handle 20 to 40 billion impressions a month. Our current language is in ASP...but are moving to PHP. Does PHP 5 has its limit with scaling web application? Or, should I have our team invest in picking up JSP? Or, is it a matter of the app server and/or DB? We plan to use Oracle 10g as the database.
2009/06/24
[ "https://Stackoverflow.com/questions/1041457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51281/" ]
No offense, but I strongly suspect you're **vastly overestimating** how many impressions you'll serve. That said: PHP or other languages used in the application tier really have little to do with scalability. Since the application tier delegates it's state to the database or equivalent, it's straightforward to add as much capacity as you need behind appropriate load balancing. Choice of language does influence per server efficiency and hence costs, but that's different than scalability. It's scaling the state/data storage that gets more complicated. For your app, you have three basic jobs: 1. what ad do we show? 2. serving the add 3. logging the impression Each of these will require thought and likely different tools. The second, serving the add, is most simple: use a [CDN](http://en.wikipedia.org/wiki/Content_delivery_network). If you actually serve the volume you claim, you should be able to negotiate favorable rates. Deciding which ad to show is going to be very specific to your network. It may be as simple as reading a few rows from a database that give ad placements for a given property for a given calendar period. Or it may be complex contextual advertising like google. Assuming it's more the former, and that the database of placements is small, then this is the simple task of scaling database reads. You can use replication trees or alternately a caching layer like [memcached](http://www.danga.com/memcached/). The last will ultimately be the most difficult: how to scale the writes. A common approach would be to still use databases, but to adopt a sharding scaling strategy. More exotic options might be to use a key/value store supporting counter instructions, such as [Redis](http://code.google.com/p/redis/), or a scalable OLAP database such as [Vertica](http://www.vertica.com/). All of the above assumes that you're able to secure data center space and network provisioning capable of serving this load, which is not trivial at the numbers you're talking.
This question (and the entire subject) is a bit subjective. You can write a dog slow program in any language, and host it on anything. I think your best bet is to see how your current implementation works under load. Maybe just a few tweaks will make things work for you - but changing your underlying framework seems a bit much. That being said - your infrastructure team will also have to be involved as it seems you have some serious load requirements. Good luck!
1,041,457
We have a new project for a web app that will display banners ads on websites (as a network) and our estimate is for it to handle 20 to 40 billion impressions a month. Our current language is in ASP...but are moving to PHP. Does PHP 5 has its limit with scaling web application? Or, should I have our team invest in picking up JSP? Or, is it a matter of the app server and/or DB? We plan to use Oracle 10g as the database.
2009/06/24
[ "https://Stackoverflow.com/questions/1041457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51281/" ]
No offense, but I strongly suspect you're **vastly overestimating** how many impressions you'll serve. That said: PHP or other languages used in the application tier really have little to do with scalability. Since the application tier delegates it's state to the database or equivalent, it's straightforward to add as much capacity as you need behind appropriate load balancing. Choice of language does influence per server efficiency and hence costs, but that's different than scalability. It's scaling the state/data storage that gets more complicated. For your app, you have three basic jobs: 1. what ad do we show? 2. serving the add 3. logging the impression Each of these will require thought and likely different tools. The second, serving the add, is most simple: use a [CDN](http://en.wikipedia.org/wiki/Content_delivery_network). If you actually serve the volume you claim, you should be able to negotiate favorable rates. Deciding which ad to show is going to be very specific to your network. It may be as simple as reading a few rows from a database that give ad placements for a given property for a given calendar period. Or it may be complex contextual advertising like google. Assuming it's more the former, and that the database of placements is small, then this is the simple task of scaling database reads. You can use replication trees or alternately a caching layer like [memcached](http://www.danga.com/memcached/). The last will ultimately be the most difficult: how to scale the writes. A common approach would be to still use databases, but to adopt a sharding scaling strategy. More exotic options might be to use a key/value store supporting counter instructions, such as [Redis](http://code.google.com/p/redis/), or a scalable OLAP database such as [Vertica](http://www.vertica.com/). All of the above assumes that you're able to secure data center space and network provisioning capable of serving this load, which is not trivial at the numbers you're talking.
PHP will be capable of serving your needs. However, as others have said, your first limits will be your network infrastructure. But your second limits will be writing scalable code. You will need good abstraction and isolation so that resources can easily be added at any level. Things like a fast data-object mapper, multiple data caching mechanisms, separate configuration files, and so on.
887,297
How many subsets of the set of divisors of $72$ (including the empty set) contain only composite numbers? For example, $\{8,9\}$ and $\{4,8,12\}$ are two such sets. I know $72$ is $2^3\cdot 3^2$, so there are $12$ divisors. Besides $2$ and $3$, there are $10$ composite divisors. Would this mean $\binom{10}{1}+\binom{10}{2}+...+\binom{10}{10}$? If so, how would you calculate this? Thank you.
2014/08/04
[ "https://math.stackexchange.com/questions/887297", "https://math.stackexchange.com", "https://math.stackexchange.com/users/165551/" ]
There are 10 composite divisors. ($4,8,6,12,24,9,18,36,72$). Any set of divisors that contains only composite numbers must be a subset of this set of 10. Conversely, any subset of this set of 10 is a subset that contains only composite numbers. So your problem is how to count how many subsets there are of this set of 10. Do you know a formula or a way of counting the numbers of subsets of a set?
The $10$ element set has $2^{10}$ subsets.
887,297
How many subsets of the set of divisors of $72$ (including the empty set) contain only composite numbers? For example, $\{8,9\}$ and $\{4,8,12\}$ are two such sets. I know $72$ is $2^3\cdot 3^2$, so there are $12$ divisors. Besides $2$ and $3$, there are $10$ composite divisors. Would this mean $\binom{10}{1}+\binom{10}{2}+...+\binom{10}{10}$? If so, how would you calculate this? Thank you.
2014/08/04
[ "https://math.stackexchange.com/questions/887297", "https://math.stackexchange.com", "https://math.stackexchange.com/users/165551/" ]
Since $72=2^3 3^2$ as you say, it has 12 positive divisors and therefore (eliminating 1, 2, and 3) has 9 composite positive divisors. Since the number of subsets of a set with 9 elements is $2^9=512$ (including the empty set), there should be 512 such subsets. (Notice that this is the same as $\binom{9}{0}+\binom{9}{1}+\binom{9}{2}+\cdots+\binom{9}{9}$.)
The $10$ element set has $2^{10}$ subsets.
887,297
How many subsets of the set of divisors of $72$ (including the empty set) contain only composite numbers? For example, $\{8,9\}$ and $\{4,8,12\}$ are two such sets. I know $72$ is $2^3\cdot 3^2$, so there are $12$ divisors. Besides $2$ and $3$, there are $10$ composite divisors. Would this mean $\binom{10}{1}+\binom{10}{2}+...+\binom{10}{10}$? If so, how would you calculate this? Thank you.
2014/08/04
[ "https://math.stackexchange.com/questions/887297", "https://math.stackexchange.com", "https://math.stackexchange.com/users/165551/" ]
There are 10 composite divisors. ($4,8,6,12,24,9,18,36,72$). Any set of divisors that contains only composite numbers must be a subset of this set of 10. Conversely, any subset of this set of 10 is a subset that contains only composite numbers. So your problem is how to count how many subsets there are of this set of 10. Do you know a formula or a way of counting the numbers of subsets of a set?
If you have the set of composite divisors, $S$, then $\mathcal{P}(S)$ is the set of subsets of $S$. This is calles "parts of $S$". And $|\mathcal{P}(S)| = 2^{|S|}$. So in your case, there are $2^{10} = 1024$ subsets of the set of divisors of $72$ that only contain composite numbers.
887,297
How many subsets of the set of divisors of $72$ (including the empty set) contain only composite numbers? For example, $\{8,9\}$ and $\{4,8,12\}$ are two such sets. I know $72$ is $2^3\cdot 3^2$, so there are $12$ divisors. Besides $2$ and $3$, there are $10$ composite divisors. Would this mean $\binom{10}{1}+\binom{10}{2}+...+\binom{10}{10}$? If so, how would you calculate this? Thank you.
2014/08/04
[ "https://math.stackexchange.com/questions/887297", "https://math.stackexchange.com", "https://math.stackexchange.com/users/165551/" ]
Since $72=2^3 3^2$ as you say, it has 12 positive divisors and therefore (eliminating 1, 2, and 3) has 9 composite positive divisors. Since the number of subsets of a set with 9 elements is $2^9=512$ (including the empty set), there should be 512 such subsets. (Notice that this is the same as $\binom{9}{0}+\binom{9}{1}+\binom{9}{2}+\cdots+\binom{9}{9}$.)
If you have the set of composite divisors, $S$, then $\mathcal{P}(S)$ is the set of subsets of $S$. This is calles "parts of $S$". And $|\mathcal{P}(S)| = 2^{|S|}$. So in your case, there are $2^{10} = 1024$ subsets of the set of divisors of $72$ that only contain composite numbers.
50,217,930
I did read a following article: <http://surbhistechmusings.blogspot.com/2016/05/neo4j-performance-tuning.html> I come across > > We loaded the files into OS cache > > > It is about loading file (on local disk) into OS cache. Could you explain me how to do such loading? And tell me please if such cache is in-memory? What is cause that it can help?
2018/05/07
[ "https://Stackoverflow.com/questions/50217930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9720141/" ]
Operate on Unicode strings, not byte strings. Your source is encoded as UTF-8 so the characters are encoded from one to four bytes each. Decoding to Unicode strings or using Unicode constants will help. The code also appears to be Python 2-based, so on narrow Python 2 builds (the default on Windows) you'll still have an issue. You could also have issues if you have graphemes built with two or more Unicode code points: ``` # coding: utf-8 import re t = u" [°] \n € dsf $ ¬ 1 Ä 2 t3¥4Ú"; print re.sub(ur'[^A-Za-z0-9 !#%&()*+,-./:;<=>?[\]^_{|}~"\'\\]', '_', t, flags=re.UNICODE) ``` Output (on Windows Python 2.7 narrow build): ``` __ [_] _ _ dsf _ _ 1 _ 2 t3_4_ ``` Note the first emoji still has a double-underscore. Unicode characters greater than U+FFFF are encoded as surrogate pairs. This could be handled by explicitly checking for them. The first code point of a surrogate pair is U+D800 to U+DBFF and the second is U+DC00 to U+DFFF: ``` # coding: utf-8 import re t = u" [°] \n € dsf $ ¬ 1 Ä 2 t3¥4Ú"; print re.sub(ur'[\ud800-\udbff][\udc00-\udfff]|[^A-Za-z0-9 !#%&()*+,-./:;<=>?[\]^_{|}~"\'\\]', '_', t, flags=re.UNICODE) ``` Output: ``` _ [_] _ _ dsf _ _ 1 _ 2 t3_4_ ``` But you'll still have a problem with complex emoji: ``` # coding: utf-8 import re t = u"‍‍‍"; print re.sub(ur'[\ud800-\udbff][\udc00-\udfff]|[^A-Za-z0-9 !#%&()*+,-./:;<=>?[\]^_{|}~"\'\\]', '_', t, flags=re.UNICODE) ``` Output: ``` ___________ ```
How about: ``` print(re.sub(r'[^A-Öa-ö0-9 !#%&()*+,-./:;<=>?[\]^_{|}~"\'\\]', '_', t)) ```
28,148,414
I have a query and have tried to do some research but i am having trouble even trying to google what i am looking for and how to word it. Currently each div has a label and then an input field. i have made all these input fields with rounded edges. my problem is when i click in the chosen area a rectangular border appears around the edge. the image can be viewed here: `http://www.tiikoni.com/tis/view/?id=6128132` how can i change the appearance of this border? This is is my css code: ``` div input{ border: 2px solid #a1a1a1; padding: 10px 40px; background: #dddddd; width: 300px; border-radius: 25px; } ``` This is part of my html: ``` <div class="fourth"> <label> Confirm Password: </label> <input type="text" name="cPassword" class="iBox" id="cPassword" onkeyup="passwordValidation()" placeholder="confirm it!" autocomplete="off"> <p id="combination"></p> </div> ```
2015/01/26
[ "https://Stackoverflow.com/questions/28148414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4486219/" ]
One solution is to remove default outline on focus using: ``` div input:focus{ outline: none; } ``` ```css div input { border: 2px solid #a1a1a1; padding: 10px 40px; background: #dddddd; width: 300px; border-radius: 25px; } div input:focus { outline: none; } ``` ```html <div class="fourth"> <label>Confirm Password:</label> <input type="text" name="cPassword" class="iBox" id="cPassword" onkeyup="passwordValidation()" placeholder="confirm it!" autocomplete="off" /> <p id="combination"></p> </div> ```
This is the `outline` property and can be set in the same way as a `border`, it is typically assigned for the `:focus` state of suitable elements, it can also be set to `none` [**More on `outline` from MDN**](https://developer.mozilla.org/en-US/docs/Web/CSS/outline) > > The CSS outline property is a shorthand property for setting one or > more of the individual outline properties outline-style, outline-width > and outline-color in a single declaration. In most cases the use of > this shortcut is preferable and more convenient. > > > [**More on `:focus` from MDN**](https://developer.mozilla.org/en-US/docs/Web/CSS/:focus) > > The `:focus` CSS pseudo-class is applied when a element has received > focus, either from the user selecting it with the use of a keyboard or > by activating with the mouse (e.g. a form input). > > > It is also interesting to note that by adding the `tabindex` attribute to elements (such as `div`) you can also enable styling of the `:focus` state. ```css div input { border: 2px solid #a1a1a1; padding: 10px 40px; background: #dddddd; width: 300px; border-radius: 25px; } input:focus { outline: none; border-color:red; } ``` ```html <div class="fourth"> <label>Confirm Password:</label> <input type="text" name="cPassword" class="iBox" id="cPassword" onkeyup="passwordValidation()" placeholder="confirm it!" autocomplete="off" /> <p id="combination"></p> </div> ```