text:
Q: coalesce of a query in postgres I have a query:
SELECT $ID_TABLE,
        TO_CHAR($DATE_COLUMN,'YYYYMMDD') ,
        '$UPPER_HOUR',
        COUNT(1)
FROM $TABLE_NAME
WHERE DATE_TRUNC('day',$DATE_COLUMN) = cast('$TODAY' as date)
        AND TO_CHAR($DATE_COLUMN,'HH24MI') BETWEEN '$LOWER_HOUR' AND '$UPPER_HOUR'
        GROUP BY TO_CHAR($DATE_COLUMN,'YYYYMMDD');

But in some cases the query has data in other cases is null.
Then if is null I need select other values, something like:
SELECT(coalesce(
SELECT $ID_TABLE,
        TO_CHAR($DATE_COLUMN,'YYYYMMDD') ,
        '$UPPER_HOUR',
        COUNT(1)
FROM $TABLE_NAME
WHERE DATE_TRUNC('day',$DATE_COLUMN) = cast('$TODAY' as date)
        AND TO_CHAR($DATE_COLUMN,'HH24MI') BETWEEN '$LOWER_HOUR' AND '$UPPER_HOUR'
        GROUP BY TO_CHAR($DATE_COLUMN,'YYYYMMDD')),select $ID_TABLE, $date, $PPER_HOUR, 0);"

Is possible do something like that.
This is for a process with a insertion with that select.
And if i don't have any row I need insert the values with constant date and the count(1)= 0.
The values with $ are constants
Thanks ;)

A: It is possible to use coalesce() in this way only when the query returns a single value.
You can use a plpgsql block and the FOUND variable, like in this pseudocode:
do $$
begin
    insert into my_table
    <a select query>;

    if not found then
        insert into my_table
        values(<some default values>);
    end if;
end $$;

A: Perhaps this is what you mean:
WITH t as (
      SELECT $ID_TABLE as col1, TO_CHAR($DATE_COLUMN, 'YYYYMMDD') as col2,
             '$UPPER_HOUR' as col3,
             COUNT(1) as col4
      FROM $TABLE_NAME
      WHERE DATE_TRUNC('day',$DATE_COLUMN) = cast('$TODAY' as date) AND
            TO_CHAR($DATE_COLUMN, 'HH24MI') BETWEEN '$LOWER_HOUR' AND '$UPPER_HOUR'
      GROUP BY TO_CHAR($DATE_COLUMN, 'YYYYMMDD'
     )
SELECT *
FROM T
UNION ALL
SELECT v.*
FROM (VALUES (?, ?, ?, ?)) v(col1, col2, col3, col4)
WHERE NOT EXISTS (SELECT 1 FROM t);


text:
Q: jquery validation max property reads only first digit? I have a form with input like:
<input name="students" id="students" type="number" max=13 required >

I do nothing special in the booting, just:
$('#mainForm').validate({
    submitHandler: function (form) {
        // doing things
    }
});

*

*Entering 2 triggers the "Please enter a value less than or equal to 13."-message.

*Entering 111 however is ok. So it is only validating the first character, as an integer?!

*14 is not ok! Now, it is checking also the second character!

Also tried
max="13"

with same results. I assume I miss something basic?
UPDATE JSFIDDLE:
http://jsfiddle.net/sw87W/630/

A: Updating from 1.11.0 to 1.11.1 solved my issue!
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facebook OAuth login bug I am trying to sign in Facebook with OAuth. I use following url:
https://www.facebook.com/dialog/oauth?client_id=233884670034708&redirect_uri=http%3A%2F%2Fapps.facebook.com%2Fdemoappfbm&scope=publish_stream&response_type=token
However, I always receive following error:
An error occurred. Please try again later.

What is possible reason?

A: Try putting your Canvas APP Url as redirect-uri, so the actual place your app is located, not on facebook.


text:
Q: determine swipe lenth to change page in viewpager I have a VerticalViewPager in my app that by default user must swipe a long amount finger on screen to change page.
I want to make the app like feedly.
How can i control and customize the amount of swiping to change page that if user swipe his or her finger for example 1cm or bring up the page 10% of screen height, page start changing with animation?


text:
Q: How to code for a UIButton in a Storyboard scene I don't know why but after searching on Google and here, no one seems to have this problem.
I have added a new storyboard scene right next to my main scene, and wrote a code for a button which will trigger a partial curl transition to the new scene.
On my new scene, are a controls, here's my problem. How can I code for them? I cannot add them as IBOutlet or IBAction to my main scene's view controller which is pretty obvious. So what should I do? How can I add a new ViewController.h/m file for that new scene?

A: To add this method to your ViewController.h/m, you will need to set the class of this view controller to "ViewController". To do this, selected the view, and select "Show the identity inspector" in inspector, and then type the view controller class (ViewController) in Class field.
If you want this view controller to be in a different class, create that class without an XIB file and type that class name in Class field.
This will allow you to declare the IBAction/IBOutlet to that button in the class you specify.


text:
Q: custom dojo stackController icons vs. theme buttons I tried using the iconClass: on the the contentpane but as expected it but the image on the background. Is there a way to break up the stackcontroller buttons to assign a custom button/img to each of them?

Dahsboard

A: you forgot a MINUS in "data dojo-props" within your ContentPane definition. It should be "data-dojo-props". Add it and the icon shows up !
Lucian


text:
Q: Facing challenge with selenium webdriver on Win 10 system
I am trying to automate login on a website using selenium. (Windows 10 64 bit os)
Using the below code I am able to open a link,
But once webpage loads the get cmd does not release my python interpreter
next cmd:
browser.find_element_by_class_name('gb_g').click()

does not run.
I tried to open google.com but the issue is same, I tried different browser it works but my project URL only works with internet explorer.
I have tried with both 64 & 32-bit driver version of internet explorer
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

link = 'https://www.google.com/'
browser = webdriver.Ie(executable_path='S:\work\Automation\Elog\IEDriverServer.exe')
browser.get(link)
browser.find_element_by_class_name('gb_g').click()

A: You need to consider a few things:

*

*If your use case is to use internet-explorer you need to use IEDriverServer.exe through selenium.webdriver.ie.webdriver.WebDriver() Class as follows:
webdriver.Ie(executable_path=r'S:\path\to\IEDriverServer.exe')

To click() on the element with text as Gmail you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following  Locator Strategies:

*

*Using LINK_TEXT:
from selenium import webdriver

browser = webdriver.Ie(executable_path=r'S:\work\Automation\Elog\IEDriverServer.exe')
browser.get("https://www.google.com/")
WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Gmail"))).click()

*Using CSS_SELECTOR:
from selenium import webdriver

browser = webdriver.Ie(executable_path=r'S:\work\Automation\Elog\IEDriverServer.exe')
browser.get("https://www.google.com/")
WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"a.gb_g[href*='com/mail/?tab']"))).click()

*Using XPATH:
from selenium import webdriver

browser = webdriver.Ie(executable_path=r'S:\work\Automation\Elog\IEDriverServer.exe')
browser.get("https://www.google.com/")
WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,"//a[text()='Gmail']"))).click()

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Update (from @rahuldesai's comment)
With the above mentioned configurations and using the 32 bit IEDriverServer binary some how the issue gets fixed.


text:
Q: Create session for java login REST service. I am trying to set up a session management over a simple login service I have written using JAX-RS. The code might not look good:
@Path("/login")
public class Login {

    @GET
    @Path("/{id}/{pass}")
    @Produces(MediaType.APPLICATION_JSON)
    public HashMap<String, Boolean> isUserValid(@PathParam("id") String id, @PathParam("pass") String pass) {

    // retrieve user map from database
    DatabaseController db = new DatabaseController();
    HashMap<String, Boolean> validation = new HashMap<String, Boolean>();
    validation.put("isValid", false);

    for (Map.Entry<String, String> user : db.user().entrySet()) {
        if ( id.equals(user.getKey()) && pass.equals(user.getValue())) {
            validation.put("isValid", true);
        }
    }
    return validation;
}

Does someone know how I can set up a session management on this service.

A: Rest web services are meant to be stateless , if you want statefull service use soap , there is a dirty hack around it but is not secure use a authentication token along with every request of rest and keep client states like browser , ip etc. in a database along with the token so that u know for a change in client or any attack.

A: By default every webservice should be stateless. It's not the best idea to use webservices in a session-based way. Sometimes there is a need for this but keep in mind that the key idea of webservices is the orchestration of services which contradicts with sessions. (See "Perspectives on Web Services" by Zimmermann).
If there is no other way to accomplish your target, see this.


text:
Q: How to generate sequence in postgresql when I execute following query.
select
     30,60,90,120,150,180
from
    table
I get output given below
But my desire output like, Want out in only one column.

 sequence
   30
   60
   90
   120
   150
   180

Is this possible?

A: Use UNION ALL that will work in all major RDBMSes
SELECT 30 "sequence" UNION ALL
SELECT 60 UNION ALL
SELECT 90 UNION ALL
SELECT 120 UNION ALL
SELECT 150 UNION ALL
SELECT 180

or use postgres' generate_series() function
SELECT *
  FROM generate_series(30, 180, 30) "sequence";

Output:

| SEQUENCE |
|----------|
|       30 |
|       60 |
|       90 |
|      120 |
|      150 |
|      180 |

Here is SQLFIddle demo for both queries

A: A bit shorter than using UNION ALL:
select *
from ( values (30), (60), (90), (120), (150), (180) ) as numbers (seq_no);

Alternatively:
with numbers (seq_num) as (
  values (30), (60), (90), (120), (150), (180)
)
select *
from numbers;

A: As @peterm said, the way to go in PostgreSQL would be to use generate_series().
In other RDBMS which support recursive cte, you can use it like this:
with recursive cte(sequence) as (
    select 30
    union all
    select sequence + 30
    from cte
    where sequence < 180
)
select *
from cte

Also, if your RDMBS supports window functions, and you have some table, and you know there're always exists at least 6 rows in this table, you can do this :)
select
    row_number() over(order by id) * 30
from temp
limit 6

sql fiddle demo

A: As other answers mention, generate_series is the way to go when the data you want to generate is a even spaced series like this. If not, I like the version by a_horse_with_no_name. Another way is:
select unnest('{30,60,90,120,150,180}'::int[]) as numbers


text:
Q: Oracle Tuning Inline View with group by I have an overly complex query that contains an inline view with a group by that I wish to try to remove for performance reasons, but I can't seem to think of a way to do so. An overly simplified representation of this query would be:
Select inline.totalValue, inline.type, everythingElse.*
From everythingElse,
(Select sum(value) totalValue, type, id
from otherTable
group by type, id) inline
Where everythingElse.id = inline.id

everythingElse only contains a small subset of the id's that are contained by inline, but it is a one to many relationship. Because inline contains a group by, the optimizer has to sum every row in the table before it can join. This makes it so this subquery represents 99% of the job's estimated cost.
Due to the fact that the select is using 2 values from inline, I don't think changing the subquery to a nested subquery, or a scalar subquery is an option. I have also considered moving the group by to encompass the entire query, but every aggregate function that I know of would cause everythingElse.* to take more time than I am saving by removing the inline view. The fastest processing one I could find was max(), but if something like any() exists, that might solve my problem.
Is there some sort of obvious solution to this that I am missing, or am I just going to have to deal with the fact that 1% of the query is getting 99% of the process time?

A: As long as you are using 12c or later, you could try using a cross apply. I'm not sure if it will improve your specific case or not, but it is worth a shot.
Select inline.totalValue, inline.type, everythingElse.*
From everythingElse
cross apply
(Select sum(value) totalValue, type, id
from otherTable
where everythingElse.id = otherTable.id
group by type, id) inline


text:
Q: How to make the viewable scope of a text-area cling to the right hand side of the text-area? I currently have a text-area with the following CSS class:
.text-area {
    background-color: black !important;
    color: white !important;
    padding: 0px;
    width: 100%;

    height: var(--display-font-size);
    font-size: var(--display-font-size);
    line-height: var(--display-font-size);

    overflow-x: hidden;
    white-space: nowrap;
    resize: none;
    border: none;
    text-align: right;
}

This produces a one line text-area that isn't resizable and has no user-interactive elements. The current output grows as follows as I type from a to z:
|.   abc|
|.  abcd|
|  abcde|
| abcdef|
|abcdef|
|abcdef|g

where |...| denotes the viewable region of the text area. However, I would like this viewable area to latch onto the right side of the text area so that I produce this effect:
|.   abc|
|.  abcd|
|  abcde|
| abcdef|
|abcdef|
a|bcdefg|

How might I accomplish this?
Edit:
I've been experimenting with the <input type="text"> HTML element, but it doesn't solve my problem. I'm not inputting text directly into the textbox; instead I generate a string and place it in the textbox using the value field, so while text may cling to the right side while I type it directly into the box, I can't reproduce this behaviour using my method.

A: Nevermind, I think I've figured out what you're trying to do based on the comments in your edit. You can set the scrollLeft property programmatically to keep the cursor right-aligned:

let val = 0;

function setText() {
  const input = document.querySelector('.text-area');
  input.value += " " + val++;
  input.scrollLeft = input.scrollWidth;
}
.text-area {
    background-color: black !important;
    color: white !important;
    padding: 0px;
    width: 100%;

    height: var(--display-font-size);
    font-size: var(--display-font-size);
    line-height: var(--display-font-size);

    overflow-x: hidden;
    white-space: nowrap;
    resize: none;
    border: none;
    text-align: right;
}
<textarea class="text-area"></textarea>
<button onclick="setText()">Update text</button>

Essentially borrowed from this thread which has some more suggestions.


text:
Q: How to render many images on a cube side and define their position like a gallery wall? I'm trying to build a gallery wall via three.js. So far I succeeded rendering an image on each side like this:

I've put paintings on left and right. However, I want to render more images on each wall rather than filling the entire wall with a single image. Something like this:

How can I set arbitrary positions?
Here's my code:
var scene = new THREE.Scene()
    var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1,1000)
    console.log(window.innerWidth, window.innerHeight)
    var renderer = new THREE.WebGLRenderer()
    renderer.setSize(   window.innerWidth,window.innerHeight)
    document.body.appendChild(renderer.domElement)
    //keep object in view when resize window
    window.addEventListener('resize',   () => {
        let width = window.innerWidth
        let height = window.innerHeight
        renderer.setSize(width, height)
        camera.aspect = width / height
        camera.updateProjectionMatrix()
    })
    controls = new THREE.OrbitControls(camera, renderer.domElement)
    controls.enableZoom = false
    controls.enableRotate = true
    controls.enablePan = false

    var geometry = new THREE.BoxGeometry( 2.5, 2, 4 )

    var cubeDice = [
        new THREE.MeshBasicMaterial({ color: 0x666666, side: THREE.DoubleSide }),
        new THREE.MeshBasicMaterial({ color: 0x666666, side: THREE.DoubleSide }),
        new THREE.MeshBasicMaterial({ color: 0x999999, side: THREE.DoubleSide }),
        new THREE.MeshBasicMaterial({ color: 0x999999, side: THREE.DoubleSide }),
        new THREE.MeshPhongMaterial({ map: new THREE.TextureLoader().load('img/h5_1993.132.jpg'), side: THREE.DoubleSide }),
        new THREE.MeshBasicMaterial({ map: new THREE.TextureLoader().load('img/unnamed.png'), side: THREE.DoubleSide }),
    ]

    // var material = new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true } )
    var material = new THREE.MeshFaceMaterial(cubeDice)
    var cube = new THREE.Mesh( geometry,material )
    scene.add( cube )

    // //set camera closer
    camera.position.z = 1
    var update = function(){
        cube.rotation.y += .005
    }
    var render = function(){ renderer.render(scene, camera) }
    var GameLoop = () => {
        requestAnimationFrame(GameLoop)
        update()
        render()
    }
    GameLoop()

A: MeshFaceMaterial does not do what you want. It makes each image fill up an entire face (an entire wall).
To make separate, movable images on the wall, it would be better to make an individual smaller mesh for each image, and then position them very close to the wall. That way the image can cover the entire mesh, but not cover the entire wall:


text:
Q: Points on a lemniscate
I have this lemniscate I plotted $r^2 = a^2 \cos 2\theta$ and that $a = 1$.
And I have these questions:
1) Are there values of $\theta$ that do not give any points on the curve? - My guess is a no since I know that the lemniscate rotates at $2\pi$.
2) Are there any values of θ that gives more than 2 points? - My guess is also no since every value $\theta$ gives a unique value.
Please correct me if I'm wrong. Thanks in advance!

A: You can only plot the lemniscate in the range
$$\theta \in \left[-\frac{\pi}{4},\frac{\pi}{4}\right]\cup \left[\frac{3\pi}{4},\frac{5\pi}{4}\right]$$.
For other values of $\theta$, you have that $\cos(2\theta)<0$, so you cannot compute $r^2$ in polar coordinates.
So the first question is true.
I don't understand the second question.


text:
Q: JSONP with Firefox 4 Not Working? We have been using JSONP (http://code.google.com/p/jquery-jsonp/) to do some localhost calls to retrieve JSON objects... I have upgraded to Firefox 4 today and now the code we were using doesn't work in Firefox 4, but it still works in IE, Chrome and Safari.
With the JSONP plugin it appends a script tag with a load of stuff in it... effectively it is like XSS... So I wondered if Firefox were trying to prevent this now.
Code:
    $.jsonp({
        url: "http://localhost:2020/wsService/LocalResources/All",
        callback: "callback",
        success: function(data) {
            // some success code
        },
        complete: function(xOptions, textStatus) {
            // this code doesn't alert in firefox 4
            alert("Complete");
        },
        error: function(xOptions, textStatus) {
            // error code
        }
    });

And then it appends this string
<script id="_jqjsp1" async="" src="http://localhost:2020/wsService/LocalResources/All?_1300967068015=">

Failed to load source for: http://localhost:2020/wsService/LocalResources/All?_1300967068015=

A: Use "window.alert" inside the function instead of "alert"... this did the trick in my case... Hope this helps...

A: I am also using jsonp in one of my projects and I tested it a few weeks back and it was not working. However I tested it again today and it seems to be working fine:

I tested this on Firefox 4.0, 4.0.1 on Windows and Linux with jQuery 3.1.2, 4.1.2 using jsonp: 2.1.2

Here is the code I used:
jQuery.jsonp({
   url: "http://api.twitter.com/1/statuses/user_timeline.json?include_rts=t&screen_name=twitter&rpp=20&callback=?",
   success: function(data) {
      alert("Success");
   },
   complete: function(xOptions, textStatus) {
       alert("complete");
   },
   error: function(xOptions, textStatus) {
       alert("Error");
   }
});

The only difference is that I am passing the callback at the end of the url as "callback=?" instead of defining it in the request options (not really sure if it matters).


text:
Q: $M$ is $k$ dimensional manifold connected, compact. Let $f:M \rightarrow \mathbb{R}$ smooth function. Prove there exists $x_0\in M$ that $f(x_0)=0$
Let $M$ a $k$ dimensional manifold, connected and compact. Let $f: M \rightarrow \mathbb{R}$ a smooth function. Suppose there exists $x_1,x_2\in M$ such that $f(x_1)<0<f(x_2)$. Prove there exists $x_0\in M$ such that $f(x_0)=0$.

I know that since $f$ is smooth, then if $M=\cup_{\alpha}r_{\alpha}(V_{\alpha})$ where $(r_{\alpha},V_{\alpha})$ is a collection of maps, then to any ${\alpha}$, $f\circ r_{\alpha}$ is smooth.
Also, if $x_1,x_2\in r_{{\alpha}_{i}}$ then because $f\circ r_{\alpha}$ is continuous we get what we need from the intermediate value theorem, but I'm not sure what to do if $x_1\in r_{{\alpha}_{i}}$ and $x_2\in r_{{\alpha}_{j}}$ where $i\neq j$.
Would appreciate your help:)

A: Take a path $\gamma:[0, 1] \to M$ from $x_1$ to $x_2,$ prove that your function is continuous on $\gamma.$

A: $M$ is path connected, so consider a path connecting $x_1$ and $x_2$. Apply IVT to the pullback of the function to the interval defining the path.

A: An alternative approach (which does not use IVT explicitly, although the method of proof here is the same as that used to prove IVT assuming the connectedness of the closed interval $\left[0,1\right]$ has been already established): If the conclusion is false, then prove that $M = f^{-1}\left(-\infty,0\right)\cup f^{-1}\left(0,\infty\right)$ is a separation of $M$ (i.e., an expression of $M$ as a union of two disjoint nonempty open subsets).


text:
Q: Why can't this tool find my database? Ok, I come from the Open Source world where the "configuration" does not seem anywhere near this bizarre. I've been given a "mdf" database file. I am working with Visual Studio 2013 and all I want to do right now is simply bring up the dadgum page in Page Inspector or in the browser -- which I was able to do when I was connected to a "real" database in the office. But now I'm remote and need to work with this "file". I have put it in the "data folder of my project; I have put it in a folder in My Documents path; I have put it in Program Files path for MS SQl Server. The next place I'm going to put it is in the garbage unless I can find out how this "project" in Visual Studio 2013 is looking for a database.
My "web.config" file has this:
    <add name="DefaultConnection" connectionString="Data Source=WS-xxxx;Initial Catalog=blahblahblah;MultipleActiveResultSets=True;Integrated Security=false;AttachDBFilename=|DataDirectory|blahblahblah.mdf;User Id=xxxxx;Password=yyyyy" providerName="System.Data.SqlClient" />

I've also tried:
    <add name="DefaultConnection" connectionString="Data Source=WS-xxxx;Initial Catalog=blahblahblah;MultipleActiveResultSets=True;Integrated Security=false;AttachDBFilename=[C:\Users\MyName\My Documents\Test Database\blahblahblah.mdf;User Id=xxxxx;Password=yyyyy" providerName="System.Data.SqlClient" />

...and this:
     <add name="DefaultConnection" connectionString="Data Source=WS-xxxx;Initial Catalog=blahblahblah;MultipleActiveResultSets=True;Integrated Security=false;User Id=xxxxx;Password=yyyyy" providerName="System.Data.SqlClient" />

Nothing else seems to make much sense. I'd appreciate any (valid) advice on why this is happening -- I was hoping to be coding in C# at this point, not fighting with MS Configuration stuff. As info, I CAN see the database in both Server Explorer and SQL Server Object Explorer in the VS Studio. I can also query it IN THE STUDIO and get valid results. And it's at the path that I specified in the "My Documents" folder. So it boggles my mind that I have put all these various paths in this web.config file and the Studio still says it can't find it when I bring up Page Inspector.
Thanks.
This is the error I keep getting, regardless of where I put this database:
The system cannot find the file specified
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified
Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

Stack Trace:

[Win32Exception (0x80004005): The system cannot find the file
  specified]
[SqlException (0x80131904): A network-related or instance-specific
  error occurred while establishing a connection to SQL Server. The
  server was not found or was not accessible. Verify that the instance
  name is correct and that SQL Server is configured to allow remote
  connections. (provider: Named Pipes Provider, error: 40 - Could not
  open a connection to SQL Server)]

A: If you can see the database in Server Explorer in VS 2013, I assume it is listed under "Data Connections". If so, right click on the database name in Data Connections, and go to Properties. One of the properties is "Connection String". Try that.
And be sure to not add square brackets around the file path as those aren't valid characters.
Your config tag should look something like:
<add name="DefaultConnection"
     connectionString="Data Source=WS-xxxx;Initial Catalog=blahblahblah;MultipleActiveResultSets=True;Integrated Security=false;AttachDBFilename=C:\Users\MyName\My Documents\Test Database\blahblahblah.mdf;User Id=xxxxx;Password=yyyyy"
     providerName="System.Data.SqlClient"
/>


text:
Q: Getting this error - 'tuple' object does not support item assignment Hello hope some one helps me on this challenge.
Getting this error - 'tuple' object does not support item assignment
I'm trying to get the posts of the users that I follow, in the models I used GenericForeignKey
the error is pointing at the first statement .  - ({% for post in posts_list %})
{% for post in posts_list %}
{{ post.title }}
{% endfor %}

views.py
class UserPostsBoardView(View):
    def get(self, request, *args, **kwargs):
        Context = {}
        # the users i'm following
        im_following = self.request.user.profile.following.all()

        query_set = Post.objects.filter(User__name__contains=im_following)

        Context["posts_list"] = query_set

        return render(request,"posts/user/user_board.html", Context)

posts/models.py
class Userposts(models.Model):
    name = models.CharField(max_length=10, default="User")
    val_obj = GenericRelation(Post, object_id_field="object_id",
                          related_query_name="User")

userprofiles/models.py
class Userprofiles(models.Model):
    user = models.OneToOneField(User, related_name="profile")
    following = models.ManyToManyField(User, blank=True, related_name="follow")

    def __str__(self):
        return str(self.following.all().count())

Traceback:
File "C:\Program
  Files\Python35\lib\site-packages\django\core\handlers\exception.py" in
  inner
    41.             response = get_response(request)
File "C:\Program
  Files\Python35\lib\site-packages\django\core\handlers\base.py" in
  _legacy_get_response
    249.             response = self._get_response(request)
File "C:\Program
  Files\Python35\lib\site-packages\django\core\handlers\base.py" in
  _get_response
    187.                 response = self.process_exception_by_middleware(e, request)
File "C:\Program
  Files\Python35\lib\site-packages\django\core\handlers\base.py" in
  _get_response
    185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Program
  Files\Python35\lib\site-packages\django\views\generic\base.py" in view
    68.             return self.dispatch(request, *args, **kwargs)
File "C:\Program
  Files\Python35\lib\site-packages\django\views\generic\base.py" in
  dispatch
    88.         return handler(request, *args, **kwargs)
File
  "C:\Users\wahab\Desktop\site1\ostra\ostrakodecommerce\posts\views.py"
  in get
    75.             return render(request,"posts/user/user_board.html", Context)
File "C:\Program Files\Python35\lib\site-packages\django\shortcuts.py"
  in render
    30.     content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\loader.py" in
  render_to_string
    68.     return template.render(context, request)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\backends\django.py"
  in render
    66.             return self.template.render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in render
    207.                     return self._render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in _render
    199.         return self.nodelist.render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in render
    990.                 bit = node.render_annotated(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in
  render_annotated
    957.             return self.render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\loader_tags.py" in
  render
    177.             return compiled_parent._render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in _render
    199.         return self.nodelist.render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in render
    990.                 bit = node.render_annotated(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in
  render_annotated
    957.             return self.render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\loader_tags.py" in
  render
    72.                 result = block.nodelist.render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in render
    990.                 bit = node.render_annotated(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in
  render_annotated
    957.             return self.render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\loader_tags.py" in
  render
    216.                 return template.render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in render
    209.                 return self._render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in _render
    199.         return self.nodelist.render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in render
    990.                 bit = node.render_annotated(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\base.py" in
  render_annotated
    957.             return self.render(context)
File "C:\Program
  Files\Python35\lib\site-packages\django\template\defaulttags.py" in
  render
    173.             len_values = len(values)
File "C:\Program
  Files\Python35\lib\site-packages\django\db\models\query.py" in len
    232.         self._fetch_all()
File "C:\Program
  Files\Python35\lib\site-packages\django\db\models\query.py" in
  _fetch_all
    1105.             self._result_cache = list(self._iterable_class(self))
File "C:\Program
  Files\Python35\lib\site-packages\django\db\models\query.py" in
  iter
    53.         results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
File "C:\Program
  Files\Python35\lib\site-packages\django\db\models\sql\compiler.py" in
  execute_sql
    863.             sql, params = self.as_sql()
File "C:\Program
  Files\Python35\lib\site-packages\django\db\models\sql\compiler.py" in
  as_sql
    420.             where, w_params = self.compile(self.where) if self.where is not None else ("", [])
File "C:\Program
  Files\Python35\lib\site-packages\django\db\models\sql\compiler.py" in
  compile
    373.             sql, params = node.as_sql(self, self.connection)
File "C:\Program
  Files\Python35\lib\site-packages\django\db\models\sql\where.py" in
  as_sql
    79.                 sql, params = compiler.compile(child)
File "C:\Program
  Files\Python35\lib\site-packages\django\db\models\sql\compiler.py" in
  compile
    373.             sql, params = node.as_sql(self, self.connection)
File "C:\Program
  Files\Python35\lib\site-packages\django\db\models\lookups.py" in
  as_sql
    170.         rhs_sql, rhs_params = self.process_rhs(compiler, connection)
File "C:\Program
  Files\Python35\lib\site-packages\django\db\models\lookups.py" in
  process_rhs
    433.             params[0] = "%%%s%%" % connection.ops.prep_for_like_query(params[0])
Exception Type: TypeError at /profile/-.1/public_board Exception
  Value: 'tuple' object does not support item assignment

A: Use __in instead of __contains.
im_following = self.request.user.profile.following.all().values_list('username', flat=True)
query_set = Post.objects.filter(User__name__in=im_following)


text:
Q: Insert PostgreSQL psycopg2 Спарсил некоторые данные, сейчас хочу вставить их в таблицу
def add_to_database(product):
    sql = "INSERT INTO parser_out(product_id, serial, code, name, article, label, release, format, package, count_disks," \
          " sounding, genres, weight, status, playlist, description, count_images, images, count_videos, videos) " \
          "VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
    for test in product:
        print(type(test), test)

    data = (product["product_id"],
            product["serial"],
            product["code"],
            product["name"],
            product["article"],
            product["label"],
            product["release"],
            product["format"],
            product["package"],
            product["count_disks"],
            product["sounding"],
            product["genres"],
            product["weight"],
            product["status"],
            product["playlist"],
            product["description"],
            product["count_images"],
            product["images"],
            product["count_videos"],
            product["videos"])
    print("Добавление записи", data)
    database_resuest(sql, data)

def database_resuest(sql_request, data):
    with closing(ps.connect(dbname=config["db_name"], user=config["db_user"], password=config["db_password"],
                            host=config["db_host"])) as conn:
        with conn.cursor() as cursor:
            if data is None:
                cursor.execute(sql_request)
            else:
                cursor.execute(sql_request, data)
                conn.commit()
            return cursor.fetchall()

Но у меня выкидывает ошибку:
Traceback (most recent call last):
  File "C:/Users/danil/PycharmProjects/untitled/parser.py", line 268, in <module>
    main_parse()
  File "C:/Users/danil/PycharmProjects/untitled/parser.py", line 237, in main_parse
    parse("https://collectomania.ru/product/samson-francois-debussy-childrens-corner-estampes-suite-bergamasque-pour-le-piano-lp", "test", "test", 12)
  File "C:/Users/danil/PycharmProjects/untitled/parser.py", line 186, in parse
    add_to_database(product)
  File "C:/Users/danil/PycharmProjects/untitled/parser.py", line 222, in add_to_database
    database_resuest(sql, data)
  File "C:/Users/danil/PycharmProjects/untitled/parser.py", line 44, in database_resuest
    cursor.execute(sql_request, data)
psycopg2.ProgrammingError: can't adapt type 'Tag'

Я проверил типы, но они все str
<class 'str'> name
<class 'str'> product_id
<class 'str'> serial
<class 'str'> code
<class 'str'> article
<class 'str'> label
<class 'str'> release
<class 'str'> format
<class 'str'> package
<class 'str'> count_disks
<class 'str'> sounding
<class 'str'> genres
<class 'str'> status
<class 'str'> weight
<class 'str'> playlist
<class 'str'> description
<class 'str'> count_images
<class 'str'> images
<class 'str'> count_videos
<class 'str'> videos

В чем еще может быть проблема?

A: Не знаю, почему так происходит, но помогло принудительное конвертирование для всех полей в
data = (
        str(product["product_id"]),
        str(product["serial"]),
        str(product["code"]),
        str(product["name"]),
        str(product["article"]),
        str(product["label"]),
        str(product["release"]),
        str(product["format"]),
        str(product["package"]),
        str(product["count_disks"]),
        str(product["sounding"]),
        str(product["genres"]),
        str(product["weight"]),
        str(product["status"]),
        str(product["playlist"]),
        str(product["description"]),
        str(product["count_images"]),
        str(product["images"]),
        str(product["count_videos"]),
        str(product["videos"])
    )
    print("Добавление записи", data)
    database_resuest(sql, data)

Происходит потому что psycopg2 конвертирует данные из типов питона в типы постгреса. Поддержиывает строки, числа, айпиадреса, ууиды. Но ваш парсер собирает данные из html и держит их в типе Tag о котором psycopg2 ничего не знает.
В вопросе возможно неправильно проверили типы.
Метод .get_text() или text в парсере должен извлекать текст из html. Возможно гдето contents вместо text, в который на каком-то из элементов попался вложенный tag.


text:
Q: Prevent Symfony 2.8 from generating Repository Alongside with Entity How to prevent the entity generator from generating the corresponding respository with an argument like --without-repository or in config.yml :
php app/console doctrine:generate:entity --entity=MyBundle:Article --format=annotation --fields="title:string(255) body:text" --no-interaction
In SF2.8, the repository is generated automatically.
Removing it manually is not envisageable for the requirement of my application.

A: In the generators Github Repository you can see, that generating a repository is not optional. It is generated by using the DoctrineEntityGenerator which uses the EntityRepositoryGenerator of doctrine.
It will be generated with this command.
If you don't want that, why not write your own generator. Feel free to do so.


text:
Q: Python multiprocessing gives slower speed as more cores are used I'm using Python Multiprocessing module to diagonalize a (large and sparse) matrix multiple times. I have to do this for a thousand times, so decided to do it in multiprocessing as I have 24 cores.
The code looks like:
import numpy as np
from scipy.sparse.linalg import eigsh
from scipy import sparse

def diag(param):
    wf, vf = 0, 0
    for i in range(10000):
        num = np.random.rand()
        .... # unrelated code producing the matrix with param and num

        Mat = sparse.csc_matrix((data, (row, col)), shape=(8000, 8000))
        w, v = eigsh(Mat, k=12)

        .... #some other unrelated process updating wf and vf using w and v

    return wf, vf

def Final(temp):
    print("Process " % multiprocessing.current_process().name)
    print(temp)
    np.random.seed()
    w0, v0 = diag(temp)

    .... #unrelated process using w0 and v0

if __name__ == '__main__':
    with Pool() as p:
        print(p.map(Final, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))

Other parts of the code are irrelevant, as diagonalising a 8000 by 8000 sparse matrix is the rate determining step in my case.
The process worked well when I did not use multiprocessing. However, the speed when I implement multiprocessing is now inversely proportional to the number of cores used(!!). I'll be grateful for any input on this, as I understand pool in general does make your process (a tiny bit) slower, but not by this much. I'm very confused as scipy inherently does not have multiprocessing implemented.
Example. Normally in one core, 10 diagonalizations take around 2s. In 24 cores (in the example above 10 cores!), it will take ~40s.
Edit: As a context, the matrix is very sparse - only 48000 entries in 8000 by 8000 matrix.

Edit: Solved, but still remaining questions.
I've solved the issue, and it is very interesting and I want your input.
The issue was as follows: When scipy.sparse diagonalises a matrix bigger than some threshold, then it automatically multithreads (which I checked with top.). However, this does NOT increase the speed significantly compared to using a single core case.
I checked the performance with my own laptop (dual core, nothing fancy!), and the performance was better(!) than the 24 core output (which has slightly bigger number of flops, but still.) and realised that the automatic multithreading is not doing anything, but just building up the queue and blocking multiprocessing.
Therefore, the solution was to set MKL and BLAS to single thread using os and then multithread - of which the programme runs very well now. I'm now curious, as why does BLAS multithread on the first place, but do not utilise the multithreads at all - it might be a developer issue, but there might be another convoluted solution. Who knows!

A: I solved similar issue by adding following lines
import os
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"


text:
Q: WSO2 API Manager (WSO2-AM) and Web services addressing (WS-A ) I've a SOAP web services hosted in a Weblogic Server that uses Web service addressing (WS-A). I'm trying to publish it using WSO2 API Manager.
The original request has a complete SOAP header including an Action and MessageID:
    <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
     <wsa:Action>urn:es:cetelem:ws:venta:promociones:services:promocionesService:promocionesService_v03:PromocionesServicePortType:obtenerPromocionesOperacionVndRequest</wsa:Action>
   <wsa:MessageID>uuid:969e636c-067f-4bed-a38a-65f0f81c295d</wsa:MessageID>
</soapenv:Header>

But the wso2-am removes the fields Action and MessageID from the SOAP Header before sending to the final endpoint in the Werblogic server. This is an example of the wrong hearder sent by wso2-am
<soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing"/>
How can I configure wso2-am to keep the SOAP Header sent by the client.

A: I found a solution. I added a new sequence mediation extension in [CARBON-HOME]/repository/deployment/server/synapse-configs/default/sequences to preserve original WS-A headers. The new extension set to true the PRESERVE_WS_ADDRESSING property.
Visit https://docs.wso2.com/display/ESB460/Generic+Properties .
The code of the new mediator is:
<sequence xmlns="http://ws.apache.org/ns/synapse" name="WSO2AM--Ext--In">
    <property name="PRESERVE_WS_ADDRESSING" value="true" scope="default" type="STRING"/>
</sequence>


text:
Q: Not getting the correct date from string in iOS I'm trying to get the date "30/06/2013" from the button:
I tried this code but I got in the log: 2013-01-04 22:00:00 +0000:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/YYYY"];

NSDate *date = [formatter dateFromString:dateBtn.titleLabel.text];
NSLog(@"date %@",date);

and in the app i got this date "05/01/2013":
I also tried this code but it didn't work:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"he_IL"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:@"dd/MM/YYYY"];
NSTimeInterval interval = 5 * 60 * 60;
NSDate *date1 = [dateFormat dateFromString:dateBtn.titleLabel.text];
date1 = [date1 dateByAddingTimeInterval:interval];

It is important to note I use locale Hebrew.

A: Have a look at Apple's official documentation on date formatters. Please note how the format differs slightly across different platforms and versions.
Also note the difference between yyyy and YYYY.

A: set date format to "dd/MM/yyyy"
    NSString *originalDate = @"30/06/2013";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd/MM/yyyy"];

    NSDate *date = [formatter dateFromString:originalDate];
    NSLog(@"date %@",date);

The explanation from @fzwo apple link
It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of "Week of Year"), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.


text:
Q: iOS Background Image doesn't display properly? I've literally piled through hundreds go searches on google :(. I can't seem to figure out what I'm doing wrong when I create an image in photoshop (960 x 600, -40 for the status bar). The image comes out to this:

When it should look like this:

(note this is not the actually size, crappy thumbnail version :P. The size is as stated above)
This is my code:
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"MenuBkground.png"]];

Am I doing something wrong when I make the image? Is it in the code? Any ideas?

A: You're using colorWithPatternImage which basically means what it says. The image will repeat itself if the space is not entirely consumed by the image. If you want to have a true background image you should create the image as a subview.
UIImage* image = [UIImage imageNamed:@"MenuBKground.png"];
UIImageView* background = [[UIImageView alloc]initWithImage: image];
[self.view addSubview: background];

A: Another way if your using interface builder,

*

*Drag an image view to your viewController.

*Assign that as MenuBkground.png in the inspector (first drop down box)


text:
Q: Помогите реализовать поиск по номеру без пробелов С бека приходят данные для поиска в которых есть номер паспорта содержащий в себе пробелы "#05 17 471424" и если вводить идентично с пробелами, то все находит, а если ввести без пробелов "#0517471424", то не находит, а нужно чтобы находил. Помогите)
PS:
Для поиска по паспорту используется символ "#" или "№"

$(function () {

    /**
     *
     * @param {Object} obj
     * @param {string} obj.selectorForFilter - Селектор по которому будет производится фильрация
     * @param {string} obj.inputSelector - Селектор инпута, в котором производится фильтрация
     * @param {string} obj.selectorForHide - Селектор в который обернуты элементы по которым производится фильтрация. Этот селектор будет скрываться, если не совпадает с введенным значением
     */
    function searchFilter(obj) {
        var items = document.querySelectorAll(obj.selectorForFilter),
            input = document.querySelector(obj.inputSelector);

        for (var i = 0; i < items.length; i++) {
            var item = items[i];

            if (item.innerHTML.toUpperCase().indexOf(input.value.trim().replace(/[#№]/g, ' ').toUpperCase()) > -1) {
                item.closest(obj.selectorForHide).style.display = "";
                item.closest(obj.selectorForHide).classList.add('active-search-item');

            }
            else {
                item.closest(obj.selectorForHide).style.display = "none";
                item.closest(obj.selectorForHide).classList.remove('active-search-item');
            }
        }
    }

    $(document).on('keyup', '.t-search', function (e) {
        e.preventDefault();

        if ($(this).val()[0] === "#" || $(this).val()[0] === "№") {
            searchFilter({
                selectorForFilter: '.search-select li .account-passport',
                inputSelector: '.t-search',
                selectorForHide: 'li'
            });
        } else if ($.isNumeric($(this).val()[0])) {
            searchFilter({
                selectorForFilter: '.search-select li .account-number',
                inputSelector: '.t-search',
                selectorForHide: 'li'
            });
        } else {
            searchFilter({
                selectorForFilter: '.search-select li .account-owner',
                inputSelector: '.t-search',
                selectorForHide: 'li'
            });
        }
        if (e.key === 'Enter' &&  $(this).siblings('.search-select')[0].querySelector('.active-search-item') !== null) {
            $(this).siblings('.search-select')[0].querySelector('.active-search-item').click();
        }

    });

});
<input type="text" placeholder="Текст" class="t-search mass-search">

                            358050001

ООО "Финанс Групп" (ИНН
                                        7745002141

),
                            рег.№3

                            358010001

Корнилов Роман Семенович (Паспорт гражданина РФ
                                        45 03 125345

),
                            рег.№4

                            358010002

Сиротин Павел Петрович (Паспорт гражданина РФ
                                        14 01 334355

), Зверева Мария Сергеевна (Паспорт гражданина РФ
                                        14 01 114355

),
                            рег.№5

                            358050002

Колчев Дмитрий Сергеевич (Паспорт гражданина РФ
                                        05 17 471424

),
                            рег.№6

                            358050002

ОАО "Алмаз" (ИНН
                                        7733223554

),
                            рег.№7

                            358050003

ФАУГИ (ИНН
                                        7700111111

),
                            рег.№8

A: Удалить пробелы из строки?
if (item.innerHTML.toUpperCase().replace(/\s+/g, '').indexOf(input.value.trim().replace(/[#№]/g, ' ').replace(/\s+/g, '').toUpperCase()) > -1) {...


text:
Q: Hammer.js scrolling activates drag right functionality I am working on my first touch project and I am using Backbone and RequireJS as the framework to the site. I am using Hammer.js as the touch library to allow me to drag open additional content.
The site has a grid layout with a simple 3 box pattern. The first box is the full width of the screen, and then the other two boxes sit directly below it at 50% of the width.
The problem I am running into is as I use my phone (iPhone 4S and Nexus 5) to scroll down to additional content (We use a lazy load to add to the grid layout) Hammer.js fires the drag right or drag left event.
I assume this is because my thumb veers off near the end of the scroll. Is there a way to prevent this functionality? Like if the drag right also has a drag up, it doesn't fire.
The code I am using is the following:
$('.tile').hammer().bind("dragright", function(event){
   event.gesture.preventDefault();
   console.log("The event type is: " + event.type)

   if ($(this).children('.desc').hasClass('active')) {
      $(this).children('.desc').removeClass('active');
   }
   else
   {
      $(this).children('.title').addClass('active');
   }
});

Any help with this would be wonderful. I have tried looking through Stack Overflow already but I don't think I am using the right terminology as I haven't had too much success finding the information I am looking for.
Thanks so much,
Andrew


text:
Q: navigation menu icon color and text is not getting changed in android In my cdoe in manin activity xml I am using "android.support.design.widget.BottomNavigationView" here I am displaying some menu icon in footer .On selection of each icon I am navigating to different screen .
Now I have to change the background of BottomNavigationView that I can do in activity_main xm , change background color , now I have to change the menu icon colot to white an text color should alos come in white . I chnged in menu navigation xml @drawable/icon_home , I changed color white but its not coming . Infact text below icon is also not coming in white . Please help . sugget me . Thank you
// XML code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.tecnotree.selfcare.ui.main.MainActivity">

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />

</LinearLayout>

// menu navigation code

<item
    android:id="@+id/navigation_home"
    android:icon="@drawable/icon_home"
    android:title="@string/title_home" />

<item
    android:id="@+id/navigation_services"
    android:icon="@drawable/icon_services"
    android:title="@string/service" />

<item
    android:id="@+id/navigation_cart"
    android:icon="@drawable/icon_cart"
    android:title="@string/shop" />

<item
    android:id="@+id/navigation_payments"
    android:icon="@drawable/icon_credit_card"
    android:title="@string/payments" />

<item
    android:id="@+id/navigation_more"
    android:icon="@drawable/icon_more"
    android:title="@string/more" />

/// Activity java code
public class MainActivity extends AppCompatActivity implements SelfCareManager.CustomerDetailsRequestCallback {

// this is a leftover from Farrukh's initial design. TBD whether this actually needed
//    @BindView(R.id.message)
//    TextView mTextMessage;

    @Inject
    ManagerFactory managerFactory;
    @Inject
    VolatileOps volatileOps;

    @BindView(R.id.navigation)
    BottomNavigationView navigationView;

    private Spinner spinner;
    private NavigationHelper navigationHelper;

    public  ProgressDialog loading;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.toolbar_dropdown, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        spinner = (Spinner) item.getActionView();

        SelfCareManager selfCareManager = managerFactory.getSelfCareManager();
        selfCareManager.getLoginCustomerDetails(
                volatileOps.getString(VolatileKey.LOGIN_NAME),
                volatileOps.getString(VolatileKey.SERVICE_NUMBER),
                true,
                this);
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        loading = ProgressDialog.show(MainActivity.this, "Fetching Data", " Please Wait...", false, false);
        super.onCreate(savedInstanceState);

        DaggerMainActivityComponent.builder()
                .appComponent(App.getInstance().getApplicationWideDeps())
                .build()
                .inject(this);

        navigationHelper = new NavigationHelper(getSupportFragmentManager());
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        navigationView.setOnNavigationItemSelectedListener(navigationHelper);
        navigationHelper.disableShiftMode(navigationView);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new TeaserFragment()).commit();
    }

    @Override
    public void onResume(){
        super.onResume();

        navigationHelper.reloadCurrentFragment();
    }

    @Override
    public void onCustomerDetailsReceived(Customer details) {

        loading.dismiss();

        List<String> serviceNumbers = new ArrayList<>();
        for(ServiceDetails serviceDetails: details.getServiceDetails()){
            serviceNumbers.add(serviceDetails.getServiceNumber());
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, serviceNumbers);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                volatileOps.setString(VolatileKey.SERVICE_NUMBER, (String) adapterView.getItemAtPosition(i));
                navigationHelper.reloadCurrentFragment();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    @Override
    public void onCustomerDetailsRequestError(String errorMessage) {
        loading.dismiss();
        Log.d("MainActivity", "Customer details request error: " + errorMessage);
    }

    public static class NavigationHelper implements BottomNavigationView.OnNavigationItemSelectedListener {

        private FragmentManager manager;

        private Fragment currentFragment;

        private HomeFragment homeFragment;
        private ServiceFragment serviceFragment;
        private ShopFragment shopFragment;
        private MoreFragment moreFragment;
        private PaymentsFragment paymentsFragment;

        @Inject
        ManagerFactory managerFactory;
        @Inject
        VolatileOps volatileOps;

        private HomeScreenContract.Presenter homePresenter;
        private ShopScreenContract.Presenter shopPresenter;
        private PaymentsScreenContract.Presenter paymentsPresenter;
        private ServiceScreenContract.Presenter servicePresenter;
        private MoreScreenContract.Presenter morePresenter;

        NavigationHelper(FragmentManager manager) {
            this.manager = manager;

            DaggerMainActivityComponent.builder()
                    .appComponent(App.getInstance().getApplicationWideDeps())
                    .build()
                    .inject(this);

            this.homeFragment = new HomeFragment();
            this.homePresenter = new HomeScreenPresenter(homeFragment, managerFactory, volatileOps);
            homeFragment.setPresenter(homePresenter);
            this.serviceFragment = new ServiceFragment();
            this.servicePresenter = new ServiceScreenPresenter(serviceFragment, managerFactory, volatileOps);
            serviceFragment.setPresenter(servicePresenter);
            this.shopFragment = new ShopFragment();
            this.shopPresenter = new ShopScreenPresenter(shopFragment, managerFactory, volatileOps);
            shopFragment.setPresenter(shopPresenter);
            this.moreFragment = new MoreFragment();
            this.morePresenter = new MoreScreenPresenter(moreFragment, managerFactory, volatileOps);
            moreFragment.setPresenter(morePresenter);
            this.paymentsFragment = new PaymentsFragment();
            this.paymentsPresenter = new PaymentsScreenPresenter(paymentsFragment, managerFactory, volatileOps);
            paymentsFragment.setPresenter(paymentsPresenter);
        }

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    manager.beginTransaction().replace(R.id.fragment_container, homeFragment).commit();
                    currentFragment = homeFragment;
                    return true;
                case R.id.navigation_services:
                    manager.beginTransaction().replace(R.id.fragment_container, serviceFragment).commit();
                    currentFragment = serviceFragment;
                    return true;
                case R.id.navigation_cart:
                    manager.beginTransaction().replace(R.id.fragment_container, shopFragment).commit();
                    currentFragment = shopFragment;
                    return true;
                case R.id.navigation_more:
                    manager.beginTransaction().replace(R.id.fragment_container, moreFragment).commit();
                    currentFragment = moreFragment;
                    return true;
                case R.id.navigation_payments:
                    manager.beginTransaction().replace(R.id.fragment_container, paymentsFragment).commit();
                    currentFragment = paymentsFragment;
                    return true;
            }
            return false;
        }

        public void reloadCurrentFragment(){
            if(currentFragment != null) {
                manager.beginTransaction().detach(currentFragment).attach(currentFragment).commit();
            }else {
               HomeFragment homeFragment = new HomeFragment();
               HomeScreenPresenter homePresenter = new HomeScreenPresenter(homeFragment, managerFactory, volatileOps);
                homeFragment.setPresenter(homePresenter);
                manager.beginTransaction().replace(R.id.fragment_container, homeFragment).commit();
                currentFragment = homeFragment;
            }
        }

        void disableShiftMode(BottomNavigationView view) {
            BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
            try {
                Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
                shiftingMode.setAccessible(true);
                shiftingMode.setBoolean(menuView, false);
                shiftingMode.setAccessible(false);
                for (int i = 0; i < menuView.getChildCount(); i++) {
                    BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
                    //noinspection RestrictedApi
                    item.setShiftingMode(false);
                    // set once again checked value, so view will be updated
                    //noinspection RestrictedApi
                    item.setChecked(item.getItemData().isChecked());
                }
            } catch (NoSuchFieldException e) {
                Log.e("NavigationHelper", "Unable to get shift mode field", e);
            } catch (IllegalAccessException e) {
                Log.e("NavigationHelper", "Unable to change value of shift mode", e);
            }
        }
    }

}

A: I think can help you for both case in case of checked or unchecked icon
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false">
        <bitmap android:src="@drawable/icon_home" android:tint="@color/white" />
    </item>
    <item android:state_checked="true">
        <bitmap android:src="@drawable/icon_home" android:tint="@color/grey" />
    </item>
    <item>
        <bitmap android:src="@drawable/icon_home" android:tint="@color/white" />
    </item>
</selector>


text:
Q: How do you allow user control over turtle and once hovering over desired spot to execute a specific function for those coordinates I am creating a custom car game for a school project and would like to know how to allow the user to navigate the turtle to the color they wish to use and then use that color after hitting enter. I am coding this using python turtle and am thinking I need to use the keyboard listen function but do not know how.
Here is what I have so far
# David, Wilson

# January 29th, 2021

# Custom Car Designer Game

import turtle

sc = turtle.Screen()

sc.setup(1400, 700)

graphic = turtle.Turtle()

# Turtle window title

usersName = turtle.textinput("Users Name", "Please enter your name to get started:")

turtle.title(" " + usersName + "'s Custom Car Simulator")

graphic.speed("fastest")

# The Sky

graphic.penup()

graphic.setpos(0, 200)

graphic.pendown()

graphic.color("SkyBlue")

graphic.begin_fill()

graphic.forward(700)

graphic.left(90)

graphic.forward(200)

graphic.left(90)

graphic.forward(1400)

graphic.left(90)

graphic.forward(200)

graphic.left(90)

graphic.forward(700)

graphic.end_fill()

# The Sun

graphic.color("yellow")

graphic.penup()

graphic.setpos(-640, 240)

graphic.pendown()

graphic.begin_fill()

graphic.circle(70)

graphic.end_fill()

# The Grass

graphic.color("LimeGreen")

graphic.penup()

graphic.setpos(0, 200)

graphic.pendown()

graphic.begin_fill()

graphic.forward(700)

graphic.right(90)

graphic.forward(250)

graphic.right(90)

graphic.forward(1400)

graphic.right(90)

graphic.forward(250)

graphic.right(90)

graphic.forward(700)

graphic.end_fill()

def drawGreen4Tree():

# tree stem

turtle.right(180)

turtle.speed(100)

turtle.pensize(20)

turtle.color("Brown")

turtle.right(180)

turtle.right(90)

turtle.forward(75)

# tree foliage

turtle.pensize(1)

turtle.left(90)

turtle.forward(10)

turtle.left(90)

turtle.forward(75)

turtle.left(90)

turtle.color("green4")

turtle.begin_fill()

turtle.forward(100)

turtle.right(150)

turtle.forward(100)

turtle.left(150)

turtle.forward(75)

turtle.right(150)

turtle.forward(75)

turtle.left(150)

turtle.forward(50)

turtle.right(150)

turtle.forward(50)

turtle.left(150)

turtle.forward(25)

turtle.right(150)

turtle.forward(50)

turtle.right(60)

turtle.forward(50)

turtle.right(150)

turtle.forward(25)

turtle.left(150)

turtle.forward(50)

turtle.right(150)

turtle.forward(50)

turtle.left(150)

turtle.forward(75)

turtle.right(150)

turtle.forward(75)

turtle.left(150)

turtle.forward(100)

turtle.right(150)

turtle.forward(100)

turtle.end_fill()

def drawChartReuseTree1():

# tree stem

turtle.right(180)

turtle.speed(100)

turtle.pensize(10)

turtle.color("Brown")

turtle.right(180)

turtle.right(90)

turtle.forward(37.5)

# tree foliage

turtle.pensize(1)

turtle.left(90)

turtle.forward(5)

turtle.left(90)

turtle.forward(37.5)

turtle.left(90)

turtle.color("chartreuse")

turtle.begin_fill()

turtle.forward(50)

turtle.right(150)

turtle.forward(50)

turtle.left(150)

turtle.forward(37.5)

turtle.right(150)

turtle.forward(37.5)

turtle.left(150)

turtle.forward(25)

turtle.right(150)

turtle.forward(25)

turtle.left(150)

turtle.forward(12.5)

turtle.right(150)

turtle.forward(25)

turtle.right(60)

turtle.forward(12.5)

turtle.right(150)

turtle.forward(12.5)

turtle.left(150)

turtle.forward(25)

turtle.right(150)

turtle.forward(25)

turtle.left(150)

turtle.forward(37.5)

turtle.right(150)

turtle.forward(37.5)

turtle.left(150)

turtle.forward(50)

turtle.right(150)

turtle.forward(50)

turtle.end_fill()

def drawDarkOliveTree2():

# tree stem

turtle.right(180)

turtle.speed(100)

turtle.pensize(10)

turtle.color("Brown")

turtle.right(180)

turtle.right(90)

turtle.forward(37.5)

# tree foliage

turtle.pensize(1)

turtle.left(90)

turtle.forward(5)

turtle.left(90)

turtle.forward(37.5)

turtle.left(90)

turtle.color("Dark Olive Green")

turtle.begin_fill()

turtle.forward(50)

turtle.right(150)

turtle.forward(50)

turtle.left(150)

turtle.forward(37.5)

turtle.right(150)

turtle.forward(37.5)

turtle.left(150)

turtle.forward(25)

turtle.right(150)

turtle.forward(25)

turtle.left(150)

turtle.forward(12.5)

turtle.right(150)

turtle.forward(25)

turtle.right(60)

turtle.forward(12.5)

turtle.right(150)

turtle.forward(12.5)

turtle.left(150)

turtle.forward(25)

turtle.right(150)

turtle.forward(25)

turtle.left(150)

turtle.forward(37.5)

turtle.right(150)

turtle.forward(37.5)

turtle.left(150)

turtle.forward(50)

turtle.right(150)

turtle.forward(50)

turtle.end_fill()

# The Road

graphic.penup()

graphic.setpos(0, -50)

graphic.pendown()

graphic.color("Black")

graphic.begin_fill()

graphic.forward(700)

graphic.right(90)

graphic.forward(200)

graphic.right(90)

graphic.forward(1400)

graphic.right(90)

graphic.forward(200)

graphic.right(90)

graphic.forward(700)

graphic.end_fill()

line1 = turtle.Turtle()

line2 = turtle.Turtle()

# White Lines

line1.penup()

line1.setpos(0, -150)

line1.pendown()

line1.pensize(10)

for i in range(10):

line1.color("white")

line1.forward(35)

line1.color("Black")

line1.forward(35)

line2.penup()

line2.setpos(0, -150)

line2.pendown()

line2.left(180)

line2.pensize(10)

for i in range(10):

line2.color("Black")

line2.forward(35)

line2.color("White")

line2.forward(35)

# The Shed

graphic.penup()

graphic.setpos(0, -50)

graphic.pendown()

graphic.color("Grey")

graphic.begin_fill()

graphic.forward(150)

graphic.right(180)

graphic.forward(300)

graphic.right(90)

graphic.forward(150)

graphic.right(90)

graphic.forward(300)

graphic.right(90)

graphic.forward(150)

graphic.end_fill()

# The Shed Roof

graphic.penup()

graphic.setpos(-150, 100)

graphic.pendown()

graphic.color("BurlyWood")

graphic.begin_fill()

graphic.left(120)

graphic.forward(125)

graphic.right(30)

graphic.forward(85)

graphic.right(30)

graphic.forward(125)

graphic.end_fill()

# The Sign on the Roof

graphic.penup()

graphic.setpos(-30, 135)

graphic.pendown()

graphic.color("Black")

graphic.write(" " + usersName + "'s ", font=("Times New Roman", 18, "normal"))

graphic.penup()

graphic.setpos(-60, 105)

graphic.pendown()

graphic.write("Kustom Kars", font=("Times New Roman", 18, "normal"))

# The flags on the building

graphic.penup()

graphic.setpos(-150, 100)

graphic.pendown()

graphic.color("red")

graphic.begin_fill()

graphic.right(270)

graphic.left(240)

graphic.forward(25)

graphic.left(120)

graphic.forward(25)

graphic.end_fill()

for i in range(3):

graphic.color("White")

graphic.begin_fill()

graphic.left(240)

graphic.forward(25)

graphic.left(120)

graphic.forward(25)

graphic.end_fill()

graphic.color("blue")

graphic.begin_fill()

graphic.left(240)

graphic.forward(25)

graphic.left(120)

graphic.forward(25)

graphic.end_fill()

graphic.color("red")

graphic.begin_fill()

graphic.left(240)

graphic.forward(25)

graphic.left(120)

graphic.forward(25)

graphic.end_fill()

graphic.color("White")

graphic.begin_fill()

graphic.left(240)

graphic.forward(25)

graphic.left(120)

graphic.forward(25)

graphic.end_fill()

graphic.color("blue")

graphic.begin_fill()

graphic.left(240)

graphic.forward(25)

graphic.left(120)

graphic.forward(25)

graphic.end_fill()

# The Garage Door

graphic.color("Gainsboro")

graphic.penup()

graphic.setpos(-140, -50)

graphic.pendown()

graphic.begin_fill()

graphic.left(30)

graphic.forward(125)

graphic.right(90)

graphic.forward(200)

graphic.right(90)

graphic.forward(125)

graphic.end_fill()

# The Windows on the Garage Door

graphic.color("SlateGray")

graphic.penup()

graphic.setpos(-130, 50)

graphic.pendown()

graphic.begin_fill()

graphic.forward(20)

graphic.left(90)

graphic.forward(30)

graphic.left(90)

graphic.forward(20)

graphic.left(90)

graphic.forward(30)

graphic.end_fill()

graphic.penup()

graphic.setpos(-85, 50)

graphic.pendown()

graphic.begin_fill()

graphic.left(90)

graphic.forward(20)

graphic.left(90)

graphic.forward(30)

graphic.left(90)

graphic.forward(20)

graphic.left(90)

graphic.forward(30)

graphic.end_fill()

graphic.penup()

graphic.setpos(-40, 50)

graphic.pendown()

graphic.begin_fill()

graphic.left(90)

graphic.forward(20)

graphic.left(90)

graphic.forward(30)

graphic.left(90)

graphic.forward(20)

graphic.left(90)

graphic.forward(30)

graphic.end_fill()

graphic.penup()

graphic.setpos(5, 50)

graphic.pendown()

graphic.begin_fill()

graphic.left(90)

graphic.forward(20)

graphic.left(90)

graphic.forward(30)

graphic.left(90)

graphic.forward(20)

graphic.left(90)

graphic.forward(30)

graphic.end_fill()

# The other garage door

graphic.penup()

graphic.setpos(85, -50)

graphic.pendown()

graphic.color("Gainsboro")

graphic.begin_fill()

graphic.right(90)

graphic.forward(100)

graphic.right(90)

graphic.forward(45)

graphic.right(90)

graphic.forward(100)

graphic.end_fill()

# The door knob

graphic.penup()

graphic.setpos(115, -10)

graphic.pendown()

graphic.color("SlateGray")

graphic.begin_fill()

graphic.circle(5)

graphic.end_fill()

graphic.pendown()

# The Checkered Flag

graphic.penup()

graphic.setpos(-415, -50)

graphic.pendown()

graphic.color("grey")

graphic.pensize(10)

graphic.right(180)

graphic.forward(125)

graphic.pensize(1)

graphic.right(90)

print(graphic.pos())

for i in range(5):

graphic.color("white")

graphic.begin_fill()

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.end_fill()

graphic.color("Black")

graphic.begin_fill()

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.end_fill()

graphic.penup()

graphic.setpos(-415, 65)

graphic.pendown()

for i in range(5):

graphic.color("Black")

graphic.begin_fill()

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.end_fill()

graphic.color("White")

graphic.begin_fill()

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.end_fill()

graphic.penup()

graphic.setpos(-415, 55)

graphic.pendown()

for i in range(5):

graphic.color("White")

graphic.begin_fill()

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.end_fill()

graphic.color("Black")

graphic.begin_fill()

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.end_fill()

graphic.penup()

graphic.setpos(-415, 45)

graphic.pendown()

for i in range(5):

graphic.color("Black")

graphic.begin_fill()

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.end_fill()

graphic.color("White")

graphic.begin_fill()

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.end_fill()

graphic.penup()

graphic.setpos(-415, 35)

graphic.pendown()

for i in range(5):

graphic.color("White")

graphic.begin_fill()

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.end_fill()

graphic.color("Black")

graphic.begin_fill()

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.left(90)

graphic.forward(10)

graphic.end_fill()

turtle.textinput("Welcome", "Greetings " + usersName + " and welcome to your very own custom car simulator in this "

"program you will be able to design your own car. Including "

"tire sizes and custom colors of your pick for the whole car. "

"Are you ready to get started? Please hit enter to continue.")

turtleMechanic = turtle.Turtle()

turtleMechanic.penup()

turtleMechanic.setpos(300, 150)

turtleMechanic.pendown()

turtleMechanic.right(90)

turtleMechanic.shape("turtle")

turtleMechanic.shapesize(5)

turtleMechanic.color("SeaGreen")

turtle.textinput("Turtle", "Hello if you notice the giant turtle on your screen I will be the one to help you design "

"your car. Well, actually the smaller version of me will be helping you. Please hit enter "

"to continue.")

def drawCar(c):

graphic.shape("turtle")

graphic.width(6)

graphic.speed(1)

graphic.penup()

graphic.setpos(-175.00, -175.00)

graphic.pendown()

graphic.color("Black")

graphic.forward(26)

graphic.color("White")

graphic.forward(100)

graphic.color("black")

graphic.forward(52)

graphic.color("White")

graphic.forward(25)

graphic.left(90)

graphic.forward(50)

graphic.left(90)

graphic.forward(50)

graphic.right(60)

graphic.forward(50)

graphic.left(60)

graphic.forward(100)

graphic.left(60)

graphic.forward(50)

graphic.left(120)

graphic.forward(75)

graphic.left(90)

graphic.forward(44)

graphic.backward(44)

graphic.right(90)

graphic.forward(75)

graphic.backward(200)

graphic.right(90)

graphic.forward(50)

graphic.left(90)

graphic.forward(15)

graphic.penup()

graphic.setpos(-175, -200)

graphic.pendown()

graphic.color("white")

graphic.begin_fill()

graphic.circle(25)

graphic.end_fill()

graphic.penup()

graphic.setpos(-25, -200)

graphic.pendown()

graphic.color("white")

graphic.begin_fill()

graphic.circle(25)

graphic.end_fill()

graphic.penup()

graphic.setpos(-175, -175)

graphic.pendown()

graphic.color("white")

graphic.forward(25)

for i in range(10): # to draw lines in circle

graphic.color("black")

graphic.penup()

graphic.goto(-25, -175)

graphic.pendown()

graphic.left(36)

graphic.forward(25)

graphic.backward(25)

for i in range(10): # to draw lines in circle

graphic.color("Black")

graphic.penup()

graphic.goto(-175, -175)

graphic.pendown()

graphic.left(36)

graphic.forward(25)

graphic.backward(25)

drawCar(graphic)

graphic.penup()

graphic.setpos(-600, -350)

graphic.penup()

graphic.color("Blue")

graphic.begin_fill()

graphic.circle(50)

graphic.end_fill()

graphic.penup()

graphic.setpos(-400, -350)

graphic.penup()

graphic.color("Red")

graphic.begin_fill()

graphic.circle(50)

graphic.end_fill()

graphic.penup()

graphic.setpos(-200, -350)

graphic.penup()

graphic.color("Yellow")

graphic.begin_fill()

graphic.circle(50)

graphic.end_fill()

graphic.penup()

graphic.setpos(0, -350)

graphic.penup()

graphic.color("Orange")

graphic.begin_fill()

graphic.circle(50)

graphic.end_fill()

graphic.penup()

graphic.setpos(200, -350)

graphic.penup()

graphic.color("Green")

graphic.begin_fill()

graphic.circle(50)

graphic.end_fill()

graphic.penup()

graphic.setpos(400, -350)

graphic.penup()

graphic.color("Navajo White")

graphic.begin_fill()

graphic.circle(50)

graphic.end_fill()

graphic.penup()

graphic.setpos(600, -350)

graphic.penup()

graphic.color("Magenta")

graphic.begin_fill()

graphic.circle(50)

graphic.end_fill()

turtle.done()


text:
Q: Make two columns on one column(python) date = '2021.02.01.2021.02.07.'
I want to divide the date into startdate and enddate like this:
startdate = 2021.02.01 enddate = 2021.02.07
How to do it??(python)

A: As the date is a string in your question you just need to split the string
date = '2021.02.01.2021.02.07.'
startdate = date[:10]
enddate = date[10:-1]

A fancier solution is to split the string with date.split('.') and get each field, and then built start and end dates


text:
Q: Setup Big Query table with UUID column? Between the "BigQuery default column value" and "Create UUID columns in BigQuery" posts, it looks like BQ recently started supporting the concept of a UUID, but is there a pattern for generating UUID (similar to a postgres/SQL trigger) values for each record upon insertion into the BQ table?
As an aside, I'm not seeing a way to automatically generate timestamp values for created_date_time and modified_date_time (typically another trigger) fields-- should I just focus on generating these values (UUIDs and timestamps) in the logic making the insertion request?

A: BigQuery supports neither default values nor triggers.  So, you have to assign these values explicitly when rows are inserted:
create table `test` (
    id string,
    x int64,
    created_at timestamp
);

INSERT INTO `test` (id, x, created_at)
    values (generate_uuid(), 1, current_timestamp);

I imagine that Google will add default values in the not-to-distant future.


text:
Q: Finitely-presented torsionfree group whose abelianization has torsion In chat someone asked

Does anyone know of a torsion-free group (finitely presentable) whose abelianisation has torsion?

A: $G=\pi_1(K)=\langle a,b\ |\ aba^{-1}=b^{-1}\rangle$ where $K$ is the Klein bottle is in fact left-orderable, which is quite a bit stronger than torsion-free (this is in fact true of any non-trivial fundamental group of a surface besides $\Bbb R \Bbb P^2$). To see this consider $G$ as the group of isometries of the plane generated by $a(x,y)=(1+x,-y)$ and $b(x,y)=(x,1+y)$. Now for $g \in G$, say $g>e$ if for $g(0,0)=(x,y)$ either $x>0$ or $x=0$ and $y>0$. It is quite easy to see that this is a left-order on $G$. As $H_1(K,\Bbb Z)=\Bbb Z \oplus \Bbb Z_2$, its abelianization has torsion.
This proof is ripped from Rolfsen's talk here.

A: Denote by $H_3(\mathbb{Z})$ the integral Heisenberg group of unitriangular matrices $\mathbb{Z}$-entries. It has
$$x=\begin{pmatrix} 1 & 1 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1\end{pmatrix}, \quad y=\begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 1 \\ 0 & 0 & 1 \end{pmatrix}, \quad z=\begin{pmatrix} 1 & 0 & 1 \\ 0 & 1 & 0 \\ 0 & 0 & 1\end{pmatrix} $$
in which $z$ commutes with $x$ and $y$, and $[x,y]=z$. In fact,
$$H_3(\mathbb{Z})=\langle x,y,z \mid [x,y]=z, [z,x],[y,x]\rangle $$
is a presentation for it. Verifying that $x,y,z$ generate $H_3(\mathbb{Z})$ and that they satisfy those relations should not be so hard, but I don't know a proof of why all relations come from those three. And yet it seems to be a well-known fact. The abelianization $H_3(\mathbb{Z})^\mathrm{ab}$ may be found by assuming $x,y,z$ commute and reconsidering the presentation: its generated by $x,y,z$ with single relation $z$. This is $\mathbb{Z}^2$.
Then consider $G=\big(H_3(\mathbb{Z})\times\mathbb{Z}\big)/\langle (z,-n)\rangle$. Writing $\mathbb{Z}=\langle w\rangle$, we can say that
$$G=\left\langle w,x,y,z ~\left| ~\begin{array}{c} [x,y]=z=w^n \\ [z,x],[z,y], \\ [w,x],[w,y],[w,z]\end{array}~~ \right. \right\rangle.$$
Evidently it has finite presentation. Suppose an element of $G$ were torsion. Its matrix part must have $0$ in its mid-upper and mid-right entries, so it is in $\langle \overline{z},\overline{w}\rangle\cong\mathbb{Z}^2/\langle(1,-n)\rangle$. If $\ell(a,b)=k(1,-n)$ for some $(a,b)\in\mathbb{Z}^2$ and nonzero $\ell,k\in\mathbb{Z}$ then $a=\frac{k}{\ell}$ is an integer so $(a,b)=\frac{k}{\ell}(1,-n)$. So $G$ is torsionfree.
The abelianization of $G$ is generated by $w,x,y,z$ with relations $z,w^n$, so $G^\mathrm{ab}\cong\mathbb{Z}^2\times\mathbb{Z}/n\mathbb{Z}$.


text:
Q: Converting from a Window based application to a view based application in Ipad I would like to know if it is possible for me to convert from a window based application to a view based appln... The reason is because I had already developed a part of my app but am getting some orientation issues which I was told would be solved only by using a view based application.
I was unable to find online any documentation regarding this..
It would be be great if anyone could help me out in this...

A: "Window based application" and "view based application" are just two of the templates you can use to start a project, anything you can actually do with one you can do with the other.
In the version of XCode I have handy here, the only difference between the two is that "view based" gives you an empty view controller and hooks it up to be displayed on app startup.

A: add a view controller subclass to your project, and then create an instance and add its view as the subview of your UIWindow in application:didFinishLaunchingWithOptions:, you've basically done it- anomie
  it's the best and easiest thing you can do as of now


text:
Q: Devops Azure not enough permission for hooks (for collaborator) I have a private repository. I added my friend as collaborator. Then I also made Devops Azure and added/installed Azure pipeline on GitHub.
Now, when my friend logs in on his Devops account, he wants to make a pipeline for the project I added him as a collaborator via GitHub. Good thing is he can see the repository from drop down list. When he chooses that and clicks review and run, Here is what the error states:

Unable to configure a service on the selected GitHub repository. This
  is likely caused by not having the necessary permission to manage
  hooks for the selected repository

Any idea how I can fix it? or how I give him the enough permission for that?

A: According to your description, I reproduced your problem.

The cause of this problem is because your repository is private. If it is a personal repository, only the repository owner can create hooks. You can refer to this case with similar issue.
If you use the classic editor to create a pipeline, you only need to be authorized with a GitHub personal access token.

A: If it is a personal repository, only the repository owner can create hooks. If it is an organization repository, you need at least "Admin permissions" which can "Change a repository's settings" with "Adding, removing, and editing webhooks and service hooks permission included. Refer to this link for details: https://help.github.com/articles/repository-permission-levels-for-an-organization/#changing-repository-settings


text:
Q: android crawling ends automatically after 10 minutes without me telling it to stop, Android crawler is part of android jetpack I am doing android app crawling and it exits after 10 minutes on its own, i have given a timeout of 60000 seconds, I want to run it for at least 15 minutes. the crawler is part of the android jetpack.I was expecting it will run till I manually stop it.
https://developer.android.com/studio/test/other-testing-tools/app-crawler


text:
Q: Handling bad URLs with requests Sorry in advance for the beginner question. I'm just learning how to access web data in Python, and I'm having trouble understanding exception handling in the requests package.
So far, when accessing web data using the urllib package, I wrap the urlopen call in a try/except structure to catch bad URLs, like this:
import urllib, sys

url = 'https://httpbinTYPO.org/' # Note the typo in my URL

try: uh=urllib.urlopen(url)
except:
    print 'Failed to open url.'
    sys.exit()

text = uh.read()
print text

This is obviously kind of a crude way to do it, as it can mask all kinds of problems other than bad URLs.
From the documentation, I had sort of gathered that you could avoid the try/except structure when using the requests package, like this:
import requests, sys

url = 'https://httpbinTYPO.org/' # Note the typo in my URL

r = requests.get(url)
if r.raise_for_status() is not None:
    print 'Failed to open url.'
    sys.exit()

text = r.text
print text

However, this clearly doesn't work (throws an error and a traceback). What's the "right" (i.e., simple, elegant, Pythonic) way to do this?

A: Try to catch connection error:
from requests.exceptions import ConnectionError

try:
    requests.get('https://httpbinTYPO.org/')
except ConnectionError:
    print 'Failed to open url.'

A: You can specify a kind of exception after the keyword except.  So to catch just errors that come from bad connections, you can do:
import urllib, sys

url = 'https://httpbinTYPO.org/' # Note the typo in my URL

try: uh=urllib.urlopen(url)
except IOError:
    print 'Failed to open url.'
    sys.exit()

text = uh.read()
print text


text:
Q: How to display div element on hover another element using css-in-js? I'm trying to display some information only on hover to special div. I'm using material ui and their withStyles component. Is there a way to do that?

A: Please check this example:
import React, {useState} from "react";

export default function ShowButtonHover() {
    const [style, setStyle] = useState({display: 'none'});

    return (

Hidden message in the box. Move mouse in the box

 {
                     setStyle({display: 'block'});
                 }}
                 onMouseLeave={e => {
                     setStyle({display: 'none'})
                 }}
            >

This was hidden

    );
}


text:
Q: Efficient way to get SingleResultObject in java I have a query to get the maximum id of a table Eg:Country.
Is there any efficient way to get a singleResultObject?
There is the possibility to get an Exception while getting a singleResultObject.
Query q = em.createQuery("SELECT MAX(c.countryId) FROM Country c ");

try
{
   Integer countryId = (Integer) q.getSingleResult();
}
catch (Exception e)
{
   logger.error("Exception " + e);
}


text:
Q: Creating a spss file in multiple languages SPSS  dll i have does  not support encoding. It reads French and German OK but any double byte language string, e.g. Chinese, Japanese, or Russian, reads back as "???"
// At binary level, the buffer actually contains "3f" for each "?". This may be the result of a failed unicode conversion.
When we write into .sav file, the interface only allows us to set interface encoding (not file level encoding, or code page). I suspect maybe the dll does not support double byte languages.
I have created SPSSDocument for write data  but  cannot find any encoding while creating file.
Can anyone help me in this issue?