text:
Q: Jelly script to reset the issue resolution in JIRA I am trying to run a jelly script in JIRA to set the resolution to null for all my issues. The following script runs without errors and returns this:
<JiraJelly xmlns:jira='jelly:com.atlassian.jira.jelly.JiraTagLib' xmlns:log='jelly:log' xmlns:core='jelly:core' xmlns:jx='jelly:xml' xmlns:util='jelly:util'>org.ofbiz.core.entity.GenericValue.NULL_VALUEorg.ofbiz.core.entity.GenericValue.NULL_VALUEorg.ofbiz.core.entity.GenericValue.NULL_VALUE.... </JiraJelly>

Here is the script.
<JiraJelly xmlns:jira="jelly:com.atlassian.jira.jelly.JiraTagLib" xmlns:util="jelly:util" xmlns:core="jelly:core" xmlns:jx="jelly:xml" xmlns:log="jelly:log">
        <jira:RunSearchRequest var="issues" />

        <core:forEach var="genericIssue" items="${issues}">
            <core:invokeStatic className="com.atlassian.jira.issue.IssueImpl" method="getIssueObject" var="issue">
                <core:arg type="org.ofbiz.core.entity.GenericValue" value="${genericIssue}"/>
            </core:invokeStatic>

            <core:invoke on="${issue}" method="setResolution">
                <core:arg type="org.ofbiz.core.entity.GenericValue">org.ofbiz.core.entity.GenericValue.NULL_VALUE</core:arg>
            </core:invoke>

        </core:forEach>
</JiraJelly>

Does any one have any idea why this isn't working or have any ideas on how I might set the resolution to nothing?
Thank you!!

A: Updating issues via jelly in JIRA is a bit broken. The best example of how to make it work that I've seen is by using ActionDispatcher as shown on the docs page in a comment by Alastair King.

A: I know it can be done with Jelly runner, but i thinks that this would be easier to do so using the Jira remote API or the Jira CLI. A more elaborated example of the Jira remote API can be found here. If anyone wants me to post a working source code feel free to ask.


text:
Q: How to change url instantly without waiting for model to load on slow connection? Is there any way to change page url instantly when clicking on a link without waiting for the model to load?
I'm using ember-data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ child changes parent member at some point between copy constructor and ouput If you test the following code, it compiles and runs without issue:
#include <iostream>

using namespace std;

class Parent
{
public:
    Parent(bool flag) : flag(flag) {}
    virtual void display() = 0;

protected:
    bool flag;
};

class Child : public Parent
{
public:
    Child(bool flag) : Parent(flag) {}
    Child(const Child & rhs) : Parent(rhs.flag) {}
    virtual void display() { cout << flag << endl; }
};

int main()
{
    // Set Flag to true
    Child tru(true);
    Child * storage [2];
    storage[0] = new Child(tru);
    storage[0]->display();

    // Set Flag to false
    Child * container = new Child(storage[0]);
    delete storage[0];
    storage[0] = new Child(false);
    storage[0]->display();

    // Set Flag to true
    storage[1] = new Child(container);
    storage[1]->display();

    return 0;
}

However, after I plug this snippet into my program, the Child objects consistently change their bool flag to true between the time they are created with the copy constructor and the time I actually attempt to display their bool flag value. I know the change initially sticks thanks to copious amounts of cout lines calling values at every step of the way, but when my display function is called, their values all switch to true.
I haven't been able to successfully reproduce the error, externally, but while I attempt to do so, I'm hoping someone might have an idea of what could possibly interfere with this process? Is there a common error, mistake or conflict I should be checking for in a situation like this?

A: storage[1] = new Child(container); will create the new object passing the pointer container to the new object.
I seriously doubt this is what you intended. Did you mean to type storage[1] = new Child(*container); (passing the reference to the pointed-to object?)
Remember a pointer is (essentially) a numerical-address, thus can evaluate to true (!= 0) or false ( == 0), thus:
storage[1] = new Child(container); evaluates as storage[1] = new Child(container != 0); (and that is new Child(0xffcd3ds != 0); //example memory address, thus calling the standard constructor taking bool, rather than the copy-constructor.
Take into account that that error also specifies the same issue one line 32 Child * container = new Child(storage[0]);, the exact same bug can be found here (thus container's object will be false anyway), however it's slightly more subtle given child * [] can be used as child **. But I imagine you can figure it out with ease.
Note that this kind of comparison may seem like a "trap" if your learning programming, however I assure you, such quick-and-dirty "is the pointer null" comparisons are a huge help in more complex projects.
In furtherance, I ran your snippet though the Visual-Studio compiler - it output the following compile log (successfully building the project)
1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1>  playground.cpp
1>c:\users\USER\documents\visual studio 2015\projects\project1\playground.cpp(32): warning C4800: 'Child *': forcing value to bool 'true' or 'false' (performance warning)
1>c:\users\USER\documents\visual studio 2015\projects\project1\playground.cpp(38): warning C4800: 'Child *': forcing value to bool 'true' or 'false' (performance warning)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

(the following is not meant to have any emotion, I realize on reading it does sound somewhat sarcastic, it is meant in sincerity).
Note that those two warnings (effectively) tell you what I just did above, assuming whatever compiler you are using outputs a similar error (I'd be surprised if it didn't), the lesson here will be what I tell my apprentice every-day, always read the compiler-output log - obviously if your compiler doesn't output such a warning, remember the lesson anyway.
Slightly useful tip
If you are able to do so, please consider using the C++11 Smart Pointers, I note that you never call delete before you return 0, doing so is a soft error, and may leak memory on some systems.


text:
Q: Как вывести метод класса в шаблон django? view.py
class test(ListView):
    model = TestModel
    template_name = 'test/test.html'
    context_object_name = 'test'

    def myfunc(self):
        return 'test'

Как вывести в шаблон html функцию myfunc?
{{ myfunc }} и {{ test.myfunc }} не работает...

A: задачу решил, кому может пригодится
views.py
 class TestView(ListView):
        model = Test
        template_name = 'test/test.html'
        context_object_name = 'test'

        def get_context_data(self, *, object_list=None, **kwargs):
            context = super().get_context_data(**kwargs)
            context['test_data']= 'some data'
            return context

test_tags.py
register = template.Library()
@register.inclusion_tag('test/test_tags.html')
def install_plugin(arg1='empty'):
    #some work...
    return {'data' : arg1}

test_tags.html
{{ data }}

test.html
{% test_tags test_data %}


text:
Q: How to disable copying the shapes present in chartarea? I have a chart in Excel where my macro populates 10 shapes by the right side of the chart area. I want to copy only the chart to the power point and could not find a way to disable copying the shapes so far. If I copy the chart, it copies the shapes as well.

A: Here's a quick example that copies the first chart from the active sheet, pastes it to the first slide of the active presentation, and deletes any existing shapes from the pasted chart...
'Declare Excel variables
Dim ChartObj As ChartObject

'Declare PowerPoint variables
Dim ppApp As Object
Dim ppPres As Object
Dim ppChartObj As Object
Dim ppShape As Object

'Copy first chart from active sheet
Set ChartObj = ActiveSheet.ChartObjects(1)
ChartObj.Copy

'Paste chart into first slide of active presentation
Set ppApp = GetObject(, "PowerPoint.Application")
Set ppPres = ppApp.ActivePresentation
Set ppChartObj = ppPres.slides(1).Shapes.Paste(1)

'Delete shapes from chart
For Each ppShape In ppChartObj.Chart.Shapes
    ppShape.Delete
Next ppShape

Hope this helps!


text:
Q: How do I force Windows Phone to not recolor my App Bar Icons? I have an app I am developing and the entire theme is custom totally separate from whatever theme the user has chosen on their device. Is there a way to prevent Windows Phone from recoloring the application bar icons.  I am using a custom color here for the background color and the black looks quite bad.
I know this is possible cause the Twitter app for Windows Phone does it.  Any hints would be appreciated. Thanks
Jason

A: Big thanks to jimpanzer for pointing this out.

Ensures the icon is ALWAYS colored white regardless of the user's theme settings.
Very nice

A: XAML
The following XAML shows how to set the foreground and background colour and opacity of the application bar.
<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" Opacity="0.75" ForegroundColor="Green" BackgroundColor="Cyan">
    <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
    <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
    <shell:ApplicationBar.MenuItems>
        <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
        <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
    </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

Same for C#
ApplicationBar = new ApplicationBar();
    //Now set the AppBar properties :
ApplicationBar.Opacity = 0.75;
ApplicationBar.BackgroundColor = Color.FromArgb(120, 0,190,190);
ApplicationBar.ForeGroundColor = Color.FromArgb(120, 0,140, 43);


text:
Q: how do I make java.exe use multiple cpu's? I'm running Hudson on a Windows 7 (x64) machine: this is simply started using 'java -jar hudson.war'. For some reason the java process only uses one cpu, out of 2 available, although it is running multiple threads. I'm pretty sure the default behaviour for the os is to spread the threads of a multi-threaded program across cpu's, unless explicitly told otherwise (using some SetProcessorAffinity api if I remember correctly).
Is there a way to tell java to use multiple cpu's?

A: Normally, java.exe will automatically put threads onto different CPUs.
If it does not, it might be because the program is I/O bound, rather than CPU-bound, or because the threads cannot run concurrently due to synchronization.
See http://www.oracle.com/technetwork/java/hotspotfaq-138619.html#perf_scaling for some more information.
You'll probably have to debug Hudson to know why it uses only one processor.


text:
Q: Showing initially full image with PhotoView in Android I am developing an Android app. In my application, I need zoom image features like in Facebook. So, I used this library - https://github.com/chrisbanes/PhotoView. But I am having problem with showing full image when the image is first loaded.
This is how I set PhotoViewAttacher to ImageView
    photoViewAttacher = new PhotoViewAttacher(imageView);
    photoViewAttacher.setZoomable(true);
    photoViewAttacher.update();

This is the xml layout of imageview
      <ImageView

        android:id="@+id/item_details_image"
        android:scaleType="fitCenter"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

What I am trying to do is I want the image to show fit to the screen if the image is bigger then screen size. No matter how big it is. But image can be smaller than screen size. I just want to show full image at initial. But the above code gives me this result.

As you can see in the screenshot, it cannot show the whole image. It showing only partially. If I want to see other area of image, I want to scroll or swipe because the image does not fit to screen initially. So that I tried to change the XML to show the whole area of image initially. This is the XML I changed to.
<ImageView

        android:id="@+id/item_details_image"
        android:scaleType="centerInside"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

As you can see I changed the height from match_parent to wrap_content. Scale type as well. When I changed to that, it shows the full image initially like this.

It shows full image but smaller. It is totally ok for me. That is what I want to have. The problem is with zoom feature. When I zoom up, the image cannot go bigger than the image height. See the screenshot below.

As you can see above, it is not showing full image when I zoom up. ImageView height is not changing.

A:  <ImageView
        android:id="@+id/item_details_image"
        android:scaleType="fitCenter"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

You Need to match_parent both height or width


text:
Q: Can I use jquery getScript() without a callback? I need to use a javascript function from an external js file inside another js file. This is basically the code I've tried:
$.getScript('js/myHelperFile.js');
myHelperFunction();

This doesn't work - I get an error of "myHelperFunction is not defined".
However, this code works:
$.getScript('js/myHelperFile.js', function(){myHelperFunction();});

I specifically want to be able to do it the first way - load the file at the top of my file, and then use any functions I need from there on. Is this possible, or am I misunderstanding how getScript works?

A: Doing it "the first way" is not presently* possible with jQuery.getScript because it only supports asynchronous operations, and thus it returns immediately after being called.
Since it returns before your script has been downloaded when the script tries to invoke myHelperFunction(), myHelperFunction is undefined and causes that error.
*See the update at the bottom of this answer for a promising new method that will eventually allow you to write code that almost works like your desired style.
You could do it using jQuery.ajax with the async setting set to false with code that is something like this:
$.ajax({
  url: 'js/myHelperFile.js',
  async: false,
  dataType: "script",
});

myHelperFunction();

But as the documentation states:

synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

This is a very bad thing.  If the server that is providing myHelperFile.js is slow to respond at any time (which will happen at some point) the page will become unresponsive until the request finishes or timesout.
It would be a much better idea to embrace the callback style which is used heavily throughout jQuery.
$.getScript('js/myHelperFile.js', function () {
   myHelperFunction();
});

You don't need to use an anonymous function either, you can put your code in a named function:
function doStuffWithHelper() {
   myHelperFunction();
}

$.getScript('js/myHelperFile.js', doStuffWithHelper);

If you need to load more than one dependency before calling myHelperFunction this won't work unless you set up some sort of system to figure out if all of your dependencies are downloaded before you execute your code.  You could then set the callback handler on all of the .getScript calls to check that all of your dependencies are loaded before running your code.
var loadedScripts = {
    myHelperFile: false,
    anotherHelperFile: false
};

function doStuffWithHelper() {
    // check to see if all our scripts are loaded
    var prop;
    for (prop in loadedScripts) {
        if (loadedScripts.hasOwnProperty(prop)) {
            if (loadedScripts[prop] === false) {
                return; // not everything is loaded wait more
            }
        }
    }

    myHelperFunction();
}

$.getScript('js/myHelperFile.js', function () {
    loadedScripts.myHelperFile = true;
    doStuffWithHelper();
});
$.getScript('js/anotherHelperFile.js', function () {
    loadedScripts.anotherHelperFile = true;
    doStuffWithHelper();
});

As you can see, this kind of approach gets convoluted and unmaintainable fast.
If you do need to load multiple dependencies you would probably be better off using a scriptloader such as yepnope.js to do it.
yepnope( {
        load : [ 'js/myHelperFile.js', 'js/anotherHelperFile.js' ],
        complete: function () {
            var foo;
            foo = myHelperFunction();
            foo = anotherHelperFunction(foo);
            // do something with foo
        }
} );

Yepnope uses callbacks just like .getScript so you can not use the sequential style you wanted to stick with. This is a good tradeoff though because doing multiple synchronous jQuery.ajax calls in a row would just compound that methods problems.

Update 2013-12-08
The jQuery 1.5 release, provides another pure jQuery way of doing it. As of 1.5, all AJAX requests return a Deferred Object so you could do this:
$.getScript('js/myHelperFile.js').done(function () {
   myHelperFunction();
});

Being a asynchronous request, it of course requires a callback. Using Deferreds however has a huge advantage over the traditional callback system, using $.when() you could easily expand this to loading multiple prerequisite scripts without your own convoluted tracking system:
$.when($.getScript('js/myHelperFile.js'), $.getScript('js/anotherHelperFile.js')).done(function () {
  var foo;
  foo = myHelperFunction();
  foo = anotherHelperFunction(foo);
  // do something with foo
});

This would download both scripts simultaneously and only execute the callback after both of them were downloaded, much like the Yepnope example above.

Update 2014-03-30
I recently read an article that made me aware of a new JavaScript feature that may in the future enable the kind of procedural-looking-yet-async code that you wanted to use! Async Functions will use the await keyword to pause the execution of a async function until the asynchronous operation completes.  The bad news is that it is currently slated for inclusion in ES7, two ECMAScript versions away.
await relies on the asynchronous function you are waiting on returning a Promise. I'm not sure how the browser implementations will behave, if they will require a true ES6 Promise object or if other implementations of promises like the one jQuery returns from AJAX calls will suffice. If a ES6 Promise is required, you will need to wrap jQuery.getScript with a function that returns a Promise:
"use strict";
var getScript = function (url) {
  return new Promise(function(resolve, reject) {
    jQuery.getScript(url).done(function (script) {
      resolve(script);
    });
  });
};

Then you can use it to download and await before proceeding:
(async function () {
  await getScript('js/myHelperFile.js');
  myHelperFunction();
}());

If you are really determined to write in this style today you can use asyc and await and then use Traceur to transpile your code into code that will run in current browsers. The added benefit of doing this is that you could also use many other useful new ES6 features too.

A: Using the getScript() function on its own, I don't think you can. The problem is that the script is being loaded using AJAX (indeed, getScript is just a shorthand for a special $.ajax() function), and when the browser tries to execute the function on the next line, perhaps the server has not yet returned the file.
If you do not wish to use a callback function, you will need to use the jQuery $.ajax() function in its original form (and forget about the getScript()), and set the transfer as synchronous. This way, you can be sure that the script will be loaded before execution of your code continues:
$.ajax({
    url: url,
    dataType: "script",
    async: false
});

A: $.getScript, and really all HTTP OP related jQuery functions are non-blocking calls by default. That is to say that the code doesn't hang while the operation completes. What this means is that your code above will most certainly fail because there is no way that $.getScript will load the script before the line attempting to execute the method runs. This is why callback functions are accepted as parameters.
However, what you're trying to do is possible. Once the script has been loaded you should be able to call it from anywhere. All that's necessary to avoid the method being called prior to the script being downloaded is setting the necessary flags.
var HelperFileLoaded = false;
$.getScript('js/myHelperFile.js', function() { HelperFileLoaded = true; });

// ...

function btnSaveClick() {
    if(!HelperFileLoaded) return;
    myHelperFunction();
}

BenM's suggestion is possible but unless you're only making a single call to myHelperFunction it won't work as a solution because there will be no guarantee that the script will have downloaded before any other methods calling myHelperFunction have been triggered.

A: Your first one works fine if you're using JSONP, I do it that way often.


text:
Q: ValueError: Field 'id' when filter model data based on user How do I return objects based on the user who made the model entry? Here is what I've tried below but I get an error:
models.py
class Csv(models.Model):

  file_name = models.FileField(upload_to='csvs', max_length = 100)
    public = models.BooleanField(default = False)
    user = models.ForeignKey(User, on_delete = models.CASCADE, null = True)
    name = models.CharField(max_length = 100)
    library = models.CharField(max_length = 100, null = True)

def __str__(self):
    return "File id: {}".format(self.id)

query
from .models import Csv
x = Csv.objects.get(user = "site_manager")

returns the error in the description
from .models import Csv
x = Csv.objects.get(library = "example library")

returns a file from the database as intended. Why does this not work when I search based on username?

A: The reason is that field user is a foreign key, so the search criteria must indicate which column in model User is the one that must match the search criteria:
from .models import Csv
x = Csv.objects.get(user__username = "site_manager")

In this case, double underscore notation indicates that we are referencing field username in instance of model User pointed by field user.


text:
Q: Plotting a Tuple in Python In python, what is the syntax that will let me plot a tuple such as
t = [(9,2,5),(3,6,4),(2,8,4)]

I am having trouble since there are three elements in each combination.

A: If your t means: (x,y,z) => (9, 3, 2), (2, 6, 8), (5, 4, 4)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

data = [(9, 3, 2), (2, 6, 8), (5, 4, 4)]
x, y, z = data[0], data[1], data[2]
ax = plt.subplot(111, projection='3d')
total_point = len(data)
ax.scatter(x[:total_point], y[:total_point], z[:total_point], c='red')
ax.plot(x[:total_point], y[:total_point], z[:total_point], c='yellow')

ax.set_zlabel('Z')
ax.set_ylabel('Y')
ax.set_xlabel('X')
plt.show()

output:


text:
Q: To have external scope for variables in php I am simply trying to store $username in a file that will be included in all the pages after a user logins.Thus, this $username will change dynamically according to the user that has logged in.
includeusername.php
<?php

     $username=$_POST['username'];

    echo $username;
?>

The variable does get initialized in includeusername.php ,as echo gives the value.On including this file in the main page which will display  "Welcome $username!" i write this code
     Welcome  <?php  echo  $username;  ?>!

The error shown is Undefined index: username.
How to have access to data from other page?And transfer it to the next page too!
I've used the following but it didn't work:

*

*sessionStorage()

*$_SESSION['username']

*include/require
Any other idea to have persistent data across the web pages?

A: <?php
    session_start();
    $_SESSION["username"]=$_REQUEST['username'];
?>

In your includeusername.php use
Welcome  <?php  echo  $_SESSION["username"];  ?>!

A: start the see SESSION START
<?php
   session_start();
    $username=$_POST['username'];
    echo $username;
   echo "Assigning session value to: " . $username;
   $_SESSION['username'] = $username;

?>


text:
Q: A small pattern in the primes. What can we do to continue the pattern ? The pattern seems to have to do with divisors of the number $n$ or $n-1$.
$$
\begin{matrix}
p(1) & = 2 \\
p(2) & = 3 \\
p(3) & = 5 \\
p(4) & = 7 & = p(3) + (p(3) - p(2))\\
p(5) & = 11 & = p(4) + (p(2)^2 - p(3)) \\
p(6) & = 13 & = p(5) + (p(5) - p(2)^2) \\
p(7) & = 17 & = p(6) + (p(2)p(3) - p(5)) \\
p(8) & = 19 & = p(7) + (p(7) - p(2)p(3)) \\
p(9) & = 23 & = p(8) + (p(2)p(4) - p(7))\\
p(10) & = 29 & = p(9) + (p(3)^2 - p(2)p(4)) \\
p(11) & = \text{here the rule mysteriously ends}
\end{matrix}
$$
Any idea of how to generalize the rule so that it extends further than $p(11)$, where $p(n)$ is the $n$th prime number in $\Bbb{Z}$.

A: I'm not quite sure what rule you want here, that $p(n) = p(n - 1) + (\prod p(i) - \prod p(j))$? I think this would just follow from the fundamental theorem of arithemtic: $p(n) - p(n - 1)$ can be expressed as the difference between two numbers less than $p(n)$ (not proving this but feels obvious), which both then factor.


text:
Q: Scope changes do not propogate to the parent scope (angular, bootstrap datetime picker) I have got a datetimepicker that I am using with angular js.. first I'll show some code.
the html

                    <input ng-model= "startDate" type= "text" class= "form-control" />

                <input type= "button" value= "Check Value" ng-click= "check()"/>

The javascript
app.controller('DateTimePicker', [
    '$scope', function($scope) {

        $scope.check = function() {
            alert($scope.startDate);
        }

        function init() {
            $('#datetimepicker1').datetimepicker();
            $('#datetimepicker1').on('dp.change', function() {
                $scope.startDate = $('#datetimepicker1').val();
            });
        }

        init();

    }
]);

This is the gist of my setup. Now, when I click the "Check Value" button, I get undefined. This happens ever after I open the popup menu and select a date/time.
I thought this was because the "check" function is defined as a part of the Controller level scope, and anything that was selected (as "startDate") in the datetimepicker was part of a different child scope.
A small test seems to have confirmed this.
$scope.startDate = "2016-07-05";

$scope.check = function() {
    alert($scope.startDate);       // this gets called with the value above
}

The hardcoded value gets alerted, but it is never updated to the value I select inside the datepicker... EVEN with the listener I assigned to it to more or less set it manually.
Is there a way I can get the scopes to stop clashing in this way?

A: Try to add: $scope.digest() after changing $scope.startDate.


text:
Q: YYYYWW format in SQL Redshift My company recently migrated to Redshift from Redash recently and I'm having a hard time recreating the YEARWEEK() function available in MySQL but not in Redshift. I've searched high and low to find a way to do this but can't seem to find the correct resource as I'm also pressed for time.
table:   order
column:   created_at
stored as:   29/03/21 03:02 -- add 8 hours here via date_add()
desired output: 202113 -- yearweek() yyyyww
In MySQL this gives me the correct output YEARWEEK(DATE_ADD(o.created_at, INTERVAL 8 HOUR))

A: You should be able to use DATE_PART here along these lines:
CONCAT(DATE_PART(y, o.created_at + interval '8 hours'),
       DATE_PART(w, o.created_at + interval '8 hours'))

Note that it is not clear if the above would produce identical output to MySQL's YEARWEEK function.

A: SELECT TO_CHAR(created_at + interval '8 hours', 'IYYY-IW');

"IW": ISO week number of year (the first Thursday of the new year is in week 1.)
Redshift Docs


text:
Q: UnsatisfiableError: The following specifications were found to be in conflict: I am trying to install opensv3 for Anaconda using the below command
conda install -c menpo opencv3

But I am getting the below error

UnsatisfiableError: The following specifications were found to be in conflict:
   - opencv3
   - zict

Not sure why Opencv3 is already there and why zict is a problem.
Any way I can uninstall both of them and then probably start fresh installation ?
Or what would be the correct way to resolve this ?'
EDIT: I am on Python 3.6. I have tensorflow and numpy already installed.


text:
Q: Understanding unit testing for dynamically changing condition I was trying to understand how to write unit tests for a few days now. I'm confused with  following scenarios in the existing code.
In first function the max value changes depending on the object created at run time but in the second case it is a constant.
NOTE: The following functions are not related. These are two different scenarios.
SomeFunction1(arg1,....)
{
  if(arg1 > someObject.MaxAllowedValue)
  {
     throw exception;
  }
}

SomeFunction2(arg1,....)
{
  if(arg1 > maxAllowedValue)
  {
     throw exception;
  }
}

I am trying to test whether the function throws an exception when max value is exceeded.
Does the unit test remain the same in both the cases or is it different?

A: That would depend somewhat on where someObject came from and how its property value changes.  But assuming that someObject.MaxAllowedValue and maxAllowedValue have the same value, the test will remain the same.  Remember, you are testing the behaviour of SomeFunctionX, not the implementation details.

A: TL;DR: 1) refactor your code 2) mock someObject
 Refactor your code
Congraz, you are just unit testing for a few days now and have learned one of the most important aspects of unit testing (especially when done early in the development process):

The act of writing a unit test is more an act of design
than of verification.

(Uncle Bob, Agile Software Development, Principles, Patterns, and Practices)

So if SomeFunction1 and SomeFunction2 have closely related functionality and concerns, refactor them into one method. If not, you also need to write different unit tests for them since they cover different functionality/concerns.
 Mock
If your code still contains
if(arg1 > someObject.MaxAllowedValue)

think about whether your current unit test should also test someObjects (probably not). If not, you should mock it, e.g. with EasyMock (this cheat sheet is helpful for both junit and EasyMock).
Update: Since you are testing another class, not that of someObject, it does not matter that someObject changes at runtime. All you have to do is cover all possible behaviors of your implementation under test with your tests, e.g.

*

*arg1 == someObject.MaxAllowedValue

*arg1 == someObject.MaxAllowedValue+1


text:
Q: Android compilation failure in maven I am making an Android app, and have created a custom view to do some animation.
I have created a custom view, extending ImageView and implementing ValueAnimator.AnimatorUpdateListener.
When I try to compile this with maven it fails with "package android.animation does not exist"
However, when building within Intellij Idea it builds fine. After building in Idea it is even possible to run mvn install successfully.
The successful build running fine in the emulator, but not on my physical device.
When trying to start it up on the device I get:
Failed resolving Lno/derp/myapp/view/MyAnimatedView; interface 7 'Landroid/animation/ValueAnimator$AnimatorUpdateListener;'
Link of class 'Lno/derp/myapp//view/MyAnimatedView;' failed
Could not find class 'no/derp/myapp/view/MyAnimatedView', referenced from method no/derp/myapp.MainActivity.onCreate

and then
java.lang.ClassNotFoundException: no/derp/myapp.MyAnimatedView in loader dalvik.system.PathClassLoader[/data/app/no/derp/myapp-2.apk]

pom.xml:
 <packaging>apk</packaging>
 <name>My App</name>

 <dependencies>
   <dependency>
     <groupId>com.google.android</groupId>
     <artifactId>android</artifactId>
     <version>2.3.3</version>
     <scope>provided</scope>
   </dependency>
 </dependencies>

<build>
  <plugins>
    <plugin>
      <groupId>com.jayway.maven.plugins.android.generation2</groupId>
      <artifactId>android-maven-plugin</artifactId>
      <version>3.0.0</version>
      <configuration>
        <androidManifestFile>${project.basedir}/AndroidManifest.xml</androidManifestFile>
        <assetsDirectory>${project.basedir}/assets</assetsDirectory>
        <resourceDirectory>${project.basedir}/resources</resourceDirectory>
      <undeployBeforeDeploy>true</undeployBeforeDeploy>
    </configuration>
    <extensions>true</extensions>
  </plugin>

  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <target>1.6</target>
        <source>1.6</source>
    </configuration>
  </plugin>
</plugins>

I am using the latest version of the SDK. A class importing the mentioned package does not compile, it is not just the view. The same happens with version 2.8.3 of android-maven-plugin (or maven-android-plugin as it was called)
Any ideas?

A: android.animation is available since API Level 11, you need set your dependency in your pom.xml to use 3.0+ to compile your code in command-line.
The reason why it works in Intellij is IDE usually use default.properties to resolve the SDK used to compile source code, I suppose you use the correct API level in your default.properties.
Hope this help.

A: It seems you are missing the configuration of the plugin for the platform/api level. Check out e.g. helloflashlight example of the official samples.
In your case you would have to add
                <sdk>
                    <!-- platform or api level (api level 4 = platform 1.6)-->
                    <platform>4</platform>
                </sdk>

with api level 9 or 10 or whatever you need. See the API level doc.
And for the compile plugin to have the right API you have to have the correct android dependency. You potentially have to use my Maven Android SDK Deployer to push the dependency into your local repository

A: Maven Android SDK Deployer helped since I got
  <dependency>
      <groupId>android</groupId>
      <artifactId>android</artifactId>
      <version>4.0_r2</version>
      <scope>provided</scope>
  </dependency>

But the application still crashes on my phone, same as before, "Link of .. failed". Which is natural, since I probably have Android 2.X on my phone.
The reason Idea compiles is because it has the Android SDK set manually, it does not use the maven plugin, I think.


text:
Q: Typescript imitation problems Hi I have the following error in typescript:
class A {
    constructor() {
        this.init();
    }

    public init() {
        console.log('a')
    }
}

class B extends A {
    constructor(public text) {
        super();
    }
    public init() {
        console.log(this.text)
    }
}

new B('text');

The console writes undefined.
What can be done to overcome it.

A: This happens because the super() call is the first thing that's called when you call new B('text'), the super call immediately calls this.init(), since this is an instance of B, not A, it tries to call console.log(this.text) and not console.log('text'). But this.text is only set after the super call, not before.
This is why you should not do work in the constructor. Until the constructor had completely finished running, your object is not ready for action.
You should remove the init() call from the parent's constructor, and call it separately, like so:
class A {
    public init() {
        console.log('a')
    }
}

class B extends A {
    constructor(public text: string) {
        super(); // no longer strictly needed, as parent has no constructor anymore.
    }
    public init() {
        console.log(this.text)
    }
}

const b = new B('text');
// only now the object is ready.
b.init();

A: class B extends A {
    public text:string;
    constructor(public text) {
        super();
        this.text = text;
    }
    public init() {
        console.log(this.text)
    }
}

try it like this


text:
Q: VBA - Replacing commas in CSV not inside quotes   Filename = Dir(Filepath & "\" & "*.csv")
    While Filename <> ""
        SourceFile = Filepath & "\" & Filename
        TargetFile = SavePath & "\" & Replace(Filename, ".csv", ".txt")

        OpenAsUnicode = False

        Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
        'Detect Unicode Files
        Dim Stream: Set Stream = objFSO.OpenTextFile(SourceFile, 1, False)
        intChar1 = Asc(Stream.Read(1))
        intChar2 = Asc(Stream.Read(1))
        Stream.Close
        If intChar1 = 255 And intChar2 = 254 Then
            OpenAsUnicode = True
        End If

        'Get script content
        Set Stream = objFSO.OpenTextFile(SourceFile, 1, 0, OpenAsUnicode)
        arrData = Stream.ReadAll()
        Stream.Close

        'Create output file
        Dim objOut: Set objOut = objFSO.CreateTextFile(TargetFile)
        objOut.Write Replace(Replace(arrData,",", "#|#"), Chr(34), "")  '-- This line is working fine but it is replacing all the commas inside the text qualifier as well..
        objOut.Close

        Filename = Dir

    Wend

In the above code the line objOut.Write Replace(Replace(arrData,",", "#|#"), Chr(34), "") is replacing all the commas with #|# including the commas inside string.so I want to replace only commas which are not in double quotes.
File containing the string
"A","B,C",D
Result I need is
A#|#B,C#|#D
Thanks for your help in advance.

A: How about something along the line of:
objOut.Write Mid(Replace(Replace(arrData,""",""", "#|#"), Chr(34), ""), 2)

Basically, this exchanges now "," for #|#. But that's not enough as the file begins with a ". So, this one is being eliminated using the Mid() function. If the file also ends with a " then you would have to adjust that as well.
Based on the speed concerns noted in the comments here is the complete code which I used to test this solution:
Option Explicit
Option Compare Text

Public Sub ConvertFile()
Dim lngRowNumber As Long
Dim strLineFromFile As String
Dim strSourceFile As String
Dim strDestinationFile As String

strSourceFile = "C:\tmp\Extract.txt"
strDestinationFile = "C:\tmp\Extract_b.txt"

Open strSourceFile For Input As #1
Open strDestinationFile For Output As #2

lngRowNumber = 0

Do Until EOF(1)
    Line Input #1, strLineFromFile
    strLineFromFile = Mid(Replace(strLineFromFile, """,""", "#|#"), 2)
    Write #2, strLineFromFile
    strLineFromFile = vbNullString
Loop

Close #1
Close #2

End Sub

The tested file was 350 MB with a bit over 4 million rows. The code completed in less than a minute.


text:
Q: CircleCI config filters's tags's only regex: how to use flags I am trying to use the tags filter for a job in CircleCI.
workflows:
  foo:
    jobs:
      - bar:
          filters:
            tags:
              only: /\d+/

The only key of tags is what I am interested in.  Here's a sample regex: /\d+/

*

*It's designed to match 1+ digits

*Currently it doesn't match numbers with 2+ digits, because I need to add the global flag, /g

*

*See this question for why

*The correct regex would be /\d+/g

*The CircleCI docs point to java.util.regex docs

*Which didn't help me figure out if CircleCI regex would support flags :S

My question(s)

*

*Does CircleCI regex support the use of flags?

*How can I use flags in a regex?

*

*Can you provide a link to an example?

*Will my above regex of /\d+/g work?

A: I don't think CircleCI supports the use of flags, it doesn't seem necessary.
Looking at the example on https://circleci.com/docs/2.0/workflows/#using-regular-expressions-to-filter-tags-and-branches
You should ensure that you use ^ and $ to encapsulate your match pattern otherwise they will early out.
e.g. /\d+/ will match "123" but will stop as soon as the first digit is encountered, however /^\d+$/ will not since the pattern has start/end markers.


text:
Q: Creating dynamic drop-down list boxes in Rails but data not from the database I want to create 2 dynamic drop-down list boxes but the data for both of the text boxes are from API response not from the local database.When I select the data in first drop-down,a REST call has to be made depends on the data selected and the response has to be shown in the second drop down.
Is there any way to do this?

I'm searching for this a long time but I'm able to do like this only using the data from local database.

A: I would take a look at select2, which does an ajax call to a controller action, which then calls the APIs in question.


text:
Q: android 5.1 capitve portal on open wrt - redirect does not work due to browser cache? I am running a captive portal based on open wrt with nodogsplash. Since the new Android 5 update there is the following problem:
New android devices (5.0 and 5.1) that have already visited the network before, are not redirected to the captive portal login page. http requests are returned in a normal way. The webpages load even though the devices are not authenticated yet and should not be able to access any websites. https requests shows a network error. all other connections for apps etc... are denied on the phone.
Only when opening the incognito browser or delete all browser data, a normal http requests is forwarded to the captive portal login page where the user can authenticate and then receive full access to the network.
Older android devices, ios devices and laptops do not experience the same problem. here everything seems normal.
Did anyone come across something similar? This is a big security problem for our network.
Thank you and best regards.

A: I found the reason for my problem ;-)
The google chrome option "data saver" routes some traffic though google servers and therefore prevents the redirect to the captive portal login page. This is of course a major pain in the ass and I do not have a solution to work around this.
But at least I know now in what direction to look.
If anyone has an Idea - it would be greatly appreciated.


text:
Q: clips [EXPRNPSR3] Missing function declaration for person ; template person

(deftemplate person
(slot name (type STRING))
(slot gender (type SYMBOL)(allowed-symbols m f)); male, female
(slot birthyear (type INTEGER))
(slot birthPlace(type STRING))
(slot Fname (type STRING))
(slot Mname (type STRING))
(multislot siblingsName (type STRING))
(slot spouse (type STRING))
(slot height (type INTEGER))
(slot weight (type INTEGER))
(slot hairColor (type STRING))
(slot eyeColor (type STRING))
(multislot oddHabits (type STRING))
)

; menu

(defrule menu
 (declare (salience 9000))
 (initial-fact)
=>
(printout t crlf
    "Menu : " crlf
    " 1-    Infer family relations " crlf
    " 2-    Add additional members " crlf
    " 3-    Modify properties of already existing members " crlf
    " 4-    List properties of a specific individual by name or reference. " crlf
    " 5-    Find for all individuals matching a certain property. " crlf
    " 6-    Find all individuals matching two properties. " crlf
    " 7-    Display family relations (same like 1) along with their height comparison." crlf
    " 8-    exit the program" crlf
    "Choose 1 - 8 -> "
)
(assert (task type =(read)))
)

; exit

(defrule Exit
(task type 8)
=>
(exit)
)

(defrule  AddMember
(task type 2)
=>
(printout t "Enter Name" crlf)
(bind ?name (read))
(printout t "Enter gender" crlf)
(bind ?G (read))
(printout t "Enter birth year" crlf)
(bind ?BY(read))
(printout t "Enter birth place" crlf)
(bind ?BP(read))
(printout t "Enter Father name " crlf)
(bind ?FN (read))
(printout t "Enter Mother name" crlf)
(bind ?MN(read))
(printout t "Enter siblings" crlf)
(bind ?SI(readline))
(printout t "Enter spouse" crlf)
(bind ?SP (read))
(printout t "Enter height" crlf)
(bind ?H (read))
(assert
(person
(name ?name)(gender ?G)(birthyear ?BY)(birthPlace ?BP)(Fname ?FN)(Mname ?MN)(siblingsName ?SI )(spouse ?SP) (height ?H))
)
)

(defrule Modify
(task type 3)
=>

(printout t " (a) to modify gender" crlf)
(printout t " (b) to modify Birth Year" crlf)
(printout t " (c) to modify Birth Place" crlf)
(printout t " (d) to modify Father Name" crlf)
(printout t " (e) to modify Mother Name" crlf)
(printout t " (f) to modify Spouse" crlf)
(printout t " (g) to modify height" crlf)
(printout t " (h) to modify weight" crlf)
(assert (task type =(read)))
)

(defrule ModifyGender
(task type a)
=>
(printout t "Enter the name of person that you want to modify" crlf)
(bind ?n (read))
(printout t " Enter new value" crlf)
(bind ?V (read))
?num <- (person (name ?n))
(printout t " num is " ?num " " crlf)

(modify ?num (gender ?V))
)

When loading the file of my project an error shows up:

[EXPRNPSR3] Missing function declaration for person.

Error:

(defrule MAIN::ModifyGender
  (task type a)
  =>
  (printout t "Enter the name of person that you want to modify" crlf)
  (bind ?n (read))
  (printout t " Enter new value" crlf)
  (bind ?V (read))
  ?num
  <-

Can anyone help me?

A: Patterns matching facts are only allowed in the condition portion of a rule, not in the actions of the rule. You can either use multiple rules to determine which person to change and to apply the change:
(defrule ModifyGender-ask
   ?f <- (task type a)
   =>
   (retract ?f)
   (printout t "Enter the name of person that you want to modify" crlf)
   (bind ?n (read))
   (printout t " Enter new value" crlf)
   (bind ?V (read))
   (assert (modify-gender ?n ?V)))

(defrule ModifyGender-apply
   ?f <- (modify-gender ?n ?v)
   ?num <- (person (name ?n))
   =>
   (retract ?f)
   (modify ?num (gender ?v)))

(defrule ModifyGender-don't-apply
   ?f <- (modify-gender ?n ?v)
   (not (person (name ?n)))
   =>
   (retract ?f))

Or you can use the fact-set query functions to locate and change the person from the actions of the rule:
(defrule ModifyGender
   ?f <- (task type a)
   =>
   (retract ?f)
   (printout t "Enter the name of person that you want to modify" crlf)
   (bind ?n (read))
   (printout t " Enter new value" crlf)
   (bind ?V (read))
   (if (any-factp ((?p person)) (eq ?p:name ?n))
      then
      (do-for-fact ((?p person)) (eq ?p:name ?n)
         (modify ?p (gender ?V)))
      else
      (printout t "Person " ?n " does not exist." crlf)))


text:
Q: sed does not work with psexec and redirect when working on large file I want to call sed upon a large file data.csv on a remote server servername and redirect the output to data_mod.csv. data.csv itself is around 1 GB. Both the local and remote machine is running on Windows.
Below is the command I used:
psexec \\\\servername sed <somepattern> \\\\servername\\data.csv > \\\\servername\\data_mod.csv
However, it ended up with the result that \\\\servername\\data_mod.csv is created but empty.
To address the issue, I also tried to run sed <somepattern> \\\\servername\\data.csv > \\\\servername\\data_mod.csv directly on the remote server, which worked fine.
Ironically, when I replaced data.csv with a small file, e.g. head data.csv > small_data.csv, then the commandpsexec \\\\servername sed <somepattern> \\\\servername\\small_data.csv > \\\\servername\\data_mod.csv also worked fine.
I am wondering what will the potential problem be.


text:
Q: CakePHP3, when joining two tables (mysql): Column not found: 1054 Unknown column in 'field list' I'm new to programming on cakePHP. I need to join four tables, but I started by joining two of this four tables. When I try to join I get the error:
Column not found: 1054 Unknown column 's.state_code' in 'field list'
I have tried using the alias, as shown before. I also tried using the table name.
Among the possible solutions for this problem that I've read, I already tried most of them. For example, the cache is not the problem, I have already deleted those files after updating the model database and I keep getting the same error.
This is the code on the officesController, here's where I'm getting the error:
public function view(){
    $this->loadModel('States');

    $options['joins'] = array(
        array('table' => 'states',
            'alias' => 's',
            'type' => 'inner',
            'conditions' => array(
                'offices.state_code = s.state_code'
            )
        )
    );

    $options['fields'] = array('offices.state_code', 'offices.office_name', 's.state_name');
    $offices = $this->Offices->find('all', $options);
    $this->set('offices',$offices);

}

I also tried the following piece of code, the problem with this one is that it only retrieves data from Offices table, not from State:
    $this->loadModel('States');

    $offices = $this->Offices->find('all',
       array('joins' => array(
            array('table' => 'states',
                    'alias' => 's',
                    'type' => 'left',
                    'foreignKey' => true,
                    'conditions' => array(
                        'offices.state_code = s.state_code')
                )
            )
        )
    );
    $this->set('offices', $offices);

In addition, with the code above I tried the foreignkey with both false and true values, and the result its exactly the same.
Also, I'm not sure about how to select specific fields from both tables.
Any help would be very appreciated. Thanks.
SQL for offices table:
CREATE TABLE offices(
    office_id VARCHAR(10) NOT NULL,
    office_name VARCHAR(128),
    address VARCHAR(128),
    state_code VARCHAR (5),
    PRIMARY KEY(office_code),
    FOREIGN KEY(state_code) REFERENCES states(state_code)
);

SQL for states table:
CREATE TABLE states(
    state_code VARCHAR(5) NOT NULL,
    state_name VARCHAR(50),
    PRIMARY KEY (state_code)
);


text:
Q: Inner function does not assign value to element dynamically created by outer function in jQuery I am trying to create a search result dynamically added below the form through ajax call using parameter given in the form. I can add results using a table, but in these results I have client ids where I need Name, so I again use ajax call for each client id which return success but can not assign the values to corresponding table field. Below is my code, what is wrong here?
var stopMulti = 0;
$('#salesreport-end_date').change(function(){
    var endDate = $(this).val();
    var startDate = $('#salesreport-start_date').val();
    var param = startDate+'#'+endDate+'#date';
    if(stopMulti == 0){
        $.get('index.php?r=reports/sales-report/sales-report',{ id : param }, function(data){
            var sReport = JSON.parse(data);
            if(typeof sReport != 'undefined'){
                if(sReport.length != 0){
                    $('

Sales Report

').insertAfter('#sub-button-div');
                    $('

Invoice Number	Client Name	Company Name	Phone	Net Total	VAT	Total

').insertAfter('#sales-report-heading-1');
                    $('

').insertAfter('#sales-report-div-1');

                    var count = 0;
                    for(var i = 0; i < sReport.length; i++){
                        $('

').insertAfter('#sales-report-row-head');
                        $('#sales-report-col-1'+count).html(sReport[i].invoice_id);
                        $.get('index.php?r=reports/sales-report/get-client',{ id : sReport[i].client_id}, function(client){
                            var client = JSON.parse(client);
                            $('#sales-report-col-2'+count).text(client.client_name);
                            $('#sales-report-col-3'+count).text(client.company_name);
                            $('#sales-report-col-4'+count).text(client.telephon);
                        });
                        $('#sales-report-col-5'+count).html(sReport[i].sub_total);
                        $('#sales-report-col-6'+count).html(sReport[i].taxrate);
                        $('#sales-report-col-7'+count).html(sReport[i].invoice_total);
                        count++;
                    }
                }
            }
        });
    }
    stopMulti = 1;
});

That is I am getting blank fields for client name, company name and telephone.
Firebug does not find any error in the code.

A: The $.get callback function will be called asynchronously, and therefor any value like count will be changed before the .get returns.
A simple technique to overcome this is to use anonymous function, so your function should look like this:
for(var i = 0; i < sReport.length; i++)
{
    f = function(i,count)
    {
        ... rest of your code
    }
    f(i,count);
    count++;
}

Here is a general example: https://jsfiddle.net/BentalSW/auyLq7rp/

A: You can't use count inside the inner AJAX Callback because by the time those asynchronous calls complete count will equal sReport.length and the wrong divs will be updated.
Use a .forEach loop instead of the for loop:
sReport.forEach(function(report, count) {
    ...
});

This will give you a value of count that is correctly bound to the current iteration count.
NB: it shouldn't be necessary to call JSON.parse on data that's already in JSON format - jQuery will do that for you automatically.


text:
Q: how can I set (add) a label to a jenkins node from itself (powershell windows 2017) how can I set (add) a label to a jenkins node from itself (powershell windows 2017) ?
I have no access to jenkins admin mode from https GUI. (that should be the standard procedure to do so).
I have both :
access to the node I need to use as remote powershell console (administrator)
access to master jenkins ssh linux account (root)
here I would like to add another label to the client node from one of thoses CLI's.
Jenkins officials neither googling permit me to find a procedure to do so.
how can I do that ? (So I can build a script around that after to make it all).

A: As an alternative method, I had to change it in its own xml file
as
<label>label addmynewlabel</label>

then restarted jenkinsclient (useless ?)
& restart jenkins service  on jenkins main server


text:
Q: Is this statement quicker than the previous? I am running through some old code if I changed the logic of this CASE statement:
                CASE WHEN ClaimNo.ClaimNo IS NULL THEN '0'
                     WHEN ClaimNo.ClaimNo = 1 THEN '1'
                     WHEN ClaimNo.ClaimNo = 2 THEN '2'
                     WHEN ClaimNo.ClaimNo = 3 THEN '3'
                     WHEN ClaimNo.ClaimNo = 4 THEN '4'
                     ELSE '5+'
                END AS ClaimNo ,

If I changed it to:
                CASE WHEN ClaimNo.ClaimNo >= 5 THEN '5+'
                ELSE COALESCE(ClaimNo.ClaimNo,0) END 'ClaimNo' ,

Would the statement technically be quicker? Its obviously a lot shorter as a statement and appears that it wouldn't run as many statements to obtain the same result.

A: These are not the same!  The case expression returns one type and in this case you want the type to be a string (because '5+' is a string).  However, mixing strings and integers in the wheres will result in a type conversion error.
Which is faster depends on the distribution of the data.  If most of the data consists of 5 or more, then the second method would be faster . . . and work if written as:
(CASE WHEN ClaimNo.ClaimNo >= 5 THEN '5+'
      ELSE CAST(COALESCE(ClaimNo.ClaimNo, 0) as VARCHAR(255))
 END) as ClaimNo,

In fact, there is only one comparison, so from the perspective of doing the comparisons it will be faster.
The next question is whether the conversion from a number to a string is faster than the multiple comparisons with each value listed separately.  Let me be honest:  I do not know.  And I have been concerned about query performance for a long time.
Why don't I know?  Such micro-optimizations generally have basically no impact in the real world.  You should use the version of the logic that works; readability and maintainability are also important.  Of course performance is an issue, but the bit fiddling techniques that are important in other languages often have no place in SQL which is designed to handle much larger quantities of data, spread across multiple processors and disks.


text:
Q: Rails, can validate a user crating a record is admin, from the model? I am attempting to make a new record object invalid if the user_id of the object is associated with an account that is not admin.
In the model I'd like to make a validation checks if the object to be created user_id.admin == true.
Neither of these solutions work:
  validates :user_id, User.find(:user_id).admin?

  before_save :user_is_admin, User.find(self.user_id).admin?

So, my question is, how do I write a validation that looks up the user and checks if they are an admin, and throws an error if they are not?
P.S. I am already doing admin checking in the controller as a before_action, but I'd like to invalidate the object if a non admin user manages to create one somehow...and for testing purposes.
If this isn't a best practice I'd still like to know a bit more about creating validity checks in rails.

A: I generally wouldn't encourage doing this type of authorization at the model/database level. Rather I would suggest that you abstract your authorization code into it's own layer and handle this at the controller level, then rely on tests to verify that nobody can create an object except through the controller.
https://github.com/elabs/pundit is a great gem for integrating an authorization layer into your Rails application.
If you still did want to do this validation at the model level, you could do something like this:
validate :creator_is_admin

def creator_is_admin
    errors[:base] << I18n.t('object_class.activerecord.validations.admin_create_check_failure') unless User.find(user_id).try(:admin?)
end

A: I mostly validating before action goes to the Model, controller could be good for it.
  ###Post Model Sample

  validate :is_admin?
  def is_admin?
    unless User.find_by_id(user_id).admin
      errors.add(:not_admin, "The post not belongs to you || not admin :) ")
    end
  end


text:
Q: Creating new Cocoapod `Unable to find a specification` on pod install I've gone through the Cocoapod guide for making a new pod.
The repo exists here: https://github.com/kkendall33/QuickInstantiating.
The QuickInstantiation pod spec looks like this:

But when I go to a different project and add QuickInstantiating to the Podfile:

and run pod install. I get this:

I just tested pod install with a different pod and it worked fine. This leads me to believe I'm doing something wrong with mine.

A: The pod must be pushed before it can be referred to by version. For testing, you can use the same path syntax -

pod 'QuickInstantiating', :path => 'relative/path'

like you used at https://github.com/kkendall33/QuickInstantiating/blob/master/Example/Podfile#L4
Otherwise you can push the pod to a private Specs repo if you do want to test the git repo before pushing the pod to trunk. Instructions at https://guides.cocoapods.org/making/private-cocoapods.


text:
Q: Do CRYPT_GEN_RANDOM give really random number? Is there any chance that this query will give the same number? If yes then how to make it truly random?
select ABS(CAST(CRYPT_GEN_RANDOM(8) AS bigint))

A:
Is there any chance that this query will give same number?

Yes.  But you can always store values in a unique index, and fail or retry on a collision.  With 64bits of randomness you can generate a few million values with only a small probability of a collision.
See, eg

https://preshing.com/20110504/hash-collision-probabilities/


text:
Q: Making WP theme / plugin multii-lingual without plugins I am new to theme and plugin development and am stuck at the translation part. I read one place that if you are using __(), and e() throughout, you do not need a plugin like WPML. Is it correct? Is generation of the translation files (like .po files) for all the target languages a tough job to do? Will I have to manually copy paste stuff from google translator and paste it in these files? Please excuse my inexperience and thank you or the patience.

A:
I read one place that if you are using __(), and e() throughout,
you do not need a plugin like WPML.

This is not accurate. Those functions and WPML are for two different things.
With a WordPress site you have two kinds of text that might need to be translated:

*

*Content. That is any text entered into WordPress as content that is stored in the database. This includes the body of posts and pages, but also titles, widgets and menus etc.

*Template strings. This refers to pieces of text that are coded into templates and functions. For example, your theme might have a "Continue reading" button for each post in a loop. That label is one of these.

The translation functions, __(), _e() etc. are exclusively for dealing with #2, and they are required if you want to allow these strings to be translated. WIthout them these strings will always be the language they were originally written in.
You can either bundle these translations yourself, or just provide a .pot file so that users can create translations themselves. If your theme properly implements localization, and is distributed via the WordPress.org Theme Repository, then users can use https://translate.wordpress.org to create a translation in their language. An overview of localization in WordPress is provided here.
When it comes to #1, content, these functions are not required. Users can set their site to whatever language they like, and enter content in whatever language they like. The only exception is right-to-left languages. To support those a theme needs to provide styles for right-to-left languages. There is a code article on that here.
So what is WPML for? WPML provides tools that allow a site to have content in multiple languages. This is for situations where a site might need to offer content in two or more languages, and allow users to switch between them. WPML is not required to translate template strings, and it's not needed to enter content in any language the author chooses. It's solely for sites that need content in multiple languages.
Some multi-language plugins, like WPML, provide built in tools for translating template strings. These features mean users don't need to depend on the theme author providing a translation, or need to have knowledge of translation tools. However, for these features to work you need to use the translation functions.
To summarise:

*

*Proper use of the translation functions allows your theme's hard-coded strings to be translated.

*You do not need to provide the actual translations yourself. There are other tools users can use to do the translations themselves.

*Using the translation functions does not give you the features of WPML without a plugin.

*Users do not need WPML unless they are serving the same content in multiple languages.

*Always read the documentation. WordPress' documentation on localisation is here.


text:
Q: VB.Net Label visuals change from design to runtime I'm designing a little program in vb.net and have encountered some really strange behavior. I've got a clock that counts down when you click the button, so the text in the Label needs to be dynamically adjusted. The amount of time is based on some settings loaded in the game initialization so the label is updated with the appropriate start time when the form loads. However, as soon as I update the text in the label during runtime the spacing or sizing or something gets all messed up.
Design view
Runtime
There is nothing in the code that is changing the font. This is only happening with the 5:00 minute label, the two smaller ones work fine. I've compared every property of the working labels with the janky one and they are the exact same.
Thoughts?


text:
Q: Fstab permissions I created a partition called sdb1 in fat32 and created 3 folders within a main folder however I wanted the 3 folders to have different permissions.
I tried to make an ana folder with all permissions, the marco with permissions for the user and group to execute and the opencloud with permissions for everything but the group. However the end result was that all the folders had all permissions.
I dont understand what i am doing wrong.

A: First, you are using the FAT32 filesystem, which does not support Unix-style file ownerships and permissions. But because Unix-like operating systems assume that all files must have an owner, group and permissions, the vfat filesystem driver fakes it - by assigning all files and all directories in the filesystem the same permissions.
You can adjust the fake permissions created by the filesystem driver: by using the dmask mount option you can set the permissions for all directories on the filesystem, and with fmask for all regular files respectively. These options are specific to the vfat filesystem driver, and won't work with just any filesystem. The drivers for other filesystems that don't natively support Unix-style ownerships/permissions may have similar mount options, or some other ways to adapt the filesystem to Unix-like conventions.
If you need to be able to assign different permissions to different files and/or directories within a single filesystem, FAT32 (or any FAT subtype really) is a wrong filesystem type for that.
Second, you haven't really made three separate folders: you've actually mounted one filesystem (on partition /dev/sdb1) to three separate locations. So if you created a file to /data/ana, the same file would be immediately accessible at /data/marco and /data/opencloud too.
Mounting the same filesystem to multiple locations in a single system simultaneously used to be impossible until relatively recent times (roughly, about the same time the container technology was being developed; it might have been a side effect of that). As such, the vfat filesystem driver apparently cannot handle multiple mounts of the same filesystem with different permission options. It looks like /data/ana might be the most recent mount, so it looks like the most recent set of mount options for the filesystem takes effect on all mounts (think "views") of that filesystem.


text:
Q: Replacing $ifNull with $cond in MongoDB aggregation I am thinking of migrating my app from MongoDB 3.6 to AWS DocumentDB. I am checking to see if everything is supported and I found $ifNull (aggregation) in the code. DocumentDB does not support $ifNull.
For a sample set of documents:
[
  { "hostname": "foo", "name": "a", "is_valid": true },
  { "hostname": "foo", "name": "b", "is_valid": false },
  { "hostname": "foo", "name": "c" }
]

I want to group document by the hostname field and if the is_valid field does not exist, make it true. This is the current aggregation query:
{
  $group: {
    _id: "$hostname",
    boxes: {
      $push: {
        name: "$name",
        is_valid: { $ifNull: ["$is_valid", true]}
      }
    }
  }
}

It returns:
{
  "_id": "foo",
  "boxes": [
    { "name": "a", "is_valid": true },
    { "name": "b", "is_valid": false },
    { "name": "c", "is_valid": true }
  ]
}

This is what I have tried:
{
  $group: {
    _id: "$hostname",
    boxes: {
      $push: {
        name: "$name",
        is_valid: { $cond: [{$ne: ["$is_valid", null]}, "$is_valid", true]}
      }
    }
  }
}

But that returns:
{
  "_id": "foo",
  "boxes": [
    { "name": "a", "is_valid": true },
    { "name": "b", "is_valid": false },
    { "name": "c" }
  ]
}

How can I translate $ifNull into an equivalent $cond?

A: Support for $ifNull was added to Amazon DocumentDB in January 2021.

A: Changing $ne to $gt works.
{
  $group: {
    _id: "$hostname",
    boxes: {
      $push: {
        name: "$name",
        is_valid: { $cond: [{$gt: ["$is_valid", null]}, "$is_valid", true]}
      }
    }
  }
}

If someone knows why this works, I would feel better understanding it more.


text:
Q: two rows of figures within sidewaysfigure not properly aligned vertically I'm trying to create two panels of figures, with a title for each one. However, I just cannot simultaneously center the title of the bottom panel and align the bottom figures with the top figures. In this example, the figured are not aligned, but the text (b) is:
\begin{sidewaysfigure}
\centering
\caption{\large Distribution of the W statistic}\par\medskip
\label{w_c}
  \begin{center}{(a) Singh-Madalla with c=1.7 }\end{center}
  \includegraphics[width=0.23\textheight]{ge_0_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_0_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_1_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_2_fim2.pdf}\quad
  \begin{center}{(b) Singh-Madalla with c=1.2 }\end{center}%\newline
  \includegraphics[width=0.23\textheight]{ge_0_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_0_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_1_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_2_fim2.pdf}
\end{sidewaysfigure}

In this example, the 4 bottom figures allign with the 4 top ones, but the text is one centered:
\begin{sidewaysfigure}
\centering
    \caption{\large Distribution of the W statistic}\par\medskip
    \label{w_c}
  \begin{center}{(a) Singh-Madalla with c=1.7 }\end{center}
  \includegraphics[width=0.23\textheight]{ge_0_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_0_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_1_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_2_fim2.pdf}\quad
  {(b) Singh-Madalla with c=1.2 }\newline
  \includegraphics[width=0.23\textheight]{ge_0_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_0_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_1_fim2.pdf}\quad
  \includegraphics[width=0.23\textheight]{ge_2_fim2.pdf}
\end{sidewaysfigure}

How to get both parts?
Thanks!

A: Two comments/suggestions:

*

*Don't use \quad to separate the graphs; use \hfill instead. And, use only three \hfill instructions, not four.

*Don't engage in excessive amounts of visual formatting, e.g., when setting up the captions of the subfigures. Instead, use the subcaption package and its subfigure environment; it provides its own \caption statement, which will automatically be centered and be numbered (a), (b), etc.

\documentclass[demo]{article} % omit 'demo' option in real doc.
\usepackage{graphicx,rotating,subcaption}
\begin{document}
\begin{sidewaysfigure}
\caption{Distribution of the $W$ statistic} \label{w_c}
  \begin{subfigure}{\textwidth}
  \caption{Singh-Madalla with $c=1.7$} \label{w_c_1.7}
  \includegraphics[width=0.23\textwidth]{ge_0_fim2.pdf}\hfill
  \includegraphics[width=0.23\textwidth]{ge_0_fim2.pdf}\hfill
  \includegraphics[width=0.23\textwidth]{ge_1_fim2.pdf}\hfill
  \includegraphics[width=0.23\textwidth]{ge_2_fim2.pdf}
  \end{subfigure}

  \bigskip
  \begin{subfigure}{\textwidth}
  \caption{Singh-Madalla with $c=1.2$} \label{w_c_1.2}
  \includegraphics[width=0.23\textwidth]{ge_0_fim2.pdf}\hfill
  \includegraphics[width=0.23\textwidth]{ge_0_fim2.pdf}\hfill
  \includegraphics[width=0.23\textwidth]{ge_1_fim2.pdf}\hfill
  \includegraphics[width=0.23\textwidth]{ge_2_fim2.pdf}
  \end{subfigure}
\end{sidewaysfigure}
\end{document}


text:
Q: Dot notation - Does it take parameters? Is it correct if I say that
[anIstance aMethod];

is equivalent to
anIstance.aMethod; --?

If it is the case, what about methods which take one ore more parameters?
Does the following statement
[anIstance aMethod : aParameter];

have an equivalent dot notation?
I have tried with
anIstance.aMethod : aParameter;

anIstance.aMethod(aParameter);

And they don't seem to work (compile time errors)
If there is not a way to invoke a method with parameters in dot notation what about the synthesized setter methods (which, as far as I know, by definition take an argument)?
If I have a synthesized property, does the following statement
anIstance.aProperty = anotherObject;

invoke the relative setter method? Or does it call the getter method?

A: This is covered in Apple's "The Objective C Programming Language" guide:

@interface MyClass : NSObject
{
    float value;
}
@property float value;
@end

You can think of a property
  declaration as being equivalent to
  declaring two accessor methods. Thus
@property float value;

is equivalent to:
- (float)value;
- (void)setValue:(float)newValue;

A: The other answers convey the general idea, but I'd like to explicitly state that dot notation and properties are separate concepts. Dot notation is intended for setters (methods named setSomething: that take a single parameter) and getters, and can also be used for any method that takes no parameters (though it's very poor style to use it for an action like myObject.doSomething).
Properties are designed to declare getters and setters more easily, and even generate the code for you.
So the two concepts are related, but it's entirely possible (and not always poor style) to use dot notation with your very own getters and setters, that you wrote by hand. It's also entirely possible (and usually perfectly acceptable!) to use properties, even with getters and setters generated for you, with normal bracket syntax, and not dot notation.
But to address the original question, no, dot notation does not take parameters. It's specifically designed for use with methods that don't take parameters.

A: dot-notation is only valid for properties. Properties are declared with the @property declaration in Objective-C
like this:
interface MyClass {
   NSString * x;
}

@property (copy) NSString *x;

implementation:
@synthesize x;

// this will generate a setter and getter method:
// - (NSString *) x {}
// - (void) setX:(NSString *)value {}

then you can use:
MyClass *obj = [[MyClass alloc] init];

obj.x = @"test";

But this only works for properties. Not for methods.

A: Dot notation is just syntactic sugar for properties in Objective-C, you can't use it for general method calls.


text:
Q: No persistence provider found with JBoss AS 7 I've just migrated from Tomcat to JBoss AS 7.
So, I configured Mysql datasource in JBoss (adding module.xml with associated Jar, adding driver bloc into standalone.xml and configuring datasource through JBoss interface.
No errors when deploying but impossible to get an entityManager (JPA with Hibernate in background).
Indeed, when this code is executed:
Persistence.createEntityManagerFactory("RoomManagement");

I obtain this error :

javax.persistence.PersistenceException: No Persistence provider for
  EntityManager named RoomManagement
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:69)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)

Very strange because I well verified that my persistence.xml does take place into War at WEB-INF/classes/META-INF directory.
My persistence.xml looks like as follow :
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">

    <persistence-unit name="RoomManagement" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:jboss/datasources/MySqlDS</jta-data-source>
        <class>com.parisdescartes.roommanagement.domain.entities.Address</class>
        <class>com.parisdescartes.roommanagement.domain.entities.Building</class>
        <class>com.parisdescartes.roommanagement.domain.entities.Civility</class>
        <class>com.parisdescartes.roommanagement.domain.entities.EventType</class>
        <class>com.parisdescartes.roommanagement.domain.entities.Job</class>
        <class>com.parisdescartes.roommanagement.domain.entities.Reservation</class>
        <class>com.parisdescartes.roommanagement.domain.entities.Room</class>
        <class>com.parisdescartes.roommanagement.domain.entities.RoomType</class>
        <class>com.parisdescartes.roommanagement.domain.entities.Tool</class>
        <class>com.parisdescartes.roommanagement.domain.entities.User</class>
        <class>com.parisdescartes.roommanagement.domain.entities.UserDetail</class>
        <class>com.parisdescartes.roommanagement.domain.entities.Schedule</class>
        <properties>
            <property name="hibernate.connection.autocommit" value="true" />
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hbm2ddl.auto" value="update"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
        </properties>
    </persistence-unit>
</persistence>

Did I make a mistake or forgot to specify something ?

A: Remove the hibernate jar from WEB-INF/lib. JBoss has that bundled, so if you have it on the classpath it probably confuses the classloader.


text:
Q: Robbery database biggest difference query with sqlite I'm using sqlite.
Is it possible to get the information I need from my database with only one query? It works if I run 20 queries in a for loop (from 0 until 4000) , but it takes more than two hours to run :(
Can someone suggest a faster solution to get the same result?
I have a database (table robbery) that stores when and where a robbery happened. The robbery table has these attributes: date, city, id (PK). The date is the day when the robbery happened.
I can't attach the real database, I don't have access to it at the moment, but it looks like this one:

I'm trying to get this information:
The city with the biggest difference in the number of robberies for all months.
For example from the attached database:
the city with the biggest difference in the number of robberies would be Chicago, because in July 2017 there were 4 and in May 2017 there was 1 robbery. The difference is 3. In the other cities this difference is much lower (1 and 0).
I would like to get this result with a query:
Chicago

A: My test table:
CREATE TABLE tbl_robbery (
                id INTEGER PRIMARY KEY,
                city TEXT,
                robbert_date DATE
);

My test data:
INSERT INTO tbl_robbery VALUES (1,'Chicago','2017-07-01');
INSERT INTO tbl_robbery VALUES (2,'Chicago','2017-08-01');
INSERT INTO tbl_robbery VALUES (3,'Chicago','2017-08-02');
INSERT INTO tbl_robbery VALUES (4,'Chicago','2017-08-03');
INSERT INTO tbl_robbery VALUES (5,'NY','2017-07-01');
INSERT INTO tbl_robbery VALUES (6,'NY','2017-08-01');

The query:
SELECT out.city,
   (select count(r2.id) from tbl_robbery r2 WHERE out.city=r2.city GROUP BY r2.city, strftime('%Y-%m',r2.robbert_date) ORDER BY count(r2.id) DESC) as maxcrime,
   (select count(r2.id) from tbl_robbery r2 WHERE out.city=r2.city GROUP BY r2.city,strftime('%Y-%m',r2.robbert_date) ORDER BY count(r2.id) ASC) as mincrime,
   (select count(r2.id) from tbl_robbery r2 WHERE out.city=r2.city GROUP BY r2.city,strftime('%Y-%m',r2.robbert_date) ORDER BY count(r2.id) DESC)-(select count(r2.id) from tbl_robbery r2 WHERE out.city=r2.city GROUP BY r2.city,r2.robbert_date ORDER BY count(r2.id) ASC) as crime_diff
   FROM (select r.city FROM tbl_robbery r GROUP BY r.city) as out
   ORDER BY (maxcrime-mincrime) DESC
;

Query output:
city        maxcrime    mincrime    crime_diff
----------  ----------  ----------  ----------
Chicago     3           1           2
NY          1           1           0

A: (Using the same table schema and test data as Krzysztof's answer):
WITH total_robberies AS (SELECT city, count(robbert_date) AS robberies
                         FROM tbl_robbery
                         GROUP BY city, strftime('%Y-%m', robbert_date))
SELECT city, max(robberies) - min(robberies) AS variance
FROM total_robberies
GROUP BY city
ORDER BY variance DESC
LIMIT 1;

produces
city        variance
----------  ----------
Chicago     2

One huge thing: In your sample data, you have dates like "1/07/2017", but you'll notice that he turned them into "2017-07-01". Using ISO-8601 formats means your dates can be used with sqlite3 date and time functions. Leaving the dates the way they are now would make things a lot more complicated. Don't do that.
Edit: Also, adding an index on the city column of the table will help a lot.


text:
Q: AWS Batch job start too long with Min vCPUs=0 in Compute environment I`m using AWS Batch. After job submitting I wait 10-15 minutes until my job gets RUNNING status. My Compute environment configuration is next:
Provisioning model: EC2
Instance types: m4.xlarge
Min vCPUs: 0
Desired vCPUs: 0
Max vCPUs: 4
ECR image size ~130 MB.
I understand that problem in Min vCPUs = 0. It takes some time to start ECS instance. But why so long??
To speed up my jobs running I run dummy job which works long time for maintaining ECS instance in running state. After that, my jobs run quickly.

A: I think this is a little late but the following threads might help other people:
Here you can find an explanation regarding the time to begin execution of jobs and why batch doesn't schedule jobs as quickly as expected:
https://forums.aws.amazon.com/thread.jspa?messageID=897734

Here you can find a thread with the issues encountered by a user and some solutions that were proposed:
https://www.reddit.com/r/aws/comments/amg7yk/is_there_an_opensource_alternative_to_aws_batch/

Here you can find a proposed way to configure the vCPU values:
https://forums.aws.amazon.com/thread.jspa?threadID=265573


text:
Q: What level of indirection to use in structs? I want to create a simple structure that holds an identifier of type int and a value of any kind. Should I use
struct {
    int key;
    void *value;
}

or
struct {
    int key;
    void **value;
}

or something else?

A: I would use the first since a void* can point to anything. There doesn't appear to be any need for a double indirection in your case.
You should also keep in mind that there is another way, one that involves having a variable size payload within the structure rather than a fixed void*. It's useful in the case where the structures themselves are allocated (such as in a linked list) so you can make them variable sized by adjusting the argument to malloc.
In that case, you can avoid pointers in the structure altogether. See this answer for more details. I'm not suggesting that it's necessary (or even a good idea) for this particular case, just providing it as another possibility. I suspect your option 1 will be more than enough, or supplying a union within the structure if you don't want any pointer in there.

A: I think You have to use a combination of union and struct:
struct my_struct {
        int key;
        union {
                int a_int;
                float a_float;
                char a_char;
                /* Other types You may need */
        } value;
}

The pointer only points to a variable, it doesn't hold its value. You have to store actual variable somewhere else.


text:
Q: Loop through keypress Jquery (case : 1; etc..) I have a problem which is how to maintain/continue a loop if a key is pressed. I figured to animate the page with case 1 / case 2 / case 3 and case 4 but I would like to know how to continue the loop if the key is pressed again (and again...). I read about loop here but I just can't figure it out.
Thanks in advance, here is my code :
var counter = 0;

$(document).bind('keydown', function(e) {
    if(e.which == 37 || e.which == 39) {
        counter++;
        switch(counter) {
            case 1:
                $('#maikeximu,#dossier').stop()
                    .animate({
                        height: "toggle",
                    }, 1200, function() {
                        $('html,body').animate({
                            scrollTop: $("#maikeximu").next().offset().top
                        }, 1000);
                    });
                break;
            case 2:
                $("#gal,#dossier, #viz").stop()
                    .animate({
                        height: "toggle",
                    }, 1200, function() {
                        $('html,body').animate({
                            scrollTop: $("#gal").next().offset().top
                        }, 1000);

                    });
                break;
            case 3:
                $('#viz,#dossier').stop()
                    .animate({
                        height: "toggle",
                    }, 1200, function() {
                        $('html,body').animate({
                            scrollTop: $("#dossier").next().offset().top
                        }, 1000);
                    });
                break;
            case 4:
                $('#maikeximu, #gal,#dossier').stop()
                    .animate({
                        height: "toggle",
                    }, 1200, function() {
                        $('html,body').animate({
                            scrollTop: $("#maikeximu").offset().top
                        }, 0);
                    });
                break;
                counter = 0;
                return;
        }
    };

});

I hope to learn more about loops (a big problem for me) :)

A: The lines
            counter = 0;
            return;

are within the switch statement, but not within any particular case defined there, which means they're never getting executed. This prevents the counter from resetting, which is what's stopping the animation.
Place them before the break ending the fourth case, thus:
                /* now they're here */
                counter = 0;
                return;
            break;
            /* they were here */
    }

and you should see it work more like what you're expecting.


text:
Q: Django Saving form with two foreign keys I am attempting to save a form that submits data (project note comments) linked to another model (project notes) via foreign key (project notes). Project notes are linked via foreign key to another model (projects). I thought I would only need to consider the immediate relationship (project notes). However from the error I am getting, I also need to process the relationship from project notes to project.
The error:
IntegrityError at /projects/note/1/add_project_note_comment/
insert or update on table "company_project_projectnotes" violates foreign key constraint "company_project_proj_project_id_478f433c_fk_company_p"
DETAIL:  Key (project_id)=(0) is not present in table "company_project_project".

The models:
class Project(models.Model):
    title = models.CharField(max_length= 200)
    description = tinymce_models.HTMLField()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse ('project_detail', args=[str(self.id)])

class ProjectNotes(models.Model):
    title = models.CharField(max_length=200)
    body = tinymce_models.HTMLField()
    date = models.DateField(auto_now_add=True)
    project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes')

    def __str__(self):
        return self.title

class ProjectNoteComments(models.Model):
    body = tinymce_models.HTMLField()
    date = models.DateField(auto_now_add=True)
    projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='notes')

The view:
class ProjectNotesCommentCreateView(CreateView):
    model = ProjectNotes
    template_name = 'company_accounts/add_project_note_comment.html'
    fields = ['body']

    def form_valid(self, form):
        projectnote = get_object_or_404(ProjectNotes, id=self.kwargs.get('pk'))
        comment = form.save(commit=False)
        comment.projectnote = projectnote
        comment.save()
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('project_detail', args=[self.kwargs.get('pk')])

The URL pattern:
path('note/<int:pk>/add_project_note_comment/', ProjectNotesCommentCreateView.as_view(), name='add_project_note_comment'),

The template:
{% extends 'base.html' %}
{% load crispy_forms_tags %}

  {% block content %}

Add Comment

   <form action="" method="post">
    {% csrf_token %}
    {{ form.media }}
    {{ form|crispy }}
    <input type="submit" value="save">
   </form>

  {% endblock content %}

Any ideas on how to get this to work?

A: You won't have a relationship with pk field of the ProjectNoteComments with the ProjectNote model and the related names are same for both models, you might want to fix that.
Moreover, you are delaying commiting the form only for ProjectNote, but you also have to handle it for Project model too through backward referencing projectnote__project (related names may cause problem at this place.


text:
Q: Confusion about the use of colon
All the Leo Messi fans here in this sub: if he joined either City or Chelsea, would you then hate him?

IS the use of colon in the sentence above is correct? Actually I don't know the proper use of colon. While making the sentence above, it generally felt appropriate to me to use colon. And would somebody explain me the proper use of colon in any kind of sentences?

A: The use of the colon is correct.  It's acting as an introductory address similar to To Whom It May Concern:.

I'm guessing you want to write something on reddit. It's the only place I know where they talk about a sub (sub-reddit).  I would write it like this:

*

*To all the Leo Messi fans here in this sub: if he joined either City or Chelsea, would you then hate him?

Note the declaration "To all..."  Also, you would not use quotes because you're the one talking, and you don't quote yourself!
Assuming this is your purpose, slight changes in phrasing may be preferred to convey different meanings.  Let's say Leo Messi fans love good old Leo, and hate all the players on the other team.  And you want to point out the absurdity of hating someone just because they are on a team.  Then I would say,

*

*To all the Leo Messi fans here in this sub: would you suddenly hate him if he joined either City or Chelsea?

On the other hand, let's say he's thinking about moving, and you want to know if his fans will stop being his fans merely because he's playing for another rival team.  Then I would say,

*

*To all the Leo Messi fans here in this sub: are you going to hate him if he does join City or Chelsea?

A: It's correct. Two of the uses of colons are to describe a list or to introduce a quote or someone's statement as it is.
However, I'd add inverted commas to show that it is a statement or a direct speech.

(To) All the Leo Messi fans here in this sub: "If he joined either City or Chelsea, would you then hate him?"

Okay, and a list example -

The checklist for our picnic is: a torch, a tent, a bed, a cycle... and so on.


text:
Q: Unable to send email using sendgrid with Laravel 5.4 and found the error I am new to sendgrid, and want to integrate sendgrid with Laravel. Here I tried as
- Added below code in app\Mail\SendgridEmail.php
namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendgridEmail extends Mailable
{
use Queueable, SerializesModels;

public $data;

public function __construct($data)
{
    $this->data = $data;
}

public function build()
{
    $address = 'demotest@gmail.com';
    $subject = 'This is a demo!';
    $name = 'Sam';

    return $this->view('emails.templateUserRegister')
                ->from($address, $name)
                ->subject($subject)
                ->with([ 'message' => $this->data['message'] ]);

}
}

- Created template file views/emails/templateUserRegister.blade.php as
<!DOCTYPE html>

    <meta charset="utf-8">

Bowoot Email

{{ $message }}

- Added below code to controller
use App\Mail\SendgridEmail; // on top of class

public function sendemail()
{
    $data = array('message' => 'This is a SendgridEmail test!');

    Mail::to('user@gmail.com')->send(new SendgridEmail($data));
}

and when I run the code I found the error message as below

(2/2) ErrorException
  htmlspecialchars() expects parameter 1 to be string, object given (View: C:\xampp\htdocs\bowoot\resources\views\emails\templateUserRegister.blade.php)
  in helpers.php (line 547)

I am unable to understand what the issue is. Please help.

A: If the information provided is accurate, you are returning a view emails.templateUserRegister and it should be email.templateUserRegister. (Notice the s)
The reason I'm saying this is because this is your view path.

views/email/templateUserRegister.blade.php

And it definitely doesn't have an 's'.
Edit
Instead of doing this:
return $this->view('emails.templateUserRegister')
                ->from($address, $name)
                ->subject($subject)
                ->with([ 'message' => $this->data['message'] ]);

Try this:
$message = $this->data['message'];
return $this->view('emails.templateUserRegister')
                ->from($address, $name)
                ->subject($subject)
                ->with('message', $message);

And make $data in

app\Mail\SendgridEmail.php

private or protected.
If this doesn't work, try sending $data from controller as a string and not as an array. Remaining code will remain the same and this line would change:
->with([ 'message' => $this->data['message'] ]);

to:
->with('message', $this->data);

And you still need to change access of $data to private or protected.
EDIT 2
If you check Laravel's documentation for mail, it says this:

Note: A $message variable is always passed to e-mail views, and allows
  the inline embedding of attachments. So, it is best to avoid passing a
  message variable in your view payload.

So to fix the issue, just change $message to some other name like $data or $text. Change this:
->with([ 'message' => $this->data['message'] ]);

to this:
->with( 'text', $this->data['message'] );

I hope this fixes the issue.


text:
Q: Some devices don't work on 3.0 USB port? My laptop a HP DV6-1149wm has 2x 3.0 USB, and 2x 2.0 USB ports.
Some devices will work fine on both, like flash drives, but some other devices, like my iPod, and my Android phone will not work on my 3.0 ports.  They just don't show up at all, lsusb shows nothing, nor syslog.
Any idea why it is device-specific?  Or is there any way to force my 3.0 ports to act as 2.0 for the time being? I don't have any 3.0 devices.

A: You didn't say which version of Ubuntu you are using. USB 3.0 is problematic (buggy) in all versions prior to 12.04 in my personal experience.
Your best options may be to upgrade to 12.04 (or upgrade your kernel to at least 3.2).

A: Also, your drivers could not be fully functioning yet. There is a reason you're not supposed to use USB3 for important installs yet.


text:
Q: Is there an injective continuous map $\mathbb{R}^2 \rightarrow \mathbb{R}$? It is commonly known fact that there exists a continuous surjective map $\mathbb{R} \rightarrow \mathbb{R}^2$. So it bids to ask:
Is there an injective continuous map $\mathbb{R}^2 \rightarrow \mathbb{R}$?

A: No.  If so by connectivity the image would be an interval.  Removing any $3$ points in the image will disconnect it, however, removing the corresponding $3$ points in the domain will not disconnect $\mathbb{R}^2$.  Then we have a continuous map from a connected set onto a disconnected set.
This also shows there isn't a continuous finite to $1$ map from $\mathbb{R}^2$ to $\mathbb{R}$.  Actually it shows there isn't a continuous countable to $1$ map from $\mathbb{R}^n$ to $\mathbb{R}$ because $\mathbb{R}^n$ with a countable set removed is path connected.