Q: Pygame in python My game was working before I added lines 7 and 8.
what happened in the game was the red sprites that fall down the screen would hit the main character sprite which is green and the game would stop just as I need it to.
import pygame
import random

from os import path
img_dir = path.join(path.dirname(__file__),'PNG')

background = pygame.image.load(path.join(img_dir,'Space-Background.png')).convert()
background_rect = background.get_rect()

WIDTH = 480
HEIGHT = 600
FPS = 60

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)

pygame.init()
pygame.mixer.init()

screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):

    def __init__(self):

        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50,40))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH/2
        self.rect.bottom = HEIGHT-10

        self.speedx = 0

    def update(self):
        self.speedx = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speedx = -5
        if keystate[pygame.K_RIGHT]:
            self.speedx = 5

        self.rect.x += self.speedx

        if self.rect.right > WIDTH:
            self.rect.right = WIDTH
        if self.rect.left < 0:
            self.rect.left = 0

    def shoot(self):
        bullet = Bullet(self.rect.centrex,self.rect.top)
        all_sprites.add(bullet)
        bullets.add(bullet)

class Mob(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((30,40))
        self.image.fill(RED)
        self.rect = self.image.get_rect()

        self.rect.x = random.randrange(0, WIDTH - self.rect.width)
        self.rect.y = random.randrange(-100,-40)
        self.speedy = random.randrange(1,8)

    def update(self):
        self.rect.y += self.speedy

        if self.rect.top > HEIGHT +10:
            self.rect.x = random.randrange(0, WIDTH - self.rect.width)
            self.rect.y = random.randrange(-100,-40)
            self.speedy = random.randrange(1,8)

class Bullet(pygame.sprite.Sprite):
    def __init__(self,x,y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((10,20))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.rect.bottom = y
        self.rect.centrex = x
        self.speedy = -10
    def update(self):
        self.rect.y += self.speedy

        if self.rect.bottom < 0:
            self.kill()

# player_img = pygame.image.load(path.join(img_dir,"spaceShips_003.png")).convert()
# bullet_img = pygame.image.load(path.join(img_dir,"spaceMissile_006.png")).convert()
# mob_img = pygame.image.load(path.join(img_dir,"SpaceMeteor_004.png")).convert()

all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()

player = Player()

for i in range(8):
    m = Mob()
    all_sprites.add(m)
    mobs.add(m)

all_sprites.add(player)

running = True
while running:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                player.shoot()
    all_sprites.update()

    hits = pygame.sprite.groupcollide(mobs,bullets,True,True)
    for hit in hits:
         m = Mob()
         all_sprites.add(m)

    hits = pygame.sprite.spritecollide(player,mobs,False)

    if hits:
        running = False

    screen.fill(BLACK)
#    screen.split(background.background_rect)
    all_sprites.draw(screen)
    pygame.display.flip()

pygame.quit()

After I added the two lines for the images there was an error message. I am not sure what happened and I need some help fixing it.
>>> %Run trial.py
pygame 2.1.2 (SDL 2.0.18, Python 3.7.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:\Users\Mish Mash\Documents\School File\trial.py", line 7, in <module>
    background = pygame.image.load(path.join(img_dir,'Space-Background.png')).convert()
pygame.error: cannot convert without pygame.display initialized

A: The meaning of the following error: pygame.error: cannot convert without pygame.display initialized is that you are trying to use a method of pygame.display (the convert method) without initializing pygame first. To fix this, simply move pygame.init() to below the import statements.
Code
import pygame
import random

from os import path

pygame.init()
pygame.mixer.init()

img_dir = path.join(path.dirname(__file__), 'PNG')

background = pygame.image.load(path.join(img_dir, 'Space-Background.png')).convert()
background_rect = background.get_rect()

WIDTH = 480
HEIGHT = 600
FPS = 60

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):

    def __init__(self):

        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 40))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH / 2
        self.rect.bottom = HEIGHT - 10

        self.speedx = 0

    def update(self):
        self.speedx = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speedx = -5
        if keystate[pygame.K_RIGHT]:
            self.speedx = 5

        self.rect.x += self.speedx

        if self.rect.right > WIDTH:
            self.rect.right = WIDTH
        if self.rect.left < 0:
            self.rect.left = 0

    def shoot(self):
        bullet = Bullet(self.rect.centrex, self.rect.top)
        all_sprites.add(bullet)
        bullets.add(bullet)

class Mob(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((30, 40))
        self.image.fill(RED)
        self.rect = self.image.get_rect()

        self.rect.x = random.randrange(0, WIDTH - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        self.speedy = random.randrange(1, 8)

    def update(self):
        self.rect.y += self.speedy

        if self.rect.top > HEIGHT + 10:
            self.rect.x = random.randrange(0, WIDTH - self.rect.width)
            self.rect.y = random.randrange(-100, -40)
            self.speedy = random.randrange(1, 8)

class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((10, 20))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.rect.bottom = y
        self.rect.centrex = x
        self.speedy = -10

    def update(self):
        self.rect.y += self.speedy

        if self.rect.bottom < 0:
            self.kill()

# player_img = pygame.image.load(path.join(img_dir,"spaceShips_003.png")).convert()
# bullet_img = pygame.image.load(path.join(img_dir,"spaceMissile_006.png")).convert()
# mob_img = pygame.image.load(path.join(img_dir,"SpaceMeteor_004.png")).convert()

all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()

player = Player()

for i in range(8):
    m = Mob()
    all_sprites.add(m)
    mobs.add(m)

all_sprites.add(player)

running = True
while running:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                player.shoot()
    all_sprites.update()

    hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
    for hit in hits:
        m = Mob()
        all_sprites.add(m)

    hits = pygame.sprite.spritecollide(player, mobs, False)

    if hits:
        running = False

    screen.fill(BLACK)
    #    screen.split(background.background_rect)
    all_sprites.draw(screen)
    pygame.display.flip()

pygame.quit()


Q: Symfony2 + Doctrine2 SQL Integrity Violation: Nullable field can't be null? So this project is moving some straight PDO SQL queries (with MySQL) to Doctrine. The tables already existed and had data in them. I set up the entities, and everything seemed golden. All the queries were rewritten with the Entity Manager in Doctrine, and everything seemed to work.
Except I forgot that three fields in one of the entities needed to be nullable. They were set to NOT NULL in the database and there was no nullable=true declaration in the Doctrine annotations.
I manually altered to table in MySQL to make the fields nullable, then added a nullable=true to the entities, cleared the cache and executed a
php app/console doctrine:schema:update --force

Just to be sure (which executed correctly).
However, despite the fact that the Doctrine entity allows null fields, and the database has the columns nullable as well, I still get this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'type_id' cannot be null

Is there any way for me to fix this without dropping the tables (which would involve also saving all the data)? What exactly is wrong here? According to all the code and databases involved, there should be no integrity violations at all (the field isn't a foreign key either).
Here is the entity in question:
class Audio
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer", name="id")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", name="type", columnDefinition="ENUM('song','demo')")
     */
    protected $type;

    /**
     * @ORM\Column(type="integer", name="type_id", nullable=true)
     */
    protected $typeId = null;

    /**
     * @ORM\Column(type="string", name="s3_url", nullable=true)
     */
    protected $s3url = null;

    /**
     * @ORM\Column(type="string", name="s3_key", nullable=true)
     */
    protected $s3key = null;

    /**
     * @ORM\Column(type="datetime", name="date_created")
     */
    protected $dateCreated;

    /**
     * @ORM\Column(type="datetime", name="date_modified")
     */
    protected $dateModified;

This is absolutely mystifying me. There's really no more ways for me to tell the program that it can be null.

A: Hi i don't know if you still have the problem.
You can do php app/console doctrine:schema:update --dump-sql
In order to know the difference bewteen your model and the database.
And apply the line he will tell you.
I think it will fix the problem


Q: bitmap size exceed VM budget in second level I'm developing a game in which I am trying to move from 1st stage to 2nd stage.
When I start the 2nd stage directly it runs perfectly, but when I play the 1st stage and unlock the 2nd stage, and then start the second stage then it shows an error:
02-25 14:07:09.923: ERROR/AndroidRuntime(409): FATAL EXCEPTION: GLThread 12
02-25 14:07:09.923: ERROR/AndroidRuntime(409): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
02-25 14:07:09.923: ERROR/AndroidRuntime(409):     at android.graphics.Bitmap.nativeCreate(Native Method)
02-25 14:07:09.923: ERROR/AndroidRuntime(409):     at android.graphics.Bitmap.createBitmap(Bitmap.java:477)
02-25 14:07:09.923: ERROR/AndroidRuntime(409):     at android.graphics.Bitmap.createBitmap(Bitmap.java:444)
02-25 14:07:09.923: ERROR/AndroidRuntime(409):     at com.threed.jpct.util.BitmapHelper.rescale(BitmapHelper.java:72)
02-25 14:07:09.923: ERROR/AndroidRuntime(409):     at bones.samples.android.LevelTwo$MyRenderer.onSurfaceChanged(LevelTwo.java:555)
02-25 14:07:09.923: ERROR/AndroidRuntime(409):     at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1356)
02-25 14:07:09.923: ERROR/AndroidRuntime(409):     at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1118)

I can't understand this situation because when I only run a single stage then they run correctly but when run 2nd after first it can't.
Texture texture = new Texture(BitmapHelper.rescale(BitmapHelper.convert(getResources().getDrawable(R.drawable.bgtwo)), 512, 1024));
TextureManager.getInstance().addTexture("texture", texture);


Q: What informations leaks during send mail programatically from google account Imagine if you are sending an email by the gmail.com using web online interface so entering the website of google, then compose mail and send it. In this case your ip address is not revealed to the receiver of mail. In details of mail header there are google server's informations.
If it is good or not it is a topic for a big discussion, have some advantages and disadvantages... However only one way to get someone's ip address so location is court way and lawyer sending a document to google with a question to reveal ip address of sender of the particular mail. Am I right ?
What is my wondering right now is if I have same privacy (assuming I claim true above) in case of using a program and perform a function like this:
    public static void SendAnEmail(MailAccount mailAccount, Mail mail)
    {
        SmtpClient client = new SmtpClient();
        client.Port = 587;
        client.Host = mailAccount.host;
        client.EnableSsl = true;
        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential(mailAccount.username, mailAccount.password);

        MailMessage mailMessage = new MailMessage(mailAccount.username, mail.mailTo, mail.subject, mail.body);
        mailMessage.BodyEncoding = UTF8Encoding.UTF8;
        mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

        client.Send(mailMessage);
    }

where Mail contain subject, body and mailTo strings and MailAccount have username, password and host, so all required informations to send an email. The whole code is written in C# by the way.
Imagine that I have a program which is doing some office work and at the end of some activities is going to send an email using code above of course using a google host (an account created at google website). Then - what is happening ? What is in mail details header ? My computer ip address or google server ones ? Do this mail contain some more information like mac address of network card or my motherboard.
I hope you understand my question, if it is not clear, please ask questions about my situation. Any suggestion how to obtain such a privacy using "mailing by code" would be appreciated. However explanation of the situation it is what I am looking for.
Thank you in advance and have a nice day.


Q: How to Display User Input of a HTML Form I've written the code below (part of my code) and I can't figure out why it won't show the user input in the form of table on the web page.

<form>
   What is the above picture?

  <input type="text" name="What is the above picture?" id="input">
  <input type="button" id="submit-button" value="Submit" onclick="insert_result()">
</form>

       Image
       Tag

A: *

*Spelling getElementById

*Move getting the input value inside the function that needs it

*you need a new cell each time, otherwise you just move the cell

you might want a new row too for each input

const inputField = document.getElementById("input");
const result_row = document.getElementById("results");

function insert_result() {
  let input = inputField.value;
  let new_row = document.createElement("td");
  new_row.append(input);
  result_row.appendChild(new_row);
}
<form>
   What is the above picture?

  <input type="text" name="What is the above picture?" id="input">
  <input type="button" id="submit-button" value="Submit" onclick="insert_result()">
</form>

       Image
       Tag


Q: Is it possible to use logical connectives in conditionals?
Possible Duplicate:
How to form “if … or … then” conditionals in TeX?

By writing \ifnum cond1 and cond2, the compilation is successful but the generated document is conceptually invalid.
If possible, how to specify logical connectives?


Q: using mysql to get a list of inserted records Inserting multiple records to a table in MYSQL returns me last inserted ID.
Is there a way I can get the list of all inserted records ?
One way would be to insert each record and then fetch that record using last inserted ID. But obviously that will raise performance issues.


Q: Is learning rate automatically decreased between passes when vw LDA is run with `--save_resume` vowpal wabbit (vw) supports out-of-core learning with --save_resume. This is what the --help options tells the end user about the --save_resume option:
--save_resume                         save extra state so learning can be
                                        resumed later with new data

I have a large living data set, currently hundreds of millions documents sorted into 1024 batches, and my goal is train a LDA-model on all batches, and for that purpose I run a script that invokes vw like this (Nota bene I do not set --passes, so each data point is only seen once).
Initial invokation:
vw -d clean.txt --lda 100 --lda_D 307000000 -f weights --readable_model lda.model.vw

Subsequent invocations (the content of clean.txt is changed between invocations):
vw -d clean.txt --lda 100 --lda_D 307000000 --save_resume -i weights -f weights --readable_model lda.model.vw

I have successfully run all batches through vw this way, but from the output given by vw in each invocation, it seems the learning rate never drops, it always looks like this:
learning rate = 0.5
initial_t = 0
power_t = 0.5

I would have guessed that the learning rate is saved when --save_resume is requested, and that vw automatically decreases the learning rate as it sees more data, but this does not seem to be the case, right?
Do you have to manage the learning rate manually with vowpal wabbit?

A: It appears that LDA has a learn rate thats computed based on (but stored separately from) the global learning rate. LDA's learning/decay rates don't appear to be printed anywhere, so you wouldn't see them in the logs.
https://github.com/VowpalWabbit/vowpal_wabbit/blob/master/vowpalwabbit/lda_core.cc#L892


Q: Issue rendering dark mode - ReactJS I'm new and trying a project to make a switch that toggles between two themes;
Here is what I have so far and I'm struggling to understand why it's not toggling between my themes.
theme.js
import { createContext } from "react";

export const themes = {
  dark: "dark-mode",
  light: "white-mode",
};

export const ThemeContext = createContext({
    theme: themes.dark,
  changeTheme: () => {},
});

themeWrapper.js
import React, { useState, useEffect } from 'react';
import { ThemeContext, themes } from './theme.js';
import "./App.css"

export default function ThemeContextWrapper(props) {
  const [theme, setTheme] = useState(themes.dark);

  function changeTheme(theme) {
    setTheme(theme);
  }

  useEffect(() => {
    switch (theme) {
      case themes.light:
        document.body.classList.add('white-mode');
        break;
      case themes.dark:
      default:
        document.body.classList.remove('white-mode');
        break;
    }
  }, [theme]);

  return (
    <ThemeContext.Provider value={{ theme: theme, changeTheme: changeTheme }}>
      {props.children}
    </ThemeContext.Provider>
  );
}

So I've got a wrapper to re-render the app when dark mode is toggled, and two themes that are being exported.
App.css
.white-mode {
  font: #333;
  background: #eee;
  link: cornflowerblue;
}

.dark-mode {
  font: #eee;
  background: rgb(41, 41, 41);
  link: lightblue;
}

Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import ThemeContextWrapper from '.themeWrapper';

ReactDOM.render(
  <ThemeContextWrapper>
    <React.StrictMode>
      <App />
    </React.StrictMode>{' '}
  </ThemeContextWrapper>,
  document.getElementById('root'),
);

So now in App.js I have the button
import './App.css';
import { Button, Container, InputGroup } from 'reactstrap';
import { ThemeContext, themes } from '.theme';
import React from 'react';

function App() {
  const [darkMode, setDarkMode] = React.useState(true);

  return (

Dark/Light mode

        <InputGroup>
          <ThemeContext.Consumer>
            {({ changeTheme }) => (
              <Button
                color="link"
                onClick={() => {
                  setDarkMode(!darkMode);
                  changeTheme(darkMode ? themes.light : themes.dark);
                }}
              >
                Toggle
              </Button>
            )}
          </ThemeContext.Consumer>
        </InputGroup> */}

  );
}

export default App;

But this button doesn't appear to do anything, where have I gone wrong?


Q: TX-row lock contention : Inserting Duplicate values for Unique Key We are getting a TX-row lock contention error while trying to insert data
It happens while running a job which processes an xml with almost 10000 records, inserting the data into a table
We are having a unique key constraint on one of the columns in the table, and in the request we are getting duplicate values. This is causing the locks and thereby the job is taking more time.
We are using hibernate and spring. The DAO method we use is hibernate template's 'save' annotated with Spring Transaction Manager's @Transactional
Any suggestions please?

A: It's not clear whether you're getting locking problems or errors.
"TX-row lock contention" is an event indicating that two sessions are trying to insert the same value into a primary or unique constraint column set -- an error is not raised until the first one commits, then the second one gets the error. So you definitely have multiple sessions inserting rows. If you just had one session then you'd receive the error immediately, with no "TX-row lock contention" event being raised.
Suggestions:

*

*Insert into a temporary table without the constraint, then load to the real table using logic that eliminates the duplicates

*Eliminate the duplicates as part of the read of the XML.

*Use Oracle's error logging syntax -- example here. http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9014.htm#SQLRF55004


Q: Is this sentence construction wrong, where "going home" has other implied meaning, the origin and span of which isn't known? I stumbled upon this article about the origins of some unusual idioms and phrases, as I have heard many of them being used popularly.
But I was bit shocked and frustrated when I read this sentence which seems to be constructed wrongly(even though it is only created to exemplify a different phrase).

Pixie should never have gone home in that Dance-Off. She wiped the floor with Simon.

Was there any separate, short-lived, short-spanned phrase "going home" where it means any style of dance like "free style" or "original style" / "ethnic style" which could represent a knowledge of unique moves which his/her dance(or any activity) competitor doesn't know of ?
Because I have never heard of(or stumbled upon while researching) any sentence where "going home" means anything other than just going home

A: “Going home” here means that participant was eliminated from a reality TV competition (in this case, Strictly Come Dancing).
It’s pretty a pretty common expression in this context. Here are some examples:

*

*Elimination Tracker: Here’s Every Celeb Who’s Gone Home on Dancing With the Stars This Season (and Why!)

*‘American Idol’s Disney Night — Did the Right People Go Home? (POLL)

*The first cut is the deepest: Nearly half of 'The Voice’ Season 19 contestants go home in one night
The origin of this expression is likely Survivor, a show where the competitors are marooned on an island and losing means they literally have to leave and go home.


Q: eclipse shortcut publish everywhere I would like to change the publish shortcut behaviour to apply to every window i work.
This would remove the need to be in the server view to use this shortcut (CTRL+ALT+P)
So far I followed this post: eclipse key bindings everywhere
Setting "when" to "in windows" did not work. I guess because the shortcut is still part of the category "server"
How can I change the category? Is there another way to fix this?

A: This is not going to work. The command handler for the Publish action (org.eclipse.wst.server.ui.internal.view.servers.ServerActionHandler) expects the current selection to be a server and doesn't do anything if it is not. So you have to be in the server view for it to work.


Q: Rails model design: propose and counter-propose a time I have a model that allows user A to propose a time for an appointment to user B. If B accepts, then event is set. But if B proposes another time, then A must accept or propose another time, and so on. Until one user accept the other's counter-proposal, the appointment won't be set.
How should I model this kind of back and forth proposals and to keep track of current stage in Rails?
Thank you.

A: What you're describing is a state machine.
Older SO question discussing the various gems and plugins of the time, plus some basics.
Newer blog post discussing the hows and whys.


Q: How to serialize canonical/normalized JSON in PHP The order of keys in JSON is not relevant, so PHP's json_encode uses the internal order of keys when serializing JSON format. I'd like to make sure that equivalent JSON is always serialized the same form. For instance $a and $b in the following example
$a = ["foo" => 1, "bar" => 2, "doz" => 3];
$b = ["doz" => 3, "bar" => 2, "foo" => 1];
print json_encode($a)."\n";
print json_encode($b)."\n";

result in different serializations
{"foo":1,"bar":2,"doz":3}
{"doz":3,"bar":2,"foo":1}

but they are equivalent.

A: You need to sort the array in some way, I recommend sorting by key (foo, bar, doz).
http://php.net/manual/en/function.ksort.php
The order will always be the same when using the same keys.
I haven't tested this, but it should work for your code.
$a = ["foo" => 1, "bar" => 2, "doz" => 3];
$b = ["doz" => 3, "bar" => 2, "foo" => 1];
ksort($a);
ksort($b);
print json_encode($a)."\n";
print json_encode($b)."\n";

This will print:

{"bar":2,"doz":3,"foo":1}
{"bar":2,"doz":3,"foo":1}


Q: What directives and other features are available for inputs with a ControlValueAccessor? I have a custom component. It has a ControlValueAccessor injected into it as a provider. This is the generic standard way to make custom components represent form inputs.
For a more precise example the component actually implements ControlValueAccessor and injects itself into itself. This detail should not be important.
I know that this makes the following things available for this component out of the box:

*

*ngModel directive for two-way data binding

*several css-classes managed by Angular: ng-dirty/ng-pristine, ng-valid and ng-touched
Is there any other directives available out of the box besides ngModel? I would expect at least something like blur and change events to work.


Q: how to show different object field in table I have a custom object name order under the opportunity object. I want to create a table which field are status which is field of opportunity and another attribute name price which is field of order custom object. how to create such table in visualforce.

A: Use can use a simple vf page page with pageblocktable to do this.
Query the opportunity object with status and price from order.
select status,(select price from order) from opportunity

Access the list from vf page in pageblocktable.
<apex:pageblocktable value={!listyouwant} var="lyw">
<apex:column >
    <apex:facet name="header">Opp Status</apex:facet>
    <apex:outputtext value="{!lyw.status}" />
</apex:column>
<apex:column >
    <apex:facet name="header">Price</apex:facet>
    <apex:outputtext value="{!lyw.price}" />
</apex:column>

This should give you the required table.

A: If sounds like Opportunity is the parent object so the query would be on the child:
select Opportunity__r.Status__c, Price__c from Order__c where ...

and the Visualforce would be:
<apex:pageBlockTable value={!list} var="item">
    <apex:column value="{!item.Opportunity__r.Status__c}"/>
    <apex:column value="{!item.Price__c}"/>
</apex:pageBlockTable>

(You will need to double check the relationship name Opportunity__r. See Understanding Relationship Names, Custom Objects, and Custom Fields for more information.)


Q: I don't know why this is happened and i don't know how to ask this question I'm using termux app, then i try to install npm packages in the different directory in my phone.
The first one "/storage/shared/coding"
.../0/Coding $ npm i node-session
npm WARN deprecated nomnom@1.8.1: Package no longer supported. Contact support@npmjs.com for more info.
npm WARN deprecated @mapbox/geojsonhint@2.0.1: Please make plans to check GeoJSON in some other way
npm ERR! code EPERM
npm ERR! syscall symlink
npm ERR! path ../@mapbox/geojsonhint/bin/geojsonhint
npm ERR! dest /storage/emulated/0/Coding/node_modules/.bin/geojsonhint
npm ERR! errno -1
npm ERR! Error: EPERM: operation not permitted, symlink '../@mapbox/geojsonhint/bin/geojsonhint' -> '/storage/emulated/0/Coding/node_modules/.bin/geojsonhint'
npm ERR!  [Error: EPERM: operation not permitted, symlink '../@mapbox/geojsonhint/bin/geojsonhint' -> '/storage/emulated/0/Coding/node_modules/.bin/geojsonhint'] {
npm ERR!   errno: -1,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'symlink',
npm ERR!   path: '../@mapbox/geojsonhint/bin/geojsonhint',
npm ERR!   dest: '/storage/emulated/0/Coding/node_modules/.bin/geojsonhint'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     /data/data/com.termux/files/home/.npm/_logs/2022-04-25T19_14_38_772Z-debug-0.log
.../0/Coding $  pwd
/storage/emulated/0/Coding

And the second one "/noda"
~/noda $ npm i node-session
npm WARN deprecated nomnom@1.8.1: Package no longer supported. Contact support@npmjs.com for more info.
npm WARN deprecated @mapbox/geojsonhint@2.0.1: Please make plans to check GeoJSON in some other way

added 151 packages, and audited 152 packages in 7s

43 packages are looking for funding
  run `npm fund` for details

17 vulnerabilities (1 moderate, 12 high, 4 critical)

To address issues that do not require attention, run:
  npm audit fix

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.
~/noda $ pwd
/data/data/com.termux/files/home/noda

Why does node-session can be installed in /noda directory but not in /storage/shared/coding and how can i install it in /storage/shared/coding

A: NodeJs you installed on Termux doesn't have permission to install dependencies on /storage/emulated/0/Coding/node_modules/.bin/geojsonhint.
You can solve it by:

*

*Changing the directory of the project to somewhere with public permissession.

*Running the command with the administration privilege but on Termux, I think.

*Using nvm to install node js instead of default ways.

This problem comes when you try to install node js with Termux. try not to.
NVM repository link: nvm-sh/nvm.
pay attention:

*

*You need to check your dependency tree is compatible with the node version you want to install.

*If the project is big be careful because you can break your project easily.


Q: Numbers from textboxes are add next to each other instead of adding them together I have 3 textboxes in which I write numbers and last one in which is the result. If I write numbers in TextBoxA and TextBoxB instead of adding them together after I press equal button then it put them next to each other.
[]
I tried this code:
 private void EqualsButton_Click(object sender, EventArgs e)
 {
    OutputTextBox.Text = ($"{InputTextBoxA.Text + InputTextBoxB.Text}");
 }

A:
First you must convert text on textbox to int or any number type

Simple way :
    private void EqualsButton2_Click(object sender, EventArgs e)
    {
        int numberA = int.Parse(textBox1.Text.Trim());
        int numberB = int.Parse(textBox2.Text.Trim());

        var result = numberA + numberB;

        textBox3.Text = result.ToString();
    }

Safe way :
    private void EqualsButton_Click(object sender, EventArgs e)
    {
        if (!int.TryParse(textBox1.Text.Trim(), out int numberA))
            numberA = 0;

        if (!int.TryParse(textBox2.Text.Trim(), out int numberB))
            numberB = 0;

        var result = numberA + numberB;

        textBox3.Text = result.ToString();
    }

A: private void EqualsButton_Click(object sender, EventArgs e)
{
  var resultA=0;
  var resultB=0;
  if(!string.IsNullOrEmpty(InputTextBoxA.Text))
        resultA=Convert.ToInt32(InputTextBoxA.Text);
  if(!string.IsNullOrEmpty(InputTextBoxB.Text))
        resultB=Convert.ToInt32(InputTextBoxB.Text);
    OutputTextBox.Text = resultA+ resultB ;
}

A: Don't listen to anyone. Do this
txtResult.Text = string.Empty;

if (!decimal.TryParse(txt1.Text.Trim(), out decimal v1))
{
    MessageBox.Show("Bad value in txt1");
    return;
}
if (!decimal.TryParse(txt2.Text.Trim(), out decimal v2))
{
    MessageBox.Show("Bad value in txt2");
    return;
}

txtResult.Text = (v1 + v2).ToString();

A: You can change into this
 private void EqualsButton_Click(object sender, EventArgs e)
 {
   try
    {
       OutputTextBox.Text = ($"{ Convert.ToInt32(InputTextBoxA.Text.Trim() == "" ? "0" : InputTextBoxA.Text) + Convert.ToInt32(InputTextBoxB.Text.Trim() == "" ? "0" : InputTextBoxB.Text)}");
    }
    catch(exception ex)
    {
      MessageBox.Show("Enter Valid number")'
    }
 }

A: You need to convert text fields to int and after for the answer back to the text.
If you did not enter a value, then there "" is considered as 0 when adding.
private void EqualsButton_Click(object sender, EventArgs e)
{
  OutputTextBox.Text = Convert.ToString(
    Convert.ToInt32(InputTextBoxA.Text == "" ? "0" : InputTextBoxA.Text)
    + Convert.ToInt32(InputTextBoxB.Text == "" ? "0" : InputTextBoxB.Text));
}


Q: Make keyboard NOT dismiss when opening a ModalViewController
Possible Duplicate:
How can I keep the keyboard present even when presenting a modal view controller?

I have an opened keyboard on one viewcontroller and I want to show another one. But when I show it, keyboard goes down. But I don't want it to go down. I want it to stay. How can I achieve this? I don't call any endEditings and resignFirstResponders myself.


Q: Why is the total energy of system considered to be a state function? Mechanical power is not a state function because it changes with the change of the path taken from a specific initial point to a specific final point.
The same for thermal power. It is not a state function.
But the sum of mechanical and thermal power is the variation of total energy of the system, and the total energy is considered a state function.
I am not convinced since if the mechanical power decreased by some amount, the thermal power doesn't increase by the same amount..
So, why is the variation of the total energy considered a state function?

A: The argument goes the other way:

*

*The energy of the system is the sum of the energies of its parts and the interactions between them - this is why it is a state function.

*The energy can be changed by work or transferring heat, which is why their sum is a state function, even though separately neither of them is.

A:
But the sum of mechanical and thermal power is the variation of total
energy of the system, and the total energy is considered a state
function.

That is true because heat and work are the only two basic means for transferring energy to or from a system. So while neither heat nor work are state functions the combination of the two must necessarily equal the change in the energy of the system (change in state function). For a closed system, the first law is
$$\Delta U=Q-W$$

I am not convinced since if the mechanical power decreased by some
amount, the thermal power doesn't increase by the same amount.

I'm not quite sure what you mean since it sounds like you may be confusing "thermal power" with internal energy.
At any rate, it is possible that the work done by or on the system can exactly equal the heat transfer out of or into the system, because in such a case $\Delta U=0$. An example is a reversible isothermal expansion or compression of an ideal gas.
Hope this helps.

A: I would only add to @Vadim's answer that the internal energy $E=Q+W$ being the sum of the absorbed heat $Q$ and work $W$ is a state function because this is what the experiments are saying going back to at least 200 years from Count Rumford to Joule. It does not matter what $Q$ and $W$ individually are, if their sum is the same $Q+W$ value then the specimen's empirical temperature is the same, i.e., it depends only on $E$. True, we do not and can not measure $E$ directly but only the empirical temperature, and we also assume that along with the mechanical/electrical/magnetic/chemical parameters a single $thermal$ parameter is enough to describe the thermostatic equilibrium state. So far, empirically it appears this is good enough.


Q: Where to get a pre-built Chromium to easily do modifications? Chromium takes too long to get compiled, like 7 hours on a regular powerful desktop. I'm thinking of some where to get a pre-built Chromium, with which I will be able to compile again only some files to re-link to make a new Chromium binary.
Possible to compile just some source code files and re-link (re-link object files)?

A: It's hard to build Chromium from source but it's every easy to build a new browser based on Chromium.
With GitHub Electron, any app based on it is a real Chromium browser, and developers may create custom UI for their Electron-based browsers.
However, modern browsers would require having servers for storing users' sync data, this might not be easily affordable for 1-man development army to create a new browser for the mass.
Electron app is a pack of Chromium sandbox, and Node.js backend, the 2 communicate thru' IPC as Node.js will be able to access all resources.
GitHub Electron:
https://electronjs.org


Q: Pandas: How to pivot rows into columns I am looking for a way to pivot around 600 columns into rows. Here's a sample with only 4 of those columns (good, bad, ok, Horrible):
df:
RecordID   good   bad   ok  Horrible
  A          0      0    1     0
  B          1      0    0     1

desired output:
 RecordID     Column    Value
   A           Good       0
   A            Bad       0
   A            Ok        1
   A          Horrible    0
   B           Good       1
   B            Bad       0
   B            Ok        0
   B          Horrible    1

A: You can use .stack() as follows.  Using .stack() is preferred as it naturally resulted in rows already sorted in the order of RecordID so that you don't need to waste processing time sorting on it again, especially important when you have a large number of columns.
df = df.set_index('RecordID').stack().reset_index().rename(columns={'level_1': 'Column', 0: 'Value'})

Output:
  RecordID    Column  Value
0        A      good      0
1        A       bad      0
2        A        ok      1
3        A  Horrible      0
4        B      good      1
5        B       bad      0
6        B        ok      0
7        B  Horrible      1

A: You can use melt function:
(df.melt(id_vars='RecordID', var_name='Column', value_name='Value')
   .sort_values('RecordID')
   .reset_index(drop=True)
)

Output:
    RecordID      Column    Value
0          A        good        0
1          A         bad        0
2          A          ok        1
3          A    Horrible        0
4          B        good        1
5          B         bad        0
6          B          ok        0
7          B    Horrible        1

A: Adding dataframe:
import pandas as pd
import numpy as np

data2 = {'RecordID': ['a', 'b', 'c'],
        'good': [0, 1, 1],
        'bad': [0, 0, 1],
        'horrible': [0, 1, 1],
        'ok': [1, 0, 0]}

# Convert the dictionary into DataFrame
df = pd.DataFrame(data2)

Melt data:
https://pandas.pydata.org/docs/reference/api/pandas.melt.html
melted = df.melt(id_vars='RecordID', var_name='Column', value_name='Value')
melted

Optionally: Group By - for summ or mean values:
f2 = melted.groupby(['Column']).sum()
df2


Q: How to run kubectl exec on scripts that never end I have a mssql pod that I need to use the sql_exporter to export its metrics.
I was able to set up this whole thing manually fine:

*

*download the binary

*install the package

*run ./sql_exporter on the pod to start listening on port for metrics

I tried to automate this using kubectl exec -it ... and was able to do step 1 and 2. When I try to do step 3 with kubectl exec -it "$mssql_pod_name" -- bash -c ./sql_exporter the script just hangs and I understand as the server is just going to be listening forever, but this stops the rest of my installation scripts.
I0722 21:26:54.299112     435 main.go:52] Starting SQL exporter (version=0.5, branch=master, revision=fc5ed07ee38c5b90bab285392c43edfe32d271c5) (go=go1.11.3, user=root@f24ba5099571, date=20190114-09:24:06)
I0722 21:26:54.299534     435 config.go:18] Loading configuration from sql_exporter.yml
I0722 21:26:54.300102     435 config.go:131] Loaded collector "mssql_standard" from mssql_standard.collector.yml
I0722 21:26:54.300207     435 main.go:67] Listening on :9399
<nothing else, never ends>

Any tips on just silencing this and let it run in the background (I cannot ctrl-c as that will stop the port-listening). Or is there a better way to automate plugin install upon pod deployment? Thank you

A: To answer your question:
This answer should help you. You should (!?) be able to use ./sql_exporter & to run the process in the background (when not using --stdin --tty). If that doesn't work, you can try nohup as described by the same answer.
To recommend a better approach:
Using kubectl exec is not a good way to program a Kubernetes cluster.
kubectl exec is best used for debugging rather than deploying solutions to a cluster.
I assume someone has created a Kubernetes Deployment (or similar) for Microsoft SQL Server. You now want to complement that Deployment with the exporter.
You have options:

*

*Augment the existing Deployment and add the sql_exporter as a sidecar (another container) in the Pod that includes the Microsoft SQL Server container. The exporter accesses the SQL Server via localhost. This is a common pattern when deploying functionality that complements an application (e.g. logging, monitoring)

*Create a new Deployment (or similar) for the sql_exporter and run it as a standalone Service. Configure it scrape one|more Microsoft SQL Server instances.

Both these approaches:

*

*take more work but they're "more Kubernetes" solutions and provide better repeatability|auditability etc.

*require that you create a container for sql_exporter (although I assume the exporter's authors already provide this).


Q: How to put a link on the bottom right hand side of a page I am currently using the following code to do it.

  Load time: 1.1920928955078E-5 seconds

The problem I am having is that if the page is scrollable then it is midway through the page. I am sure that there is a simple solution for this, but I can't come up with it.
Any help or suggestions would be greatly appreciated.

A: You'll need the div have position fixed instead of absolute.
Fiddle: http://jsfiddle.net/hqkm7/

A: <\span style="position: absolute; bottom: 0pt; right: 0pt;">Load time: 1.1920928955078E-5 seconds<\/span>

should be
Load time: 1.1920928955078E-5 seconds

A: you need to use position:fixed instead of position:absolute. position:absolute does not scroll with the page while positions:fixed does (by taking your span out of the flow of the page).


Q: Why does The Doctor want to hide his browser history from Osgood? In the Zygon Inversion episode of Doctor Who (2005), The Doctor and Osgood had this conversation:

 DOCTOR: Oh, your specs are broken. I'll fix them. You can wear mine, they're sonic.
 OSGOOD: Sonic specs?
 DOCTOR: Yeah.
 OSGOOD: Isn't that a bit pointless? Like a visual hearing aid?
 DOCTOR: What's wrong with pointless? I once invented an invisible watch. Spot the design flaw.
 OSGOOD: You're talking nonsense to distract me from being really scared. It's one of your known character traits.
 (She puts the sonic sunglasses on.)
 DOCTOR: Don't look at my browser history.
 (The sunglasses beep.)
 OSGOOD: Whoa!
 DOCTOR: Yeah, I said don't.

Does The Doctor look at... exotic materials on his new wearable tech? Or, is there something else which the Doctor wants to keep private and which can make others jump? Is there anything from the history of Doctor Who to suggest what this is?

A: It seems pretty clear from context that the Doctor was "talking nonsense," as Osgood put it in the previous line. Whatever stimulus from the sonic specs made Osgood say "whoa" probably had nothing to do with browser history (for all we know she was just responding to it beeping in her ear), but the Doctor chose to spin out the joke further.


Q: Is this a valid regular language expression for a binary string? Can it be condensed into something more concise? The regular expression is:
(10) U ((10(0 U 1))*10)

The language I am trying to write is this:(q2 is the accept state and {0,1} is the langauge)
(q0,0)=q3
(q0,1)=q1
(q1,0)=q2   — accept state
(q1,1)=q3
(q2,0)=q0
(q2,1)=q0
(q3,0)=q3
(q3,1)=q3


Q: SQL check if next row doesn't exist I have an MsSQL server and what I am doing is selecting rows from the table. Currently I have two rows so I was wondering how would I check if there are no other rows after second one without making another query?
For example
table users
id    name    pass

1     joe     123

2     bob     abc

How would I check if there is no row after 2 with just a query? I am willing to combining it with my current query, which just selects the data.

A: You can return the number of rows in your query as another column:
SELECT id, name, pass, count(*) over () as rows
FROM users

Keep in mind that this is telling you the number of rows returned by the query, not the number of rows in the table. However, if you specify a "TOP n" in your select, the rows column will give you the number of rows that would have been returned if you didn't have "Top n"

A: If you're trying to paginate the trick is to query one more record than you actually need for the current page. By counting the result (mysql_num_rows) and comparing that to your page size, you can then decide if there is a 'next page'.
If you were using mysql you could also use SQL_CALC_FOUND_ROWS() in your query, which calculates the number of rows that would be returned without the LIMIT clause. Maybe there is an equivalent for that in MsSQL?

A: I assume that you are inserting manually the first 2 rows of your table.
According to that, my idea is to just do a select where the id is more than 2 like this:
SELECT * FROM users WHERE id > 2;

I also assume that you are using PHP so mysql_num_rows will return you 0 if no data is found, otherwise it will return you the number of rows from your query and now you know that you need to do a while or some loop to retrieve the data after id number 2.


Q: How to increase the font size in the Matlab help browser permanently? Maybe I'm getting old, but the text in Matlab's built-in help browser is too small for me to read comfortably. It is possible to increase the font size using Ctrl-+, but every time a new help page is loaded, this change is lost
How can I permanently increase the font size?

A: This has been tested with Matlab R2015a on Linux, but I'd expect it to work on other platforms and maybe earlier versions, too.
Matlab's documentation is in the form of HTML, and the help browser is basically a web browser displaying locally stored files. There are several central style files, but the most important one appears to be
/opt/MATLAB/R2015a/help/includes/product/css/reset.css

Open this file (as root / administrator) in a text editor, and append the line
html { zoom: 1.5; }

Adjust the number to your liking.

A: for R2014a, in /opt/MATLAB/R2015a/help/includes/product/css/reset.css, alter the value in the field
font-size:100%

to your liking. start with 105% - it's sensitive.
Note that you don't have to restart Matlab, just close the help window and re-open after you save the file. You can iterate quickly to find your desired zoom.


Q: How to get MouseOver trigger event alter child items I have a MouseOver event for a border.  Within that border (further down) I have a couple of Borders with RotateTransforms... How can I, within the top level Border hover event alter their transform? (i.e. change their rotation?)
<Border.Style>
    <Style>
        <Style.Triggers>
            <Trigger Property="Border.IsMouseOver" Value="True">
                <Setter Property="Border.Background" Value="#f0f0f0" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Border.Style>

Further down the tree, but inside this border is
<Border Padding="3" Width="73" Height="57" Background="White" RenderTransformOrigin="0.5, 0.5">
    <Border.Effect>
        <DropShadowEffect BlurRadius="4" Direction="0" ShadowDepth="0" Color="#aa505050" />
    </Border.Effect>
    <Border.RenderTransform>
         <RotateTransform Angle="-2" />
    </Border.RenderTransform>
</Border>

A: You could use a DataTrigger in an inner border Style with FindAncestor or ElementName binding to get the IsMouseOver of your outer border.
i.e.
<Border.Style>
    <Style TargetType="Border">
        <Setter Property="RenderTransform">
            <Setter.Value>
                <RotateTransform Angle="3"/>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=IsMouseOver}" Value="True">
                <Setter Property="RenderTransform">
                    <Setter.Value>
                        <RotateTransform Angle="6"/>
                    </Setter.Value>
                </Setter>
            </DataTrigger >
        </Style.Triggers>
    </Style>
</Border.Style>


Q: Pass data (retrieved from server) from parent route to its child route My Angular application have parent and child route. I am using (ui-router)
I what to build that parent route data (which are retrieved from server using $resource) are passed to its child route.
Here will be my application code. When I debugged my code, then "phaseTasks" in child route always was empty Array.
flowAdminApp.config(['$stateProvider', '$urlRouterProvider',
  function($stateProvider, $urlRouterProvider){

    $stateProvider
      .state('phase', {
        url: "/phases/:phase_id",
        template: JST['layouts/admin/flows/tasks/index'],
        resolve: {
          phaseTasks: ['$stateParams', 'taskData',
            function( $stateParams, taskData ){
              return taskData.getPhaseTasks($stateParams.phase_id);
          }]
        },
        controller: 'taskListController'
      })
      .state('phase.task', {
        url: "/tasks/:task_id",
        template: JST['layouts/admin/flows/tasks/show'],
        resolve: {
          task: ['$stateParams', 'phaseTasks',
            function( $stateParams, phaseTasks ){

              // phaseTasks is empty Array

          }]
        },
        controller: 'taskController'
      })
}]);

flowAdminApp.factory('taskData', [ '$resource',
  function ($resource) {
    return {
      getPhaseTasks: function (phase_id) {
        return $resource('/admin/tasks.json?phase_id=:phase_id', {phase_id:'@phase_id'}).query({phase_id:phase_id});
      }
    }
}]);

When I changed my code that parent data are static, then "phaseTasks" passed to child route correctly.
flowAdminApp.config(['$stateProvider', '$urlRouterProvider',
  function($stateProvider, $urlRouterProvider){

$stateProvider
  .state('phase', {
    url: "/phases/:phase_id",
    template: JST['layouts/admin/flows/tasks/index'],
    resolve: {
      phaseTasks: ['$stateParams',
        function( $stateParams ){
          return [{a: 1}]
      }]
    },
    controller: 'taskListController'
  })
  .state('phase.task', {
    url: "/tasks/:task_id",
    template: JST['layouts/admin/flows/tasks/show'],
    resolve: {
      task: ['$stateParams', 'phaseTasks',
        function( $stateParams, phaseTasks ){

          // phaseTasks is [{a: 1}]

      }]
    },
    controller: 'taskController'
  })
}]);

How to pass data (retrieved from server) from parent route to its child route or prevent child route loading until parent route data are retrieved from database ?

A: Try to implement your getPhaseTasks service method using a promise
flowAdminApp.factory('taskData', [ '$resource','$q'
  function ($resource,$q) {
    return {
      getPhaseTasks: function (phase_id) {
        var defer = $q.defer();
        $resource('/admin/tasks.json?phase_id=:phase_id', {phase_id:'@phase_id'})
         .query({phase_id:phase_id},
            function(data){
                defer.resolve(data);
             },
            function(error) {
                defer.reject(error);
            });
        return defer.promise;
      }
    }
}]);

I think the problem currently is that the $resource api is async in nature and returns an array, which gets filled in the future. Since there is no promise available for your $state routes the resolve function does not wait.


Q: Xpath selector does not work I'm quite new in XPath and I can't figure out what's wrong with this selector:
'//div[@id="records"].//div[@class="record"]'

The structure html:
The thing is that I want to get all <div class="record"> elements.
What's wrong please?
EDIT: Elaborated snippet:

A: your xpath
wrong syntax, just get rid of the "." and you'll get all the div elements with attribute class="record"
'//div[@id="records"]//div[@class="record"]'

if (as you said in the comments) you want to get all anchor elements then try this xpath:
'//div[@id="records"]/div[@class="record"]/a[contains(@href,"firma")]'


Q: What is the Dojo Equivalent to Button Click In JavaScript -  If I want to fire a button I do this -
<button type = 'button' id='myButton'>HiddenButton</button>

When I want to fire this button click, say, onChange of a text field -
<input type= 'text' onchange ='callAutoClick()'/>

I am not able to do the same in DOJO. I have found a solution using Javascript -
var divId = document.getElementById('myDivID');
divId.getElementsByTagName("button")[0].click();

But I don't want to have the dependency with the DivID. Is it possible to click a button just knowing the button's controlID. All I could find online were methods to define an OnClick() using dojo for a button and not clicking the button itself.
Plus I am designing the page with a BPM Tool so on including sections the DivID changes. When I open the page in FireBug I can see this -

<button class="BPMButton BPMButtonBorder" type="button">Hidden_Cancel</button>

If you guys could suggest me a way to access the DOM object using the data-viewId also it would cater to my need.
Thanks in advance :)

A: You can use dojo/query:

function progClick() {
  require(["dojo/query"], function(query) {
    query("div[data-viewid=myViewId] > button").forEach(function(node) {
      node.click();
    });
  });
}

  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.10.1/dijit/themes/claro/claro.css">

    <button type="button" onclick="alert('my button got clicked!')">My Button</button>

  <button type="button" onclick="progClick()">Programatically Click My button</button>


Q: Expand one card on click Currently using Material-UI-React for the first time to build out cards that expand, the issue I'm running into is when I click on one card to expand, they all expand.How can I refactor my code to only allow the card that is clicked on to expand not affecting the others?

const useStyles = makeStyles(theme => ({
  card: {
    maxWidth: 300
  },
  media: {
    height: 0,
    paddingTop: '56.25%' // 16:9
  },
  expand: {
    transform: 'rotate(0deg)',
    marginLeft: 'auto',
    transition: theme.transitions.create('transform', {
      duration: theme.transitions.duration.shortest
    })
  },
  expandOpen: {
    transform: 'rotate(180deg)'
  }
}));

const HomePageCards = props => {
  console.log(props);
  const classes = useStyles();
  const [expanded, setExpanded] = React.useState(false);

  function handleExpandClick() {
    setExpanded(!expanded);
  }
  return (
    <Card className={classes.card}>
      <CardHeader title={props.title} subheader={`User: ${props.username}`} />
      <CardMedia
        className={classes.media}
        image='https://source.unsplash.com/1600x900/?crafts'
        title={props.title}
      />
      <CardContent>
        <Typography variant='body2' color='textSecondary' component='p'>
          {props.description}
        </Typography>
      </CardContent>
      <CardActions disableSpacing>
        <IconButton
          className={clsx(classes.expand, {
            [classes.expandOpen]: expanded
          })}
          onClick={handleExpandClick}
          aria-expanded={expanded}
          aria-label='show more'
        >
          <ExpandMoreIcon />
        </IconButton>
      </CardActions>
      <Collapse in={expanded} timeout='auto' unmountOnExit>
        <CardContent>
          <Typography paragraph>Method:</Typography>
          <Typography paragraph>
            Step 1:
            {props.step_1}
          </Typography>
          <Typography paragraph>
            Step 2:
            {props.step_2}
          </Typography>
          <Typography paragraph>
            Step 3:
            {props.step_3}
          </Typography>
          <Typography>
            Step 4:
            {props.step_4}
          </Typography>
          <Typography>
            Step 5:
            {props.step_5}
          </Typography>
        </CardContent>
      </Collapse>
    </Card>
  );
};

import React, { useEffect, useState } from 'react';
import Axios from 'axios';

import HomePageCards from '../HomePageCards/HomePageCards';

const HomePage = props => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const token = localStorage.getItem('token');
    Axios.get('https://bw-how-to.herokuapp.com/guides', {
      headers: { authorization: token }
    })
      .then(res => {
        // console.log('Data', res.data);
        setUsers(res.data);
      })
      .catch(err => console.error(err));
  }, []);

  return (

      {users.map(user => (
        <HomePageCards {...user} key={user.id} />
      ))}

  );
};

export default HomePage;

I looked around but can't seem to find the solution. Any suggestions or guidance would be greatly appreciated. Thank you in advance.


Q: Contact Form 7 allow in HTML tag area How can I enable contact form 7 shortcode in HTML area( Where only allow html tag ) .
[contact-form-7 id="2358" title="Contact Form 1"]
Actually, I would like to allow 3rd slide of my web site.
http://vistabrand.com/

A: You can output it in php like this
<?php echo do_shortcode( '[contact-form-7 id="617" title="capta contact form"]' ); ?>

Search on web little bit before posting, Search on web little bit before posting,
 I found this on Google.


Q: Can I control visibility of generated protobuf-classes in Java? I found an answer for .NET, but can't find a way for Java. I'd like to set the visibility of the generated protobuf-classes automatically to private.
Currently, when I compile my .proto-Files, everything is set to public.


Q: Only a part of data ca be inserted into csv I want to insert all data which I scrape from web into csv, but only a part of info can be inserted!
why this happen
should I use MySQL database instead of csv
And I want to connect this csv file to web browser by using flask.
plus when I insert many import text like "import re" into top of the function "input_to_output(site,oc,id,place,pg)" after "import csv" , I can not import most of them. Is this because csv method do something?
The most thing I want to know is the first one why only a part of data can be inserted.
def townwork_page(oc,place,pg):
    import csv
    import re
    from bs4 import BeautifulSoup
    import requests
    name_list=[]
    ac={"":"","北海道":"101","青森":"110","東京":"041","茨城":"047","千葉":"043","埼玉":"044","群馬":"045","神奈川":"042","栃木":"046",\
    "秋田":"110","岩手":"109","山形":"108","宮城":"106","福島":"107","静岡":"600","愛知":"081","岐阜":"085","山梨":"118","新潟":"117","福井":"124",\
    "長野":"116","滋賀":"064","富山":"122","石川":"123","三重":"084","奈良":"065","和歌山":"066","京都":"063","大阪":"061","兵庫":"062","鳥取":"133",\
    "島根":"134","岡山":"132","佐賀":"441","山口":"135","広島":"131","香川":"136","徳島":"138","愛媛":"137","高知":"139","福岡":"440","長崎":"442",\
    "大分":"444","熊本":"443","宮崎":"445","鹿児島":"446","沖縄":"447"}
    jc={"":"","IT/コンピュータ":"005","営業":"009","専門職/その他":"017","レジャー/エンタメ":"011","接客/サービス":"010","物流/配送":"012","建築/土木":"013","教育":"014"\
    ,"医療/介護/福祉":"015","飲食/フード":"001","販売":"002","事務":"003","総務/企画":"004","IT/コンピュータ":"005","軽作業":"018","芸能":"008","マスコミ/出版":"007",\
    "工場/製造":"019"}
    if any([oc not in jc, place not in ac]):
        print("Input collectlly!")
        return ""
    if type(oc)==str:
        oc=oc,""
    if type(place)==str:
        place=place,""
    url_form="https://townwork.net/joSrchRsltList/?"
    if oc:
        for i in oc:
            if i:
                url_form+="jc="+jc[i]+"&"
    if place:
        for j in place:
            if j:
                url_form+="ac="+ac[j]+"&"
    if pg:
        for l in range(1,pg+1):
            url_form+="pg="+str(l)+"&"
            if url_form[-1]=="&":
                url_form=url_form[:-1]
                res=requests.get(url_form)
                soup=BeautifulSoup(res.text,"html.parser")
                company_name=soup.findAll(class_="job-lst-main-ttl-txt")
                for i in company_name:
                    if i.get_text().split() not in name_list:
                        name_list.append(i.get_text().split())
    return name_list
def input_to_output(site,oc,id,place,pg):
    import csv
    if site=="タウンワーク":
        with open ("output.csv","w+",newline='',encoding="utf-8") as csvFile:
            try:
                writer=csv.writer(csvFile,lineterminator='\n')
                writer.writerow(["information"])
                for line in townwork_page(oc,place,pg):
                    writer.writerow(line)
            finally:
                csvFile.close()
    elif site=="食べログ":
        with open ("output.csv","w+",newline='') as csvFile:
            try:
                writer=csv.writer(csvFile)
                writer.writerow(("information"))
                writer.writerow((tabelog_page(place,pg)))
            finally:
                csvFile.close()
    else:
        print("write collectlly!")

input_to_output("タウンワーク","営業","","北海道",10)

scraping site is "タウンワーク".
Is there any grammer problem


Q: How to implement Google's DoubleClick Ads in an android application? How do we implement google's double click for displaying ads in our android application?
Can someone provide me steps that needs to be followed to implement the same.
Thanks in advance

A: Check this link -  http://code.google.com/mobile/afma_ads/docs/ it explains it all (well most of it to get started!)

I went on a similar path looking for a ad serving support in my android app - eventually I settled for Mobclix - I am happy :-)  Check the question I had posed at  Serving Ads in Android App -


Q: Chrome Packaged App: Open Website in New Tab I'm updating one of my chrome apps to just launch the web app (why? I don't have the time to continue updating the chrome app, alone with the desktop apps for offline use)
Here's what the manifests starts with...
"app": {
   "background": {
      "scripts": [ "background.js" ]
   }
},

I just want it to open a new tab to the website now instead of launching a packaged app. So I tried the following...
"app": {
   "launch": {
      "web_url": "http://stackoverflow.com/"
   }
},

An error occurred: Failed to process your item.
Please specify background subsection of app section in the manifest.
"app": {
   "launch": {
      "web_url": "http://stackoverflow.com/"
   },
   "background": {
      "scripts": [ "background.js" ]
   }
},

An error occurred: Failed to process your item.
Application specifications for packaged and hosted apps are incompatible. Please refer to manifest specification.
The manifest may not contain a launch object inside the app object.
So I decided to stick with just the background script and try to just create a new tab that way.
background.js
chrome.app.runtime.onLaunched.addListener(function(launchData) {
  chrome.app.window.create(
    'index.html',
    {
      id: 'mainWindow',
      innerBounds: {
        'width': 800,
        'height': 600
      }
    }
  );
});

index.html
<script>
  var a    = document.createElement("a")
  a.href   = "http://stackoverflow.com/"
  a.target = "_blank"
  document.body.appendChild(a)
  a.click()
</script>

I was finally able to successfully add a new tab with...
chrome.app.runtime.onLaunched.addListener(function(launchData) {
  window.open("http://stackoverflow.com/")
})

in my background.js script.
However the following error occurs...

I clicked on the "Learn More" button but that too gave me the same "Aw, Snap!" page
Does anyone know why I can't open a new tab in a chrome packaged app?
and
How am I suppose to open a new tab in a chrome packaged app?

A: Use chrome.browser.openTab({ url: "" }, callback) with the "browser" permission.
https://developer.chrome.com/apps/browser#method-openTab


Q: Other Users Cannot Connect to SQL Data Connection I have been banging my head for hours now trying to figure out this issue.  Currently, I have an Excel 2013 file that I created with a few pivot charts.  The pivot charts are connected to SQL Server 2012.  I personally can refresh the data without any issues on my end, however whenever someone else tries to
open the database connection they receive the following error.  I have tested this on multiple users and each one experiences the same error.  Any suggestions on what's going on here?

A: Either your users need to instal the same SQL Server driver you use, or you need to change yours to match their drivers:
https://support.microsoft.com/en-us/help/2022518/error-message-class-not-registered-when-you-update-powerpivot-data


Q: objective c setter method memory management I have question about allocating and releasing objects:
if I have code like this:
MyObject *object = [[MyObject alloc] init];
NSMutableString *string = [[NSMutableString alloc]initWithString:@"bla"];
object.myString = string;
NSLog(@"retain count: %d",[object.myString retainCount]); //gives me 2
[string release];
NSLog(@"retain count: %d",[object.myString retainCount]); //gives me 1

Than I have exactly what I want. I need just one reference and I have retain count 1
but
if I use
object.myString = [[NSMutableString alloc]initWithString:@"bla"];

my property look like this:
@property (nonatomic,retain) NSMutableString *myString;

one alloc, and one setter method with retain gives me as retain count 2
If I release the object after resignment than the app crashes. I dont know why?
So , do i have to always create an object with a temporary reference, than assign to real reference and release the temp reference like first code?
or is there any other way?

A: Yes and no.  Generally, this is a common pattern:
// create the object, retain count 1
MyObject *myObject = [[MyObject alloc] init];

// increment the retain count in the setter
self.myObjectProperty = myObject;

// let go of the object before the end of the current method
[myObject release];

You can avoid the release, sort of, by using autorelease pools.  More accurately, you indicate that you want the object to be released soon:
MyObject *myObject = [[[MyObject alloc] init] autorelease];
self.myObjectProperty = myObject;

// all done!

With many of the Apple-provided classes, you can use class methods other than alloc/init to get objects that are already autoreleased.  Your example could be rewritten as:
MyObject *myObject = [[MyObject alloc] init];
myObject.myString = [NSMutableString stringWithFormat:@"bla"];

A final note: -retainCount is a blunt object.  Particularly with NSStrings and other built-in classes, it may return results that are quite different from what you expect.  Generally you should avoid it.


Q: C# anonymous method/block? I cannot understand this piece of code what is the "ViewDissapearing"? And what about "add" and "remove" blocks?
public event EventHandler ViewDisappearing;

public event EventHandler ViewDissapearing {
    add {
        ViewDisappearing += value;
    }
    remove {
        ViewDisappearing -= value;
    }
}

A: This is done to provide two names for the same event. "ViewDissapearing" is how the event was previously wrongly named, and all existing code that subscribes to the "ViewDissapearing" event is instead rerouted to subscribe to the new correctly spelt "ViewDisappearing" event instead.
The add { ... } block is executed when someone calls ViewDissapearing += ..., which does nothing more than ViewDisappearing += that same .... Similarly for the remove { ... } block and -=.

A: This is to allow other code to attach to this event. This is the same idea as the Get / Set Property of a variable. For Events it is Add / Remove. As with Properties of variables, you can use the Variable directly, or you can use an Property. You usually use the Properrty if you want to add some custom code when adding a event.

A: This is explicitly stating what is normally autogenerated by the compiler for an event in a class.


Q: How do I convert quaternion values to specific angles I'm getting quaternion values, and I want to convert these values to 2 angles.
One of the angles is between the "ground plane" (please correct me if this is an incorrect name for it) and the fictional vector between the origin and the quaternion point ( the complementary angle of gamma ).
The second angle is the rotational angle, this is the rotation that the vector has made relatively to a plane perpendicular to the vector ( R in the picture ).
I looked lot up on the internet, but everything I try has a range of -90° to 90°, while I want it to go from -180° to 180°.
This is the last version of code I ended up with:
float gx = 2 * (x*z - w*y);
float gy = 2 * (w*x + y*z);
float gz = w*w - x*x - y*y + z*z;
float yaw = atan2(2*x*y - 2*w*z, 2*w*w + 2*x*x - 1); // about Z axis
float pitch = atan(gx / sqrt(gy*gy + gz*gz)); // about Y axis
float roll = atan(gy/gz); // about X axis

Serial.print("  yaw ");
Serial.print(yaw * 180/M_PI,0);
Serial.print("  pitch ");
Serial.print(pitch * 180/M_PI,2);
Serial.print("  sideways ");
// Don't mind this section as I'm applying a mathematical function I created
if(pitch > 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,((pitch * 180/M_PI)-51.57)))), 2);
else if(pitch == 0) Serial.println(roll * 180/M_PI, 2);
else if(pitch < 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,(((pitch) * (-180)/M_PI)-51.57)))), 2);

A:
You should always use atan2(y,x) instead of atan(y/x). It is a common mistake. – Somos

He wrote this on a math form were I asked this too, and that was my stupid mistake -_-
My new version is:
float gx = 2 * (x*z - w*y);
float gy = 2 * (w*x + y*z);
float gz = w*w - x*x - y*y + z*z;
float yaw = atan2(2*x*y - 2*w*z, 2*w*w + 2*x*x - 1); // about Z axis
float pitch = atan2(gx, sqrt(gy*gy + gz*gz)); // about Y axis
float roll = atan2(gy, gz); // about X axis

/*Serial.print("  yaw ");
Serial.print(yaw * 180/M_PI,0);*/
Serial.print("  pitch ");
Serial.print(pitch * 180/M_PI,2);
Serial.print("  sideways ");
// Please don't pay  attention to the extra function I made for the project but it doesn't have to do with the problem
if(pitch > 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,((pitch * 180/M_PI)-51.57)))), 2);
else if(pitch == 0) Serial.println(roll * 180/M_PI, 2);
else if(pitch < 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,(((pitch) * (-180)/M_PI)-51.57)))), 2);


Q: Navigation based application without a uitableview error I do this:
First create navigation based application.
Then delete UITableView from rootViewController.xib, add a UIView connect it to File's Owner.
Change UITableView to UIViewController in RootViewcontroller.h
Finally clean all methods of UITableView in RootViewcontroller.m
But when I run the project receives this error:
-[RootViewcontroller tableView:numberOfRowsInSection:]:unreconized selector sent to instance

What am I doing wrong?

A: There are a few possibility.

*

*Make sure that UITableView protocol is implemented in the header file.
Eg @interface TestingViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

*Check that your connection from in the Interface Builder and make sure its linked properly


Q: Grammaticality of "the near-term pain a trade battle would impose on U.S. workers will prove worthwhile" In the last August edition of TIME Magazine, I stumbled across this sentence. I am not a native speaker and am interested whether the unusual structure without any comma is correct. I am also unsure about the meaning of the word impose in this context.

But there's a catch for the Trump team. If you want to be sure the near-term pain a trade battle would impose on U.S. workers will prove worthwhile in the long run, you'd better have allies — both political and military.

A: “the near-term pain a trade battle would impose on U.S. workers will prove worthwhile...”
Can be rewritten as “the pain that a trade battle would put on US workers will be worth it.”


Q: Creating LRS dataset from line feature class with route IDs, from and to measures using ArcGIS Pro I am using ArcGIS Pro 2.9.3 with the Location Referencing extension.
I am trying to create an LRS dataset so that I can start using the Location Referencing tab on the ribbon to edit routes.  I have a line feature class (testFC) with fields for RouteID, FromMeasure and ToMeasure that I can easily create a route feature class from but that does not make the Location Referencing tab become available.
My test data is simple - see picture below:

I use the code below to create the test data above (testFC), an empty LRS dataset (testLRS), and an intermediate feature dataset (testFD) into which I've copied testFC as intermediateFC as well as the empty Calibration_Point and Redline feature classes from testLRS because they need to be there to use the Create LRS From Existing Dataset tool.
import arcpy

arcpy.env.overwriteOutput = True

# Create empty feature class and its schema
sr = arcpy.SpatialReference("GCS_WGS_1984")
arcpy.management.CreateFileGDB(r"C:\temp","test")
arcpy.management.CreateFeatureclass(r"C:\temp\test.gdb","testFC","POLYLINE")
arcpy.management.DefineProjection(r"C:\temp\test.gdb\testFC",sr)
arcpy.management.AddField(r"C:\temp\test.gdb\testFC","RouteID","LONG")
arcpy.management.AddField(r"C:\temp\test.gdb\testFC","FromMeasure","DOUBLE")
arcpy.management.AddField(r"C:\temp\test.gdb\testFC","ToMeasure","DOUBLE")

# Write two lines and their attributes to the feature class
cursor = arcpy.da.InsertCursor(r"C:\temp\test.gdb\testFC",["SHAPE@","RouteID","FromMeasure","ToMeasure"])
array = arcpy.Array([arcpy.Point(0.0,0.0),
                     arcpy.Point(0.0,1.0)])
polyline = arcpy.Polyline(array,sr)
cursor.insertRow([polyline,1,0.0,1.0])
array = arcpy.Array([arcpy.Point(0.0,1.0),
                     arcpy.Point(1.0,1.0)])
polyline = arcpy.Polyline(array,sr)
cursor.insertRow([polyline,2,1.0,2.0])
del cursor

# Create empty TestLRS dataset and TestLRSNetwork for testing, and copying schema from
# Create empty LRS dataset (TestLRS), with default names for three feature classes (Calibration_Point,Centerline,
# Redline) and an LRS Hierarchy (TestLRS) within it, and three tables (Centerline_Sequence, Lrs_Edit_Log,Lrs_Locks)
gdb = r"C:\temp\test.gdb"
if arcpy.Exists(r"{0}\{1}".format(gdb,"TestLRS")):
    arcpy.management.Delete(r"{0}\{1}".format(gdb,"TestLRS"))
if arcpy.Exists(r"{0}\{1}".format(gdb,"Centerline_Sequence")):
    arcpy.management.Delete(r"{0}\{1}".format(gdb,"Centerline_Sequence"))
if arcpy.Exists(r"{0}\{1}".format(gdb,"Lrs_Edit_Log")):
    arcpy.management.Delete(r"{0}\{1}".format(gdb,"Lrs_Edit_Log"))
if arcpy.Exists(r"{0}\{1}".format(gdb,"Lrs_Locks")):
    arcpy.management.Delete(r"{0}\{1}".format(gdb,"Lrs_Locks"))
if arcpy.Exists(r"{0}\{1}".format(gdb,"TestLRS")):
    arcpy.management.Delete(r"{0}\{1}".format(gdb,"TestLRS"))
print("Creating LRS dataset named {0}".format("TestLRS"))
arcpy.locref.CreateLRS(gdb,"TestLRS","Centerline","Calibration_Point","Redline","Centerline_Sequence",sr,
                       "8.98315284119521E-09 DecimalDegrees","0.001 Meters",
                       "0.000000001 DecimalDegrees","0.0001 Meters")
print("Creating LRS Network ({0}) in LRS dataset ({1}".format("TestLRSNetwork","TestLRS"))
arcpy.locref.CreateLRSNetwork(gdb, "TestLRS", "TestLRSNetwork",
                              "RouteId", "RouteName", "FromDate", "ToDate", "DO_NOT_DERIVE", '',
                              "DO_NOT_INCLUDE", "LineId", "LineName", "LineOrder", "KILOMETERS")

print("Creating intermediate feature dataset")
arcpy.management.CreateFeatureDataset(gdb,"IntermediateFD")
arcpy.management.DefineProjection(r"{0}\{1}".format(gdb,"IntermediateFD"),sr)
print("Copying testFC into IntermediateFD as IntermediateCL")
arcpy.management.CopyFeatures(r"C:\temp\test.gdb\testFC",r"C:\temp\test.gdb\IntermediateFD\IntermediateFC")
emptyCalibrationFC = r"{0}\{1}\Calibration_Point".format(gdb,"TestLRS")
intermediateCalibrationFC = r"{0}\{1}\IntermediateCalibration".format(gdb,"IntermediateFD")
arcpy.management.CopyFeatures(emptyCalibrationFC,intermediateCalibrationFC)
emptyRoutelineFC = r"{0}\{1}\Redline".format(gdb,"TestLRS")
intermediateRoutelineFC = r"{0}\{1}\IntermediateRedline".format(gdb,"IntermediateFD")
arcpy.management.CopyFeatures(emptyRoutelineFC,intermediateRoutelineFC)

After running the code above my test.gdb looks like this:

I think I now have what is needed to create a FinalLRS using the Create LRS From Existing Dataset tool but when I start to use them to populate its parameters I get three warnings:

*

*WARNING 130172 which I suspect will be easy to address by making testFC (and therefore IntermediateFC) z-aware.

*WARNING 130010 telling me "The field has not been mapped" which I do not yet know how to address.

*WARNING 130018 telling me "The chosen dataset is already being used with another LRS" which I suspect is correct but I do not yet know how to address it.

When I try to Run the tool it bails out because I've not addressed the first warning.
Before I expend more effort trying to address each of the three warnings, is there another (hopefully much simpler) way to create an LRS dataset from a "route-ready" line feature class (like my testFC with fields for RouteID, FromMeasure and ToMeasure)?
I am trying separately to find additional documentation/help via the Esri Community at Creating LRS Dataset from existing line/route feature class.

A: It took more effort than I originally anticipated but I ended up getting measured routes in an LRS dataset and network, as seen below, from test data generated and processed using the code and output that follows.

# This script is intended to create an empty LRS dataset and load
# the geometries of a test polyline feature class with route IDs (TEXT),
# Route Names (TEXT) and from/to measures (DOUBLE) into it so that an
# LRS Network with those routes can be created
import arcpy

arcpy.env.overwriteOutput = True

# Establish coordinate system and geodatabase to be used
srWGS84 = arcpy.SpatialReference("GCS_WGS_1984")
workingFolder = r"C:\temp"
gdbName = "test"
gdb = r"{0}\{1}.gdb".format(workingFolder,gdbName)
lrsName = "TestLRS"
lrsFD = r"{0}\{1}".format(gdb,lrsName)
testFCName = "testFC"
testFC = r"{0}\{1}".format(lrsFD,testFCName)
testStatsTableName = "testStats"
testStatsTable = r"{0}\{1}".format(gdb,testStatsTableName)
testDissolvedFC = r"{0}{1}".format(testFC,"_Dissolve")
calibrationFC = r"{0}\{1}".format(lrsFD,"Calibration_Point")
centerlineFC = r"{0}\{1}".format(lrsFD,"Centerline")
lrsNetworkName = "testLRSNetwork"
lrsNetworkFC = r"{0}\{1}".format(lrsFD,lrsNetworkName)
redlineFC = r"{0}\{1}".format(lrsFD,"Redline")
centerlineSequenceTable = r"{0}\{1}".format(gdb,"Centerline_Sequence")
newCalibrationPointsFCName = "NewCalibrationPoints"
newCalibrationPointsFC = r"{0}\{1}".format(lrsFD,newCalibrationPointsFCName)
newCalibrationPointsFCTempName = newCalibrationPointsFCName+"Temp"
newCalibrationPointsFCtemp = r"{0}\{1}".format(lrsFD,newCalibrationPointsFCTempName)
uniqueCalibrationPointsFCName = "UniqueCalibrationPoints"
uniqueCalibrationPointsFC = r"{0}\{1}".format(lrsFD,uniqueCalibrationPointsFCName)

# Create empty geodatabase for testing
arcpy.management.CreateFileGDB(workingFolder,gdbName)

# Create empty TestLRS dataset with default names for three feature classes
# (Calibration_Point,Centerline,Redline) and an LRS Hierarchy (TestLRS)
# within it, and three tables (Centerline_Sequence, Lrs_Edit_Log,Lrs_Locks)
print("Creating LRS dataset named {0} in {1}".format(lrsName,gdb))
arcpy.locref.CreateLRS(gdb,lrsName,"Centerline","Calibration_Point",
                       "Redline","Centerline_Sequence",srWGS84)

# Prepare feature class from which routes will be appended into the LRS Network later
# Create empty feature class and its schema
print('Creating "route-ready" polyline feature class ({0}) in LRS dataset ({1})'.format(testFC,lrsFD))
arcpy.management.CreateFeatureclass(lrsFD,"testFC","POLYLINE")
arcpy.management.AddField(testFC,"RouteID","TEXT", None, None, 10)
arcpy.management.AddField(testFC,"RouteName","TEXT", None, None, 10)
arcpy.management.AddField(testFC,"FromMeasure","DOUBLE")
arcpy.management.AddField(testFC,"ToMeasure","DOUBLE")
arcpy.management.AddField(testFC,"FromDate","DATE")
arcpy.management.AddField(testFC,"ToDate","DATE")
# Write three polylines and their route attributes to the feature class
cursor = arcpy.da.InsertCursor(testFC,["SHAPE@","RouteID","RouteName","FromMeasure","ToMeasure"])
array = arcpy.Array([arcpy.Point(0.0,0.0),
                     arcpy.Point(0.0,1.0)])
polyline = arcpy.Polyline(array,srWGS84)
cursor.insertRow([polyline,"Route1","Route 1",0.0,750.0])
array = arcpy.Array([arcpy.Point(0.0,1.0),
                     arcpy.Point(1.0,1.0)])
polyline = arcpy.Polyline(array,srWGS84)
cursor.insertRow([polyline,"Route1","Route 1",750.0,2000.0])
array = arcpy.Array([arcpy.Point(1.0,1.0),
                     arcpy.Point(1.0,0.0)])
polyline = arcpy.Polyline(array,srWGS84)
cursor.insertRow([polyline,"Route2","Route 2",0.0,999.0])
del cursor
arcpy.management.CalculateField(testFC, "FromDate", "datetime.datetime.now()", "PYTHON3", '', "TEXT", "NO_ENFORCE_DOMAINS")
print('Writing statistics from polyline feature class ({0}) into table ({1})'.format(testFC,testStatsTable))
arcpy.analysis.Statistics(testFC,testStatsTable,"FromMeasure MIN;ToMeasure MAX","RouteID")

# Dissolve testFC so that there's only one polyline per route
print("Dissolving {0} primarily on RouteID to create {1}".format(testFC,testDissolvedFC))
arcpy.management.Dissolve(testFC,testDissolvedFC,
                          "RouteID;RouteName;FromDate;ToDate",
                          None, "SINGLE_PART", "UNSPLIT_LINES")
arcpy.management.JoinField(testDissolvedFC,"RouteID",testStatsTable,"RouteID","MIN_FromMeasure;MAX_ToMeasure")

# Create empty TestLRSNetwork in TestLRS dataset
print("Creating LRS Network ({0}) in LRS dataset ({1})".format("TestLRSNetwork","TestLRS"))
arcpy.locref.CreateLRSNetwork(gdb, "TestLRS", "TestLRSNetwork",
                              "RouteID", "RouteName", "FromDate", "ToDate", "DO_NOT_DERIVE", '',
                              "DO_NOT_INCLUDE",None,None,None,"METERS")
lrsNetworkFC = r"{0}\{1}".format(lrsFD,"TestLRSNetwork")

# Append routes from testFC into TestLRSNetwork which should append them into Centerline feature class at the same time
routeCount = arcpy.management.GetCount(testDissolvedFC)[0]
print("Appending {0} Routes from {1}\n into LRS Network ({2}) in LRS dataset ({3})".format(routeCount,testDissolvedFC,"TestLRSNetwork","TestLRS"))
arcpy.locref.AppendRoutes(testDissolvedFC,lrsNetworkFC, "RouteID", "RouteName", "FromDate", "ToDate",
                          None,None,None, None, "ADD")

# Generating calibration points and calibrating routes using them
arcpy.locref.GenerateCalibrationPoints(testDissolvedFC,"RouteID","FromDate","ToDate",calibrationFC,
                                       lrsNetworkName, "DIGITIZED_DIRECTION","ATTRIBUTE_FIELDS","MIN_FromMeasure","MAX_ToMeasure")
calPointCount = arcpy.management.GetCount(calibrationFC)[0]
print("Using {0} calibration points to generate measures on routes in LRS Network".format(calPointCount))
arcpy.locref.GenerateRoutes(lrsNetworkFC,"NO_RECORD_CALIBRATION_CHANGES")

# Clean up intermediate data
print(r"Deleting intermediate data")
for itm in [testStatsTableName]:
    if arcpy.Exists(r"{0}\{1}".format(gdb,itm)):
        print(r"Deleting {0}\{1}".format(gdb,itm))
        arcpy.management.Delete(r"{0}\{1}".format(gdb,itm))
for itm in [testFC,testDissolvedFC]:
    if arcpy.Exists(itm):
        print(r"Deleting {0}".format(itm))
        arcpy.management.Delete(r"{0}".format(itm))

Start Time: Tuesday, 5 July 2022 9:45:33 AM
Creating LRS dataset named TestLRS in C:\temp\test.gdb
Creating "route-ready" polyline feature class (C:\temp\test.gdb\TestLRS\testFC) in LRS dataset (C:\temp\test.gdb\TestLRS)
Writing statistics from polyline feature class (C:\temp\test.gdb\TestLRS\testFC) into table (C:\temp\test.gdb\testStats)
Dissolving C:\temp\test.gdb\TestLRS\testFC primarily on RouteID to create C:\temp\test.gdb\TestLRS\testFC_Dissolve
Creating LRS Network (TestLRSNetwork) in LRS dataset (TestLRS)
Appending 2 Routes from C:\temp\test.gdb\TestLRS\testFC_Dissolve
 into LRS Network (TestLRSNetwork) in LRS dataset (TestLRS)
Using 4 calibration points to generate measures on routes in LRS Network
Deleting intermediate data
Deleting C:\temp\test.gdb\testStats
Deleting C:\temp\test.gdb\TestLRS\testFC
Deleting C:\temp\test.gdb\TestLRS\testFC_Dissolve
Succeeded at Tuesday, 5 July 2022 9:47:08 AM (Elapsed Time: 1 minutes 34 seconds)


Q: Datepicker Javafx I am facing difficulty in date picker implementation (JAVAFX). I need these characters in my date picker I want to restrict only numeric input and a specific length of input in the date picker.It should have fixed / / in it which cannot be removed by user.


Q: selenium.webdriver.firefox.firefox_profile.AddonFormatError: ("[Errno 2] No such file or directory: import time
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.options import Options
binary = FirefoxBinary('/usr/bin/firefox/firefox')
ffprofile = webdriver.FirefoxProfile()
ffprofile.add_extension('/home/user/Desktop/exten/stylish.xpi')
driver = webdriver.Firefox(firefox_binary=binary, firefox_profile=ffprofile)  # firefox_options=options)
link = driver.get('https://www.youtube.com/watch?v=fDrTbLXHKu8')

Получаю :

selenium.webdriver.firefox.firefox_profile.AddonFormatError: ("[Errno 2] No such file or directory: '/tmp/tmpttv3ykej.stylish.xpi/install.rdf'", )

В чём моя ошибка?

A: Подозреваю, что вы используете одну из версий Firefox Quantum (с 57-й версии включительно). На новом движке метаданные расширения хранятся не в файле install.rdf, а в файле manifest.json. В том собственно и проблема, Selenium ещё не умеет работать с новыми расширениями (научиться только в версии 3.14), и поэтому ищет внутри архива расширения файл install.rdf.
Вот тут
автор поста написал класс который несколько изменяет процедуру поиска метаданных в подключаемом расширении, благодаря чему selenium тянет инфу уже из manifest.json.
То есть, вам нужно:
# Добавить импорт
import json
import os
import sys
from selenium.webdriver.firefox.firefox_profile import AddonFormatError

# Добавить класс изменяющий процедуру поиска метаданных
class FirefoxProfileWithWebExtensionSupport(webdriver.FirefoxProfile):
    def _addon_details(self, addon_path):
        try:
            return super()._addon_details(addon_path)
        except AddonFormatError:
            try:
                with open(os.path.join(addon_path, 'manifest.json'), 'r') as f:
                    manifest = json.load(f)
                    return {
                        'id': manifest['applications']['gecko']['id'],
                        'version': manifest['version'],
                        'name': manifest['name'],
                        'unpack': False,
                    }
            except (IOError, KeyError) as e:
                raise AddonFormatError(str(e), sys.exc_info()[2])

# Объявить профиль Firefox не FirefoxProfile(), а созданным классом
profile = FirefoxProfileWithWebExtensionSupport()

Всё остальное продолжить делать как и раньше)))
Удачи)


Q: Android: best way(9 patch or gradient shape in xml) to draw two gradients(see screenshot)
I need to add background to a textview, the background has two parts: top half is a gradent from color A to B, bottom part is a gradient from color C to D and B does not equal to C, it is actually a semi-transparent shadow, I intentionally put an orange layer underneath it to make it clear to see.
I am looking for the best way to do it, using shape/gradient only allows me setting startColor, centerColor and endColor but I need for color points. Using 9 patch is a bit complicated. Or can I merge two gradients together so each has two colors and together give me four colors?
Thanks!

A: 9 patch seems the simplest way to achieve what you want. And I believe, it would generate less computations to display your image.
9 patch is not so complicated, even easy. Did you try the android 9 patch tool?


Q: yii active record join models Using Yii framework.
I have 3 models.
Articles - table articles(id, name)
ArticlesToAuthors - table articles_to_authors (id, article_id, author_id, type)
Authors - table authors (id, name)
I need to get authors.*, article_to_authors.type for specific article_id.
I was trying to make relation in ArticlesToAuthors model like that:
'authors'  => array(self::HAS_MANY, 'Authors', array('id' => 'author_id'), ),

then i made query:
$authors = ArticlesToAuthors::model()->with('authors')->findAll(array('condition' => 'article_id=2217') );

foreach($authors as $a)
{
     //this is not working
     #var_dump($a->authors->name);
         #var_dump($a->name);

     //this works fine
     foreach($a->authors as $aa)
     {
            var_dump($aa->name);
     }
}

*

*Can i get all active record object in one and not to do foreach in foreach?
I need an analogue to sql "SELECT atoa., a. FROM articles_to_authors atoa LEFT JOIN authors a ON atoa.author_id=a.id WHERE atoa.article_id=:article_id"

*Am i doing right?
p.s. - sorry for my bad english.

A: It looks like you need the following relations:
in your ArticlesToAuthors table:
'author' => array(self::BELONGS_TO, 'Authors', 'author_id'),
'article' => array(self::BELONGS_TO, 'Articles', 'article_id'),

and, for completeness, in your Authors table:
'articlesToAuthors'  => array(self::HAS_MANY, 'ArticlesToAuthors', array('id' => 'author_id'), ),

This should allow you to access $a->author->name. Not tested, that's just off the top of my head.


Q: Consider the six dot product of four vectors $v_1,v_2,v_3,v_4$ on $\mathbb{R}^2$. Can all of them be negative?
Consider the six dot products of four vectors $v_1,v_2,v_3,v_4$ on $\mathbb{R}^2$. Can all of them be negative?

If all dot products are negative, then the angle between each two vectors are larger than $\pi/2$. Intuitively, I don't think it's possible. But I don't know how to make a formal proof.

A: Assume this is possible. Since you are only concerned with angles between the vectors (as you correctly note, the pairwise angles must be between $\pi/2$ and $3\pi/2$), you can rotate any such system of vectors so that $v_1$ is along the $x$-axis. Then $v_2$ must be in the 2nd or 3rd quadrant.
If $v_2$ is in the third, $v_3$ cannot be in the 4th and can only be in the second. If $v_2$ is in the second, $v_3$ cannot be in the 4th so must be in the 3rd.
In summary, there is no place to put $v_4$ so that it would be more than $\pi/2$ away from other placed vectors.

A: You can do this with simple algebra. Can you first convince yourself that there is no loss of generality taking $v_1 = (1,0)$?
Suppose all the inner products are negative.
Write $v_2 = (a_2,b_2)$, $v_3 = (a_3,b_3)$, and $v_4 = (a_4,b_4)$. Compute the inner products with $v_1$ to find $a_2 < 0$, $a_3 < 0$, and $a_4 < 0$.
Since $a_2 a_3 + b_2 b_3 < 0$ and $a_2 a_3 > 0$ you get $b_2 b_3 < 0$. Likewise $b_2 b_4 < 0$ and $b_3 b_4 < 0$. This is impossible.


Q: Pyqt add 9 elements in layout and then lot of layout in group box I want to make elements in row in one layout and a lot of layouts will be in GroupBox, it must  be like this.
Result Interface
I try to release this
formLayout = QFormLayout()

for i in range(50):
    formLayout.addRow(QLabel(i), QPushButton("Start"))

groupBox.setLayout(formLayout)
self.scrollArea.setWidget(groupBox)
self.scrollArea.setWidgetResizable(True)

Result from code
I know that i should make in grib layout, because i have a lot of elements, but how can I create a layout with layouts which everyone have 9 elements?
Just explain how it should be grouped , like this scrollArea->groupBox->formLayout.addrow(elements)
I don't need full code, him I can write myself.

A: The layout you're showing is not a form layout, it could be a grid layout, but it actually seems more like a QTableView (or QTableWidget) or even a QTreeView (if those small arrows on the left are used to expand elements). Using nested layouts in this case might not be a good solution, as each layout would be independent from the others, with the result that the widgets might not be properly aligned. This small arrows for expand element in that case a QTreeView with a QStandardItemModel or a QTreeWidget might help, then use setItemWidget() to add buttons. –
musicamante


Q: Header android 9patch I would like to create a full screen header for Android.
I created the image that is 70 * 480 px (& 9patch).
how can I do?
I tried using the galaxy tab .. but it does not fill the screen horizontally.
This is the code:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:foo="http://schemas.android.com/apk/res/aaa.bbb"
    android:id="@+id/db1_root"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background">
 <ImageView
                android:src="@drawable/header"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="top"
                    >
</ImageView>

thanks in advance.

A: You need to set the android:scaleType and optionally android:adjustViewBounds.  Play around with these two attributes to get the desired effect.
http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType

A: Use this code to add your ImageView to the xml file
            <shush.android.util.AspectImageView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/header" />

Add this class:
package shush.android.util;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

/**
 * @author Sherif elKhatib
 *
 */
public class AspectImageView extends View {

    public AspectImageView(Context context) {
        super(context);
    }

    public AspectImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AspectImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = width * getBackground().getIntrinsicHeight()
                / getBackground().getIntrinsicWidth();
        setMeasuredDimension(width, height);
    }
}

A: try this
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/aaa.bbb"
android:id="@+id/db1_root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background">
<ImageView
            android:src="@drawable/header"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="top"
                >
</ImageView>


Q: How to add picture to JLabel? How to add a picture to JLabelin Java?

A: You can use ImageIcon
JLabel l = new JLabel(new ImageIcon("path-to-file"));

A: Try this code:
ImageIcon imageIcon = new ImageIcon("yourFilepth");
JLabel label = new JLabel(imageIcon);

For more Info

A: jLabel1 = new javax.swing.JLabel();
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\admin\\Desktop\\Picture 34029.jpg"));

Here i posted the code that got generated automatically in netbeans.Hope my code helps in this regards keep coding goodluck.

A: You have to supply to the JLabel an Icon implementation (i.e ImageIcon). You can do it trough the setIcon method, as in your question, or through the JLabel constructor:
Image image=GenerateImage.toImage(true);  //this generates an image file
ImageIcon icon = new ImageIcon(image);
JLabel thumb = new JLabel();
thumb.setIcon(icon);

I recommend you to read the Javadoc for JLabel, Icon, and ImageIcon. Also, you can check the How to Use Labels Tutorial, for more information.
Also have a look at this tutorial: Handling Images in a Java GUI Application


Q: How do you select the Fourth kill streak? On one of the loading screens for MW3 I noticed an "intel" text that said something similar to this: "You can choose 3 kill streaks for support, assault, or specialist. You also can choose one other kill streak that occurs regardless of your strike package"
I've heard about the M.O.A.B but this implies that you can choose your own killstreak. What exactly does it mean?

A: You can not select the fourth "M.O.A.B." kill streak for any strike package configuration.  The only way to obtain it is to get a 25 kill streak with your primary weapon, secondary weapon, equipment and/or knife.

A: It's saying that you have one extra slot to hold killstreaks obtained through other means. For example, if you took a killstreak from a care package it would be stored in that fourth slot. It's there so you can have your three killstreaks and still be able to take care packages.