text:
Q: Unable to get the Jenkins Deployment details in Hygieia Product Dashboard We have setup the Hygieia dashboard to view the all DevOps tools in one place.
I am running the hygieia collectors to get the sonar qube, gitlab commits etc. And also install Jenkins plugin for get the Jenkins Build and Deployment details.
Created application specific Teams board and Pipeline view in hygieia and able to get the sonar, gitlab, Jenkins build and Deployment details.

After created Product Dashboard to display the all application in one place. But I am only able to get the build, sonar and gitlab commit details
I am unable to get the Deployment details in Product Dashboard .

I got below Hygieia version from pom.xml
Hygieia API -- 3.1.2-SNAPSHOT
Hygieia UI --- 3.1.1-SNAPSHOT
Can some one help me to resolve the issue.
Thank you.


text:
Q: Doesn't display salary from given table to created column, wrong SELECT AND WHERE In the "Positions" dictionary, you need to add an additional column "Position salary". The value of this field is taken from the "Amount" field from the payroll table "salary", and all this must be on the current system date (current)
WHAT IS AVAILABLE
There is a dictionary "Positions" (POSITIONS), in which you need to add the field Amount (SUMM) from the table POSITIONSFOT (Positions (wage fund)). There is also an OKLZP table (Composition), where in the NAME field you need to select the value '1.salary' and display exactly those amounts that relate specifically to the value NAME='1.salary'.
The function compiled, but shows nothing, even though the SUMM value has zeros. Although the table has 0. In the code below, I am trying to find the record number (RN) of the "Positions (wage fund)" table, given the condition that its record numbers match the 'Positions' table and matches the name '1.salary'
FUNCTION CODE:

create or replace function view_SALAR
(
NRN NUMBER
)
RETURN NUMBER
AS
  INRN NUMBER;
  NUMVAL NUMBER; --- variable for selecting values and returning from the function
BEGIN
  INRN:=NRN;
  BEGIN
    SELECT POSFOT.SUMM INTO NUMVAL
    FROM
    POSITIONSFOT POSFOT, --- table "Positions (wage fund)"
   POSITIONS POSIT, --- table "Positions"
    OKLZP OKL, --- table "Composition of payroll", from where we take the exact name of the type of wages (salary)
    STAFFPOSITIONS  STAFFPOS ---table "full positions", where you need to take Date from(DO_ACT_FROM) and date by(DO_ACT_TO) to get the system date
    WHERE
    POSIT.RN= INRN
    AND POSIT.RN=POSFOT.RN
    AND OKL.NAME='1. salary'
    AND STAFFPOS.DO_ACT_FROM<=SYSDATE AND (STAFFPOS.DO_ACT_FROM>SYSDATE OR STAFFPOS.DO_ACT_TO IS NULL);
  END;
  return NUMVAL;
end view_SALAR;

why do i need help or explanation?
Help me understand my mistake when drafting the request and conditions. All the tables that I have listed are interconnected through the RN record number.
The function compiles, there are no error messages. The column is created, but there are no values in the field. It is quite possible that I write SELECT incorrectly or the conditions themselves after WHERE.
If you do not have information, i can supplement my quesstion.

redpajama_set_name: RedPajamaStackExchange


text: Q: Extracting 'Tags' metadata from a video / image In Windows OS, Images & Video files have 'Tags' Metadata.  We can add tags to these files like 'Favouite' & 'Romantic'.    How to retrieve/extract these tag values using TIKA?


text:
Q: Problema com nth-child Tenho o seguinte cenário:
HTML:

Visivel

Visivel

Invisivel

Visivel

CSS:
.visivel:nth-child(odd) { background: yellow }
.visivel:nth-child(even) { background: green }

Resultado encontrado:

*

*1º linha com classe visivel AMARELA

*2º linha com classe visivel VERDE

*3º linha com classe visivel VERDE

Resultado esperado:

*

*1º linha com classe visivel AMARELA

*2º linha com classe visivel VERDE

*3º linha com classe visivel AMARELA

http://jsfiddle.net/vk6xqnhb/
Pelo que eu entendo, o nth-child deveria pintar alternadamente as divs com a classe visivel. Mas como há uma div oculta no meio ele acaba não fazendo isso corretamente.
Estou enganado sobre o comportamento? Como corrigir?

A: Baseado nos comentários e na resposta do SO em inglês não tive outra solução a não ser usar o jQuery:
 $(".visivel:even").css("background-color", "green");
 $(".visivel:odd").css("background-color", "yellow");

Comentário do @utluiz sobre o comportamento "inesperado":

O comportamento é este mesmo, pois o seletor funciona com base nos nós
  do DOM e não se aplica somente ao que é selecionado pelo CSS.

A: Sobre o funcionamento do nth-child(odd) e nth-child(even): Quando se coloca even e odd vai colorir as linhas pares e ímpares, respectivamente.
Outro modo de fazer, sem usar jQuery, é você criar uma div e colocar todos os elementos dentro dela (de acordo com essa resposta):

.todas {
  line-height: 1.2em;
  background-color: yellow;
  background-image: linear-gradient(transparent 50%, green 50%);
  background-size: 100% 2.4em;
}

Visivel

Visivel

Invisivel

Visivel


text:
Q: Javascript to modify table cell colour on mouseover - Syntax error 800A03EA for javascript Theres this error pop up when I tried to open it with the default microsoft window based script host, but my javascript works fine. When I open in webpages.
I tried to look into it but couldn't find any syntax error.
      td.addEventListener("mouseover", modifyColor, false);
      td.addEventListener("click", clickWhite, false);

const modifyColor = event =>
{
  const color = document.querySelector(".color");
  event.target.style.background = color.value;
}

const clickWhite = event =>
{
  event.target.style.backgroundColor = "white";
}

Based on the error message, it pointed to this section of the code.


text:
Q: HashMap with synchronized block: After these posts
Locking value objects of a ConcurrentHashMap
ConcurrentHashMap: how to replace the value of an entry only if the current value is smalle
Can we use Synchronized for each entry instead of ConcurrentHashMap?
And spending so much time, I think I should give up on concurrency (at least for now) and forget entry locking. It is too error-prone. Several times I came up with a solution, but again I found a bug.
So, if I want to scarify concurrency, and jut have a correct program, I think the easiest what is locking the whole hash table. So what is the best way to do that. I have 6 hash tables.  One solution is using 6 HashMaps and whenever I want to do something use synchronized block. Is it OK, or I need to use ConcurrenHashMap? Note that I am using synchronized block.


text:
Q: программа работает по разному при запуске При запуске программы происходит 3 разновероятных сценария:

*

*всё работает нормально - чуть меньше половины случаев

*всё на панели после создания объекта textField не создаётся (в окне только label) - чуть больше половины случаев

*панель пустая - редко

import javax.swing.*;
import java.awt.*;

public class Start {
    public static void main(String[] args) {

        JPanel panel = new JPanel();

        JFrame frame = new JFrame("Title");
        frame.setSize(200, 100);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.add(panel);
        frame.setVisible(true);

        panel.setLayout(new GridLayout());

        JButton button = new JButton("Button");
        JLabel label = new JLabel("Label");

        panel.add(label);

        JTextField textField = new JTextField();

        panel.add(button);
        panel.add(textField);
    }
}

A: В вашем коде вы сначала создаете JPanel и JFrame и выводите все на экран. Потом вы добавляете элементы на JPanel. По-умолчанию, JPanel никогда не перерисовывает панель после добавления элементов.
Как вариант можно сделать, как уже предложили в комментарии - перенести
frame.setVisible(true);

в конец функции.
Либо можно вызвать:
frame.revalidate();

что в принципе для вас перерисует JPanel и покажет все элементы.


text:
Q: Elasticsearch корректировка поиска Нужна помощь в настройке поисковика elasticsearch. Проблема состоит в том что на данный момент ищет много лишнего. Например, если забить в поиск "приора" то получим как  и сам приору так и кучу результатов типа "приготовления", "прицепы", "привода" и прочее нинужное.
Я использую [php клиент][1] для работы с эластиком
Сейчас в индексе используеются следующие параметры:
        $this->client->indices()->create([
        'index' => 'lots',
        'body' => [
            'mappings' => [
                'properties' => [
                    'id' => [
                        'type' => 'integer',
                    ],
                    'published_at' => [
                        'type' => 'date',
                    ],
                    'name' => [
                        'type' => 'text',
                    ],
                    'lot_info' => [
                        'type' => 'text',
                    ],
                ],
            ],
            'settings' => [
                'analysis' => [
                    'char_filter' => [
                        'replace' => [
                            'type' => 'mapping',
                            'mappings' => [
                                '&=> and '
                            ],
                        ],
                    ],
                    'filter' => [
                        'word_delimiter' => [
                            'type' => 'word_delimiter',
                            'split_on_numerics' => false,
                            'split_on_case_change' => true,
                            'generate_word_parts' => true,
                            'generate_number_parts' => true,
                                'catenate_all' => true,
//                                'preserve_original' => true,
                                'catenate_numbers' => true,
                            ],
                            'trigrams' => [
                                'type' => 'edge_ngram',
                                'min_gram' => 3,
                                'max_gram' => 4,
                            ],
                        ],
                        'analyzer' => [
                            'default' => [
                                'type' => 'custom',
                                'char_filter' => [
                                    'html_strip',
                                    'replace',
                                ],
                                'tokenizer' => 'whitespace',
                                'filter' => [
                                    'lowercase',
                                    'word_delimiter',
                                    'trigrams',
                                ],
                            ],
                        ],
                    ],
                ],
            ],
        ]);

Фильтр ngram режет слово по 3-4 буквы получается "при" "рио" "иор" "ора" и тд. Но при таком использование выдается полный бред после первый пары результатов, отсеять их не получается.
Для себя я представляю алгоритм такого плана, нарезать слово не просто по 3 буквы а учитывать нарезу сначала слова, например "приора", "приор", "прио", "при" и выставить приоритет от большего к меньшему. Это не обязательно должны быть так как я написал, просто это мысли. Если кто знает как сделать поиск более "умным" подскажите пожалуйста

A: использовать нграммы как основной поиск плохая идея. Лучше какой нибудь match по ключевым словам. Либо попробуйте добавить к поиску по нграмам minimum_should_match = 90%, хотя это вряд ли сильно поможет.


text:
Q: Enhanced ecommerce not reporting data to google analytics swift I have integrated google analytics in my app. google analytics is working perfectly but when it comes to enhanced ecommerce it is not reporting revenue to google analytics i tried my best to find the solution but no got succeeded yet. any help will be appreciated. Thanks
 private func logCheckoutProgress(){

        var products = [[String:Any]]()

        for product in CartManager.sharedInstance.cart {
            products.append(product.getFirebaseProductForCart())
        }

        let ecommerce = [
            "items" : products,
            AnalyticsParameterCheckoutStep : 2, // Optional for first step.
            AnalyticsParameterCheckoutOption : "COD" // Optional.
            ] as [String : Any]
        Analytics.logEvent(AnalyticsEventCheckoutProgress, parameters: ecommerce)
    }
    private func logPurchases(){

        var products = [[String:Any]]()

        for product in CartManager.sharedInstance.cart {
            products.append(product.getFirebaseProductForCart())
        }

        let subtotal = (confirmedOrder?.subTotal ?? CartManager.sharedInstance.cartSubTotalAmount()) - (PersistenceManager.sharedInstance.promotion()?.calculateDiscount() ?? 0)
        var ecommerce = [
            "items" : products,
            AnalyticsParameterTransactionID : confirmedOrder?.displayId ?? 0,
            AnalyticsParameterAffiliation : PersistenceManager.sharedInstance.vendor()?.name ?? "",
            AnalyticsParameterValue : subtotal,
            AnalyticsParameterCurrency : AppConstants.Currency,
            AnalyticsParameterShipping : CartManager.sharedInstance.doesQualifiesFreeDelivery() ? PersistenceManager.sharedInstance.vendor()?.deliveryCharges ?? 0 : 0,
            ] as [String : Any]

        if let promoCode = PersistenceManager.sharedInstance.promotion()?.promoCode {
            ecommerce[AnalyticsParameterCoupon] = promoCode
        }

        Analytics.logEvent(AnalyticsEventEcommercePurchase, parameters: ecommerce)
    }


text:
Q: java.lang.NoClassDefFoundError: javax/faces/context/FacesContextFactory All similar questions didn't help me, so I'm creating my own:
I'm creating a JSF Webapp with Maven in Eclipse. To test it, I run it as a Maven build with the war:war goal, this works without errors. However, when I deploy the war-file to my local tomcat to test it, I get the following error message during startup:
SCHWERWIEGEND: Critical error during deployment:
java.lang.NoClassDefFoundError: javax/faces/context/FacesContextFactory
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:270)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1701)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:270)
        at javax.faces.FactoryFinder.getImplGivenPreviousImpl(FactoryFinder.java:618)
        at javax.faces.FactoryFinder.getImplementationInstance(FactoryFinder.java:509)
        at javax.faces.FactoryFinder.access$400(FactoryFinder.java:139)
        at javax.faces.FactoryFinder$FactoryManager.getFactory(FactoryFinder.java:993)
        at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:343)
        at com.sun.faces.config.processor.FactoryConfigProcessor.verifyFactoriesExist(FactoryConfigProcessor.java:303)
        at com.sun.faces.config.processor.FactoryConfigProcessor.process(FactoryConfigProcessor.java:219)
        at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:360)

        at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:225)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)

        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:976)

        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1653)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: javax.faces.context.FacesContextFactory
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        ... 39 more

I have the following dependencies...
<dependencies>
  <dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.1.7</version>
  </dependency>
  <dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-impl</artifactId>
    <version>2.1.7</version>
  </dependency>
</dependencies>

and plugins:
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.1</version>
        <configuration>
            <source>1.6</source>
            <target>1.6</target>
        </configuration>
    </plugin>
    <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
    </plugin>
</plugins>

If you need further information, let me know. Thanks!

A: This problem suggests that you've another JSF API library somewhere else in the runtime classpath which is loaded by the JRE or Tomcat itself instead of by the webapp. This way the webapp-supplied JSF impl library can't find the right API, resulting in exactly this exception+trace.
In other words, the runtime classpath is dirty. Cleanup it. Get rid of JARs randomly placed in wrong places. This covers among others Tomcat's own /lib folder, the JRE's /lib and /lib/ext folders. On the other hand, if you make sure that you never randomly put JARs in folders covered by the webapp's runtime classpath, then everything should be well.
Another potential cause is that you're shipping multiple different versioned JSF API libraries in the webapp itself, but this information is not visible in the question in its current form. Exploring the /WEB-INF/lib folder of the Maven-built WAR file must give clues.


text:
Q: iOS - UITextAutocorrection background color I'm using a UITextView with a background color set to [UIColor clearColor]. So when accepting AutoCorrection suggestions they will briefly blink white (which would be no problem if my UITextView had a white background). Is it possible to set the background color of UITextAutocorrection?

A: I believe it's a No. This hasn't been available for all I know. I'm not quite sure if there's a trick (hack) for this.
But, if you do get any update on this matter, please keep us updated :) Thanks!


text:
Q: Fire Subroutine when user leaves a date field ContentControl Word VBA Edit: I've updated the post with more info.
I have a Content Control inside a header in Word in which I have a date time picker. I'm trying to fire the _ContentControlOnExit event when the user leaves the focus (blurs) of the picker.
Let's suppose I've manually created a Content Control and I've assigned it a Date Picker. I've also tagged it with the value date.
I want that each time the date is changed, I perform a subroutine that will insert a text value to another ContentControl tagged tide-level. I tried the code below with no success.
Please, note that the date ContentControl is inside a header in the Word Document.

  Private Sub ActiveDocment_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
        If (ContentControl.Type = wdContentControlDate) Then
            MsgBox "Let's do it! Write the tide levels"

            dateObj = ActiveDocument.SelectContentControlsByTag("tide-level")
            dateObj.Range.Text = "wwwoohooo Tide Levels!"

            Cancel = True
        End If
    End Sub

I remember reading somewhere that whenever you have content in the header, it seems things get problematic...
Any ideas?
P.S:
Currently using Word 365 - VBA

A: Based on the name of the procedure in the question - ActiveDocment_ContentControlOnExit - it appears the event handler was not generated automatically by Word and that it is therefore not in the ThisDocument class module of the document that contains the content controls. The name of the event handler (generated by the VBA editor) is usually Document_ContentControlOnExit.
The content control event handlers must be in ThisDocument. Theoretically, they could be typed manually, but Word doesn't always recognize manually typed event handlers. So it's better to use the VBA Editor's automatic "stub" generation to get the structures:

*

*Open the ThisDocument module for the document that contains the content control.

*In the code page window, at the top left, select "Document" from the drop-down.

*from the top-right select the event to be inserted.

At this point, the VBA editor will create the "stub" for you - all that's needed is the code to be executed.
Note about the content control being in the header: This event does fire as long as focus when exiting remains in the header. If, however, the user double-clicks in the document body in order to exit the header the event doesn't fire. (At least, not in my tests.) If this is a problem you may want to put this field in the body of the document with a second, linked content control in the header to reflect the selection. Doing this is a bit complex (requires a Custom XML Part in the document to manage the linked information), but the version of Word you're using should have a tool for setting it up.

A: the macro name should be:
Docment_ContentControlOnExit

NOT:
ActiveDocment_ContentControlOnExit


text:
Q: In SQL Server, how to obtain set of latest entries for an every set of parameters? I have a table like
 TIMESTAMP PARAMETER1 PARAMETER2 VALUE
 --------------------------------------
 111       2          3          12.00
 222       2          3          13.00
 333       2          3          13.00
 111       3          4          15.00
 222       3          4          19.00
 010       3          5          20.00

In SQL Server, I would need to build a query that would return several rows, one row per combination of PARAMETER1 and PARAMETER2, and only for latest timestamp that appears for the respective combination.
For the example above, for combination {PARAMETER1, PARAMETER2} = {2,3} the latest timestamp is 333, for {3,4} it is 222, and for {3,5} it is 010, so I'd like to write a query that returns:
 TIMESTAMP PARAMETER1 PARAMETER2 VALUE
 --------------------------------------
 333       2          3          13.00
 222       3          4          19.00
 010       3          5          20.00

A: This has been asked and answered hundreds if not thousands of times. But it was easier to type out an answer than find a duplicate.
select TIMESTAMP
    , PARAMETER1
    , PARAMETER2
    , VALUE
from
(
    select TIMESTAMP
        , PARAMETER1
        , PARAMETER2
        , VALUE
        , RowNum = ROW_NUMBER() over (partition by PARAMETER1, PARAMETER2 order by TIMESTAMP desc)
)x
where x.RowNum = 1


text:
Q: WP отображение пагинации при Ajax сформированном контенте Есть страница на которой выводятся посты (произвольный тип записи news). На этой странице имеется форма фильтрации, с чекбоксами на таксономию этих постов.

Вопрос, как реализовать Пагинацию для Ajax фильтра, Фильтр должен работать без перезагрузки страницы, а также должна присутствует пагинация (не более 5 записей на странице).
Решить задачу в лоб. Не получилось. functionns.php

add_action('wp_ajax_myfilter', 'my_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'my_filter_function');

function my_filter_function(){

    $my_terms = $_POST['filter_tags_id'];

    if(!empty( $my_terms)){
        $args = array(
            'post_type' => 'news',
            'orderby' => 'post_date',
            'order' => 'DESC',
            'posts_per_page' => '5',
            'tax_query' => [
                'relation' => 'OR',
                [
                    'taxonomy' => 'post_tag',
                    'field'    => 'id',
                    'terms'    => $my_terms,
                ]
            ],
        );
    } else{
        $args = array(
            'post_type' => 'news',
            'orderby' => 'post_date',
            'order' => 'DESC',
            'posts_per_page' => -1,
        );
    }

    $query = new WP_Query( $args );
    if( $query->have_posts() ) :
        while ($query->have_posts()) : $query->the_post();
            $title = get_the_title();
            echo '

                    ' . $title . '

';
        endwhile;
        ?>

                        <?php
                        echo paginate_links( array(
                            'base' => get_pagenum_link(1) . '%_%',
                            'format' => '/page/%#%/',
                            'total' => $query->max_num_pages,
                            'current' => max( 1, get_query_var('paged') ),
                            'show_all' => false,
                            'end_size' => 1,
                            'mid_size' => 2,
                            'prev_next' => true,
                            'prev_text' => __('Previous', 'test'),
                            'next_text' => __('Next', 'test'),
                            'class' => '',
                        ) );
                        ?>

        <?php
        wp_reset_postdata();
    else :
        echo '
No news found
';

    endif;

    die();
}

При добавлении обычной пагинации на аякс запрос, оно рисует ссылки, вот только URL адресса у ссылок получаются по типу 2
И нажимая на данные ссылки оно разумеется никуда не перебрасывает. Подскажите, как быть с пагинацией на Ajax для WordPress


text:
Q: ModelCheckpoint monitoring values when the model has multiple outputs My model has two outputs, I want to monitor one to save my model.
Below is part of my code. The version of TensorFlow is 2.0
model = MobileNetBaseModel()()
model.compile(optimizer=tf.keras.optimizers.Adam(),
              metrics={"pitch_yaw_roll": "mae"},
              loss={"pitch_yaw_roll": compute_mse_loss, # or "mse"
                    "total_logits": compute_cross_entropy_loss(num_classes=num_classes)},
              loss_weights= {"pitch_yaw_roll":mse_weight, "total_logits":cross_entropy_weight})
file_path = os.path.join(checkpoint_path, "model.{epoch:2d}-{val_loss:.2f}.h5")
tf.keras.callbacks.ModelCheckpoint(filepath=file_path,
                                   monitor="val_loss",
                                   verbose=1,
                                   save_freq=save_freq,
                                   save_best_only=True)

The default monitor='val_loss' in the ModelCheckpoint callback, how do I choose what I need? I want to monitor {"pitch_yaw_roll": "mae"}.

A: If you want ModelCheckpoint to save according to another metric value, use the key of that metric in the .compile(metrics={...}, ...) metrics dictionary.
So for example, if you would like to save only the best "pitch_yaw_roll" epoch result (best being the minimum value) you should use
tf.keras.callbacks.ModelCheckpoint(filepath=file_path,
                                   monitor="val_pitch_yaw_roll",
                                   verbose=1,
                                   mode="min",
                                   save_freq=save_freq,
                                   save_best_only=True)

If you opt for "pitch_yaw_roll" instead of "val_pitch_yaw_roll" it will save according to the training loss and not according to the validation loss

A: Just adding to comment above, I belive your checkpoint doesn't work because of incorrect name of value to monitor.
General, solution here might be to have a peak into history that your fit creates.
history = model.fit(...)
pd.DataFrame(history.history)

there you will find names of metrics you should use in monitor statement.


text:
Q: Android live video streaming issue I have a question about video streaming from Android devices and maybe someone who will give me some useful advice/suggestions about my question.So here is the deal :
I have a project for video streaming from Android device.The idea is that to connect to devices to a server and the first one is streaming live video and upload it to server and the second device is streaming and watching the video from the first device. So there is connection like this :
First Device ----live streaming----> Web Server ------live streaming---->Second Device , where second device is connecting to the web server.
Any suggestions/advice how can I do that and what should I use?I will be really glad to hear your ideas.
Thanks in advance!

A: I was playing with something similar. Basically:
android video capture --> upstream to server --> transcoding --> streaming to players

*

*the video is captured by a mobile phone (currently only a proof of concept for Android) and delivered to a server

*the server performs transcoding from the original format (H.263 and AMR-NB within a .3gp
container) to a Flash video, so that it can be played in vast majority of browsers

My biggest issue is that with the H.263, I'm not able to upstream it live to the server. The video has a header, which indicates among others its length and other info. Then, in order the video can be transcoded (I use ffmpeg), the header must be present. But it is set by Android AFTER the video capturing is finished.
So as a work around, I'm capturing the video in e.g. 5 second slices.
Take a look at http://code.google.com/p/moteve and feel free to contribute :-)


text:
Q: monotouch subviews horizontal paging
firstly, i want add 3 subviews with textview, image also edittext ;
view1 ; image,
view 2 : text, image,
view 3 : text, label
i want to scroll with async or with swipe
i used image scroll but can't find subviews
thanks for sharing

A: You can use an UIScrollView, or an UIPageViewController. Both will work, but the custom scroll view may be a bit simpler.


text: Q: intel-renderkit Use this tag to ask questions about the Intel® oneAPI Rendering Toolkit, which is designed to accelerate workloads with a set of rendering and ray-tracing libraries to create high-performance, high-fidelity visual experiences.


text:
Q: Integral $\int \frac{\sin^n(x)}{\cos(x)}dx$ In one of my exercises about integration we had to solve the following integral:
\begin{equation}
\int \frac{\sin^n(x)}{\cos^m(x)}dx
\end{equation}
We had to do this via a recursive integral. I found:
\begin{equation}
\mathcal{K_{m,n}} = \frac{\sin^{n-1}(x)}{(m-1)\cdot\cos^{m-1}(x)}-\frac{n-1}{m-1}\cdot\mathcal{K}_{m-2,n-2}, \qquad n,m\geq2
\end{equation}
I know for a fact that this solution is correct because we solved this in class, but the other cases where m and/or n are not $\geq$ 2, were left as an exercise for us at home. I've found a solution for every case except for the case where $m = 1$, which makes the following integral.
\begin{equation}
\int \frac{\sin^n(x)}{\cos(x)}dx
\end{equation}
I've tried different things, I tried integration by parts with many different u's and v's but none of them seem to work out. I tried for example:

*

*$u = \frac{\sin^{n-1}(x)}{\cos(x)}$, $v = \sin(x)$

*$u = \tan(x)$, $v = \sin^{n-1}(x)$

*$u = \sin^{n-1}(x)$, $v = \tan(x)$
Would anyone know how to solve this integral? I'm not looking for a complete solution but rather for a method that should work so i can find the solution by myself from that point on.

A: Denote $I_n=\displaystyle\int \frac{\sin^n(x)}{\cos(x)}~\mathrm dx$. We have
\begin{align*}
I_{n}-I_{n+2}&=\int \frac{\sin^n(x)(1-\sin^2(x))}{\cos(x)}~\mathrm dx\\
&=\int \sin^n(x)\cos(x)~\mathrm dx,
\end{align*}
which is the reduction formula for $I_n$.


text:
Q:  tags are not supported in the HTML specified in either the Content property or the Content Link property I've got two SharePoint Online site collections. One is rather old, the other one was created about two hours ago.
There is an HTML file located in _catalogs/master/webparts/test.html with the following contents. Notice that there is no  tag.

TEST

Now that I add a CEWP to a page and reference this simple HTML file the webpart displays an error:

< FORM > tags are not supported in the HTML specified in either the
  Content property or the Content Link property. You can remove the
  < FORM > tag, or use the Page Viewer Web Part, which supports the HTML
  < FORM > tag. More about the Page Viewer Web Part

I have the same problem in two site collections no matter what HTML I use. At the same time, on other two site collections, there is no such problem.
More info. If I move this html file from _catalogs/master/.. to Assets library then CEWP displays it quite fine. But I've been using _catalogs folder for HTML files for over a year with no problems, and I don't understand why all over sudden it's happening on several site collections. The old site collections with the same approach are still working just fine...
Did anyone encounter this weird bug? Any ideas how to fix it?

A: I've discovered the reason. And it's quite ridiculuous. If there is a space immediately after slash in the URL to the HTML it causes CEWP to show this error. Examples:
Good URL:
/sites/modernDev2/_catalogs/.../sptest/webparts/test.html

Gives a misleading < form > tag ERROR:
/sites/modernDev2/_catalogs/.../sptest/ webparts/test.html

< FORM > tags are not supported in the HTML specified in either the
  Content property or the Content Link property. You can remove the
  < FORM > tag, or use the Page Viewer Web Part, which supports the HTML
  < FORM > tag. More about the Page Viewer Web Part

Notice the space right after /sptest/ That was the reason.


text:
Q: Polymorphic keys - definitive list? I am working with salesforce data within SQL, and am trying to come up with a proper solution to handle polymorphism/polymorphic keys. I am aware of the easy ones (whatid/whoid in task and event), however I am wanting to find every example of polymorphism within Salesforce.  Is there a definitive list that is available?
The second part of this question, is determining the proper way to 'lookup' these IDs. Making ~30 joins would kill the performance of my queries, so I am trying to establish a route forward to lookup these values.

A: You can run an anonymous script like the below to find out for a specific org all of the fields which are polymorphic lookups:
for (SObjectType sObjectType : Schema.getGlobalDescribe().values())
{
    for (SObjectField field : sObjectType.getDescribe().fields.getMap().values())
    {
        if (field.getDescribe().getReferenceTo().size() > 1)
        {
            system.debug(sObjectType + '.' + field);
        }
    }
}

In a fresh Trailhead Playground, for example, the standard objects returned are:

*

*AcceptedEventRelation.RelationId

*AccountShare.UserOrGroupId

*ActivityHistory.OwnerId

*ActivityHistory.WhatId

*ActivityHistory.WhoId

*AssetShare.UserOrGroupId

*AttachedContentDocument.LinkedEntityId

*Attachment.OwnerId

*Attachment.ParentId

*AuthConfigProviders.AuthProviderId

*CampaignMember.LeadOrContactId

*CampaignMember.LeadOrContactOwnerId

*CampaignShare.UserOrGroupId

*Case.OwnerId

*CaseShare.UserOrGroupId

*CaseTeamMember.MemberId

*CaseTeamTemplateMember.MemberId

*CollaborationGroupRecord.RecordId

*CollaborationInvitation.SharedEntityId

*CombinedAttachment.ParentId

*ConsumptionSchedule.OwnerId

*ConsumptionScheduleShare.UserOrGroupId

*ContactRequest.OwnerId

*ContactRequest.WhatId

*ContactRequest.WhoId

*ContactRequestShare.UserOrGroupId

*ContactShare.UserOrGroupId

*ContentDistribution.RelatedRecordId

*ContentDocumentLink.LinkedEntityId

*ContentNotification.EntityIdentifierId

*ContentVersion.FirstPublishLocationId

*ContentWorkspaceMember.MemberId

*CustomBrand.ParentId

*CustomBrandAsset.AssetSourceId

*CustomHttpHeader.ParentId

*Dashboard.FolderId

*DeclinedEventRelation.RelationId

*Document.FolderId

*DuplicateRecordItem.RecordId

*EmailMessage.RelatedToId

*EmailMessageRelation.RelationId

*EmailStatus.WhoId

*EmailTemplate.FolderId

*EntityDefinition.DataStewardId

*EntitySubscription.ParentId

*Event.OwnerId

*Event.WhatId

*Event.WhoId

*EventChangeEvent.WhatId

*EventChangeEvent.WhoId

*EventRelation.RelationId

*EventRelationChangeEvent.RelationId

*ExternalDataUserAuth.ExternalDataSourceId

*FeedAttachment.FeedEntityId

*FeedAttachment.RecordId

*FeedComment.FeedItemId

*FeedComment.ParentId

*FeedItem.ParentId

*FeedLike.FeedEntityId

*FeedLike.FeedItemId

*FeedPollChoice.FeedItemId

*FeedPollVote.FeedItemId

*FeedRevision.FeedEntityId

*FeedSignal.FeedEntityId

*FeedSignal.FeedItemId

*FeedTrackedChange.FeedItemId

*FieldDefinition.BusinessOwnerId

*FlowInterview.OwnerId

*FlowInterviewShare.UserOrGroupId

*FlowRecordRelation.RelatedRecordId

*ForecastShare.UserOrGroupId

*Group.OwnerId

*Group.RelatedId

*GroupMember.UserOrGroupId

*Image.OwnerId

*ImageShare.UserOrGroupId

*Lead.OwnerId

*LeadShare.UserOrGroupId

*ListEmail.OwnerId

*ListEmailIndividualRecipient.RecipientId

*ListEmailRecipientSource.SourceListId

*ListEmailShare.UserOrGroupId

*LoginHistory.AuthenticationServiceId

*LookedUpFromActivity.OwnerId

*LookedUpFromActivity.WhatId

*LookedUpFromActivity.WhoId

*Macro.OwnerId

*MacroShare.UserOrGroupId

*Note.ParentId

*NoteAndAttachment.ParentId

*OpenActivity.OwnerId

*OpenActivity.WhatId

*OpenActivity.WhoId

*OpportunityShare.UserOrGroupId

*Order.OwnerId

*OrderShare.UserOrGroupId

*OrgDeleteRequest.OwnerId

*OrgDeleteRequestShare.UserOrGroupId

*OutgoingEmail.RelatedToId

*OutgoingEmail.WhoId

*OutgoingEmailRelation.RelationId

*PermissionSet.LicenseId

*ProcessInstance.TargetObjectId

*ProcessInstanceHistory.ActorId

*ProcessInstanceHistory.OriginalActorId

*ProcessInstanceHistory.TargetObjectId

*ProcessInstanceStep.ActorId

*ProcessInstanceStep.OriginalActorId

*ProcessInstanceWorkitem.ActorId

*ProcessInstanceWorkitem.OriginalActorId

*QuickText.OwnerId

*QuickTextShare.UserOrGroupId

*RecordAction.RecordId

*RecordActionHistory.ParentRecordId

*Report.OwnerId

*SetupEntityAccess.SetupEntityId

*StreamingChannel.OwnerId

*StreamingChannelShare.UserOrGroupId

*Task.WhatId

*Task.WhoId

*TaskChangeEvent.WhatId

*TaskChangeEvent.WhoId

*TodayGoal.OwnerId

*TodayGoalShare.UserOrGroupId

*TopicAssignment.EntityId

*UndecidedEventRelation.RelationId

*User.DelegatedApproverId

*UserAppMenuCustomization.OwnerId

*UserAppMenuCustomizationShare.UserOrGroupId

*UserChangeEvent.DelegatedApproverId

*UserEmailPreferredPerson.OwnerId

*UserEmailPreferredPerson.PersonRecordId

*UserEmailPreferredPersonShare.UserOrGroupId

*UserProvisioningRequest.OwnerId

*UserProvisioningRequestShare.UserOrGroupId

*UserShare.UserOrGroupId

*Vote.ParentId

*WebLink.ScontrolId


text:
Q: Why doesn't equals throw NullPointerException when one of the variables is pointing to null Let's consider following code:
String s1=null;
String s2="something";
System.out.println(s2.equals(s1));
//output: false

Why is s2.equals(s1) not throwing NullPointerException?
EDIT: Thanks for the Answers, I am sorry for the Question I wasn't aware of this

For any non-null reference value x, x.equals(null) should return
  false.

The confusion came because toString method was throwing exception while equals didn't and I thought to myself but equals has also to "look" inside of the object so that it can perform comparison why isn't equals also throwing excetion

A: Usually, the equals implementation has something like:
if ( o == null ) return false;
So, why would you expect this to throw an NPE? If you want it to throw one, change your statement to:
System.out.println( s1.equals(s2));

Then, you are actually calling an instance method on a null without checking for null first.

A: It's because the contract for the equals method, as specified in the Javadoc for the Object.equals method , explicitly states:

For any non-null reference value x, x.equals(null) should return false.

If the method threw a NullPointerException, it would be non-compliant with the contract.


text:
Q: singleton at the boot of application I'm creating a small game where I would like to have a game room and a bunch of games in the game room. This would be a spring boot application. So I was thinking of starting the GameRoom at the start of the application. Then whenever a new game is created, I will add it to the list of games in the game roon. Is is a good idea? Or are there any potential pitfalls.
public class GameRoon{

   private static GameRoom instance = null;
   List<Game> games = new ArrayList();

   private GameRoom() {}

   public static GameRoom getIsntance() {
    if(instance == null) {
       instance = new GameRoom();
    }
    return instance;
  }
}

The above is my unfinished singleton.. I have 2 questions.
1. Is it a good idea to start this during spring-boot start up?
2. Is it better to use singleton like this in spring-boot or is there a better way to do it

A: Singletons are highly debated and you will always find reasons for using it and for not.
In my opinion if your class responsibility is to hold a state (think of a registry with some data) which is shared within the application I don't see any problem. It is clear that you share the data and must be sure to govern concurrent access.
The main drawback of Singleton is testing: you have a global state but ideally during unit testing you want to test some code without relying on the singleton class (instead a mock). You can still solve this thanks to Spring: define the GameRoom as Spring bean (default scope is Singleton) which is injected like any other bean. This allows to mock it during unit testing, even if underneath there is a singleton behavior.


text:
Q: How to exclude node_modules folder from TFS Fortify build? I am running a TFS build for Fortify security results. The web app has a npm/gulp task dependency so those tasks run correctly which then creates the node_modules folder. I then push the scan results to Fortify which is flagging over 600 issues within the node_modules folder. Is there a task I can add to the TFS-Fortify build to run the gulp/npm tasks and then remove or exclude the node_modules from the Fortify scan results?
I have tried adding a windows batch task to the build with the path set to where the node_modules folder will be added and set the arguments to rmdir "node_modules" which causes ##[error]Process completed with exit code 1. Any suggestions?


text:
Q: PCA - more than 2 principal components for >80% variance I have analyzed some datasets using prcomp and some of my data is nice and amenable to PCA. But the summary of one set is showing that at least 6 components are needed to cover 80% of the variance. I've checked and the correlation matrix should work better than the covariance matrix.
When I plot the results using biplot, is that plotting all components, taking all components into consideration or only the first two?
If that is not the best way to look at my data with so much variance, then what is?
Also, does anyone know of a tutorial on how to plot a biplot of only the top values and not all - this would be useful as I have a few datasets with >1,000 entries.
Any help greatly appreciated.


text:
Q: Angularjs cascade dropdown with json object array i'm trying to understand how controllers works in angularjs using cascade dropdowns. But my second dropdown is not being populated based on the previous dropdown value.
My JSON arry result:
[{
    "id": "23031",
    "fabricante": "ALFA ROMEO",
    "modelo": "33",
    "motor": "1.3 \/ 1.3 ie",
    "combustivel": "Gasolina \/ GNV",
    "ano_vela": "",
    "ngk": "",
    "ngk_green": "BPR6EY",
    "gap": "0,7",
    "ano_cabo": "",
    "cabos_ngk": "",
    "inicio": "",
    "fim": "",
    "seguimento": "4 RODAS",
    "ano_bobina": "",
    "bobina_ngk": "",
    "pais": "Argentina",
    "n_processo": "0"
}, {
    "id": "23057",
    "fabricante": "ARO",
    "modelo": "Serie 10",
    "motor": "1.4",
    "combustivel": "Gasolina \/ GNV",
    "ano_vela": "",
    "ngk": "BP6HS",
    "ngk_green": "",
    "gap": "0,7",
    "ano_cabo": "",
    "cabos_ngk": "",
    "inicio": "",
    "fim": "",
    "seguimento": "4 RODAS",
    "ano_bobina": "",
    "bobina_ngk": "",
    "pais": "Argentina",
    "n_processo": "0"
}]

My Controller EDITED:
angular.module('starter.controllers', [])

.controller('fabricanteController', ['$scope','$http', function($scope, $http) {
$http.get('JSON_PATH').success(function (data) {
    $scope.fabricantes = data;
    $scope.$watch('fabricante', function(newVal) {
    if (newVal) $scope.modelo = data;
    console.log($scope.modelo);
});
});
}]);

And my HTML:

        Fabricante

    <select ng-model="fabricante" ng-options="fab.fabricante for fab in fabricantes track by fab.fabricante">
        <option value="" disabled="disabled">Selecionar</option>
    </select>

        Modelo

    <select ng-model="modelo" ng-options="mod.modelo for mod in fabricantes">
        <option value="" disabled="disabled">Selecionar</option>
    </select>

Tried to look around how to make it work but no luck.
Any idea why?

A: Your watch isn't firing because you're passing in a string, not a variable. Also, I don't know where you're checking newVal, but it won't work like that..
Basic implementation:
$scope.$watch($scope.fabricante, function() {
    $scope.modelo = data;
    console.log($scope.modelo);
});

With newVal checking:
$scope.$watch($scope.fabricante, function() {
    if($scope.modelo!=data)
    {
      $scope.modelo = data;
      console.log($scope.modelo);
    }

});

You can also use ng-change on the Select box, which will fire on any change.
<select ng-model="fabricante" ng-change="doSomething()" ng-options="fab.id for fab in fabricantes"></select>

A: If you wanna show the 'modelo' property of the selected 'fabricante' object you must point the ng-option of your second DDL to a new $scope array variable such:
$scope.modelos = [{"modelo": newVal.modelo}];

Your ng-options should be:
<select ng-model="test" ng-options="mod.modelo for mod in modelos">

Here is a working JSFiddle
Hope this helps.


text:
Q: How to use editor templates from within a razor page that resides in an area? How can I use editor templates when using razor pages? I'm also using areas as a structural pattern.
I see no output when I call @Html.EditorFor(m => m.Something). But, I do see the content of a custom display template when using @Html.DisplayFor(m => m.Something).
My project tree looks like the following ...

*

*Areas

*

*Identity

*

*Pages

*

*... my various pages

*Pages

*

*Shared

*

*DisplayTemplates

*

*string.cshtml (for example)

*EditorTemplates

*

*string.cshtml (again, example)

With this structure, I'm seeing my display templates being used but not my editor templates.
How do I use editor templates when also using razor pages & areas?

A: @Ryan, I've tried to repeat your codes to find out the answer and found that @Html.EditorFor() and @Html.DisplayFor() will cause errors in partial view.
But @Html.Raw() and @Html.TextBoxFor() works well.
There is no clear answer for the reason of@Html.EditorFor() and @Html.DisplayFor() which I'm still looking for.
/Pages/Shared/DisplayTemplates/string.cshtml
@model RazorPages62921534.Models.User

DisplayTemplates

@Html.LabelFor(m => m.Id): @Html.Raw(Model.Id)

/Pages/Shared/DisplayTemplates/string.cshtml
@model RazorPages62921534.Models.User

EditorTemplates

@Html.LabelFor(m => m.Name): @Html.TextBoxFor(x => x.Name)

Areas/Identity/Pages
@page
@model RazorPages62921534.Areas.Identity.Pages.IdentityIndexModel

@{

        var user = new RazorPages62921534.Models.User() {
            Id = 1,
            Name = "Ada"
        };
}

@Html.Partial("~/Pages/Shared/DisplayTemplates/string.cshtml", user)

@Html.Partial("~/Pages/Shared/EditorTemplates/string.cshtml", user)

Test

Related Link:
How to pass a nested model value in @Html.Partial
Passing a model to a partial view

Did I misunderstand your needs? Please let me know and I will follow
this up.


text:
Q: Start CloudSQL Proxy on Python Dataflow / Apache Beam I am currently working on a ETL Dataflow job (using the Apache Beam Python SDK) which queries data from CloudSQL (with psycopg2 and a custom ParDo) and writes it to BigQuery. My goal is to create a Dataflow template which I can start from a AppEngine using a Cron job.
I have a version which works locally using the DirectRunner. For that I use the CloudSQL (Postgres) proxy client so that I can connect to the database on 127.0.0.1 .
When using the DataflowRunner with custom commands to start the proxy within a setup.py script, the job won't execute.
It stucks with repeating this log-message:
Setting node annotation to enable volume controller attach/detach
A part of my setup.py looks the following:
CUSTOM_COMMANDS = [
['echo', 'Custom command worked!'],
['wget', 'https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64', '-O', 'cloud_sql_proxy'],
['echo', 'Proxy downloaded'],
['chmod', '+x', 'cloud_sql_proxy']]

class CustomCommands(setuptools.Command):
  """A setuptools Command class able to run arbitrary commands."""

  def initialize_options(self):
    pass

  def finalize_options(self):
    pass

  def RunCustomCommand(self, command_list):
    print('Running command: %s' % command_list)
    logging.info("Running custom commands")
    p = subprocess.Popen(
        command_list,
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    # Can use communicate(input='y\n'.encode()) if the command run requires
    # some confirmation.
    stdout_data, _ = p.communicate()
    print('Command output: %s' % stdout_data)
    if p.returncode != 0:
      raise RuntimeError(
          'Command %s failed: exit code: %s' % (command_list, p.returncode))

  def run(self):
    for command in CUSTOM_COMMANDS:
      self.RunCustomCommand(command)
    subprocess.Popen(['./cloud_sql_proxy', '-instances=bi-test-1:europe-west1:test-animal=tcp:5432'])

I added the last line as separate subprocess.Popen() within run() after reading this issue on Github from sthomp  and this discussion on Stackoverflo. I also tried to play around with some parameters of subprocess.Popen.
Another mentioned solution from brodin was to allow access from every IP address and to connect via username and password. In my understanding he does not claim this as best practice.
Thank you in advance for you help.
!!! Workaround solution at bottom of this post !!!

Update - Logfiles
These are the logs on error level which occur during a job:
E  EXT4-fs (dm-0): couldn't mount as ext3 due to feature incompatibilities
E  Image garbage collection failed once. Stats initialization may not have completed yet: unable to find data for container /
E  Failed to check if disk space is available for the runtime: failed to get fs info for "runtime": unable to find data for container /
E  Failed to check if disk space is available on the root partition: failed to get fs info for "root": unable to find data for container /
E  [ContainerManager]: Fail to get rootfs information unable to find data for container /
E  Could not find capacity information for resource storage.kubernetes.io/scratch
E  debconf: delaying package configuration, since apt-utils is not installed
E    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
E                                   Dload  Upload   Total   Spent    Left  Speed
E
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100  3698  100  3698    0     0  25674      0 --:--:-- --:--:-- --:--:-- 25860

#-- HERE IS WHEN setup.py FOR MY JOB IS EXECUTED ---

E  debconf: delaying package configuration, since apt-utils is not installed
E  insserv: warning: current start runlevel(s) (empty) of script `stackdriver-extractor' overrides LSB defaults (2 3 4 5).
E  insserv: warning: current stop runlevel(s) (0 1 2 3 4 5 6) of script `stackdriver-extractor' overrides LSB defaults (0 1 6).
E  option = Interval; value = 60.000000;
E  option = FQDNLookup; value = false;
E  Created new plugin context.
E  option = PIDFile; value = /var/run/stackdriver-agent.pid;
E  option = Interval; value = 60.000000;
E  option = FQDNLookup; value = false;
E  Created new plugin context.

Here you can find are all logs after the start of my custom setup.py (log-level: any; all logs):
https://jpst.it/1gk2Z
Update logfiles 2
Job logs (I manually canceled the job after not stucking for a while):
 2018-06-08 (08:02:20) Autoscaling is enabled for job 2018-06-07_23_02_20-5917188751755240698. The number of workers will b...
 2018-06-08 (08:02:20) Autoscaling was automatically enabled for job 2018-06-07_23_02_20-5917188751755240698.
 2018-06-08 (08:02:24) Checking required Cloud APIs are enabled.
 2018-06-08 (08:02:24) Checking permissions granted to controller Service Account.
 2018-06-08 (08:02:25) Worker configuration: n1-standard-1 in europe-west1-b.
 2018-06-08 (08:02:25) Expanding CoGroupByKey operations into optimizable parts.
 2018-06-08 (08:02:25) Combiner lifting skipped for step Save new watermarks/Write/WriteImpl/GroupByKey: GroupByKey not fol...
 2018-06-08 (08:02:25) Combiner lifting skipped for step Group watermarks: GroupByKey not followed by a combiner.
 2018-06-08 (08:02:25) Expanding GroupByKey operations into optimizable parts.
 2018-06-08 (08:02:26) Lifting ValueCombiningMappingFns into MergeBucketsMappingFns
 2018-06-08 (08:02:26) Annotating graph with Autotuner information.
 2018-06-08 (08:02:26) Fusing adjacent ParDo, Read, Write, and Flatten operations
 2018-06-08 (08:02:26) Fusing consumer Get rows from CloudSQL tables into Begin pipeline with watermarks/Read
 2018-06-08 (08:02:26) Fusing consumer Group watermarks/Write into Group watermarks/Reify
 2018-06-08 (08:02:26) Fusing consumer Group watermarks/GroupByWindow into Group watermarks/Read
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/WriteBundles/WriteBundles into Save new watermar...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/GroupByKey/GroupByWindow into Save new watermark...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/GroupByKey/Reify into Save new watermarks/Write/...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/GroupByKey/Write into Save new watermarks/Write/...
 2018-06-08 (08:02:26) Fusing consumer Write to BQ into Get rows from CloudSQL tables
 2018-06-08 (08:02:26) Fusing consumer Group watermarks/Reify into Write to BQ
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/Map(<lambda at iobase.py:926>) into Convert dict...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/WindowInto(WindowIntoFn) into Save new watermark...
 2018-06-08 (08:02:26) Fusing consumer Convert dictionary list to single dictionary and json into Remove "watermark" label
 2018-06-08 (08:02:26) Fusing consumer Remove "watermark" label into Group watermarks/GroupByWindow
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/InitializeWrite into Save new watermarks/Write/W...
 2018-06-08 (08:02:26) Workflow config is missing a default resource spec.
 2018-06-08 (08:02:26) Adding StepResource setup and teardown to workflow graph.
 2018-06-08 (08:02:26) Adding workflow start and stop steps.
 2018-06-08 (08:02:26) Assigning stage ids.
 2018-06-08 (08:02:26) Executing wait step start25
 2018-06-08 (08:02:26) Executing operation Save new watermarks/Write/WriteImpl/DoOnce/Read+Save new watermarks/Write/WriteI...
 2018-06-08 (08:02:26) Executing operation Save new watermarks/Write/WriteImpl/GroupByKey/Create
 2018-06-08 (08:02:26) Starting worker pool setup.
 2018-06-08 (08:02:26) Executing operation Group watermarks/Create
 2018-06-08 (08:02:26) Starting 1 workers in europe-west1-b...
 2018-06-08 (08:02:27) Value "Group watermarks/Session" materialized.
 2018-06-08 (08:02:27) Value "Save new watermarks/Write/WriteImpl/GroupByKey/Session" materialized.
 2018-06-08 (08:02:27) Executing operation Begin pipeline with watermarks/Read+Get rows from CloudSQL tables+Write to BQ+Gr...
 2018-06-08 (08:02:36) Autoscaling: Raised the number of workers to 0 based on the rate of progress in the currently runnin...
 2018-06-08 (08:02:46) Autoscaling: Raised the number of workers to 1 based on the rate of progress in the currently runnin...
 2018-06-08 (08:03:05) Workers have started successfully.
 2018-06-08 (08:11:37) Cancel request is committed for workflow job: 2018-06-07_23_02_20-5917188751755240698.
 2018-06-08 (08:11:38) Cleaning up.
 2018-06-08 (08:11:38) Starting worker pool teardown.
 2018-06-08 (08:11:38) Stopping worker pool...
 2018-06-08 (08:12:30) Autoscaling: Reduced the number of workers to 0 based on the rate of progress in the currently runni...

Stack Traces:
No errors have been received in this time period.

Update: Workaround Solution can be found in my answer below

A: Workaround Solution:
I finally found a workaround. I took the idea to connect via the public IP of the CloudSQL instance. For that you needed to allow connections to your CloudSQL instance from every IP:

*

*Go to the overview page of your CloudSQL instance in GCP

*Click on the Authorization tab

*Click on Add network and add 0.0.0.0/0 (!! this will allow every IP address to connect to your instance !!)

To add security to the process, I used SSL keys and only allowed SSL connections to the instance:

*Click on SSL tab

*Click on Create a new certificate to create a SSL certificate for your server

*Click on Create a client certificate to create a SSL certificate for you client

*Click on Allow only SSL connections to reject all none SSL connection attempts

After that I stored the certificates in a Google Cloud Storage bucket and load
them before connecting within the Dataflow job, i.e.:
import psycopg2
import psycopg2.extensions
import os
import stat
from google.cloud import storage

# Function to wait for open connection when processing parallel
def wait(conn):
    while 1:
        state = conn.poll()
        if state == psycopg2.extensions.POLL_OK:
            break
        elif state == psycopg2.extensions.POLL_WRITE:
            pass
            select.select([], [conn.fileno()], [])
        elif state == psycopg2.extensions.POLL_READ:
            pass
            select.select([conn.fileno()], [], [])
        else:
            raise psycopg2.OperationalError("poll() returned %s" % state)

# Function which returns a connection which can be used for queries
def connect_to_db(host, hostaddr, dbname, user, password, sslmode = 'verify-full'):

    # Get keys from GCS
    client = storage.Client()

    bucket = client.get_bucket(<YOUR_BUCKET_NAME>)

    bucket.get_blob('PATH_TO/server-ca.pem').download_to_filename('server-ca.pem')
    bucket.get_blob('PATH_TO/client-key.pem').download_to_filename('client-key.pem')
    os.chmod("client-key.pem", stat.S_IRWXU)
    bucket.get_blob('PATH_TO/client-cert.pem').download_to_filename('client-cert.pem')

    sslrootcert = 'server-ca.pem'
    sslkey = 'client-key.pem'
    sslcert = 'client-cert.pem'

    con = psycopg2.connect(
        host = host,
        hostaddr = hostaddr,
        dbname = dbname,
        user = user,
        password = password,
        sslmode=sslmode,
        sslrootcert = sslrootcert,
        sslcert = sslcert,
        sslkey = sslkey)
    return con

I then use these functions in a custom ParDo to perform queries.
Minimal example:
import apache_beam as beam

class ReadSQLTableNames(beam.DoFn):
    '''
    parDo class to get all table names of a given cloudSQL database.
    It will return each table name.
    '''
    def __init__(self, host, hostaddr, dbname, username, password):
        super(ReadSQLTableNames, self).__init__()
        self.host = host
        self.hostaddr = hostaddr
        self.dbname = dbname
        self.username = username
        self.password = password

    def process(self, element):

        # Connect do database
        con = connect_to_db(host = self.host,
            hostaddr = self.hostaddr,
            dbname = self.dbname,
            user = self.username,
            password = self.password)
        # Wait for free connection
        wait_select(con)
        # Create cursor to query data
        cur = con.cursor(cursor_factory=RealDictCursor)

        # Get all table names
        cur.execute(
        """
        SELECT
        tablename as table
        FROM pg_tables
        WHERE schemaname = 'public'
        """
        )
        table_names = cur.fetchall()

        cur.close()
        con.close()
        for table_name in table_names:
            yield table_name["table"]

A part of the pipeline then could look like this:
# Current workaround to query all tables:
# Create a dummy initiator PCollection with one element
init = p        |'Begin pipeline with initiator' >> beam.Create(['All tables initializer'])

tables = init   |'Get table names' >> beam.ParDo(ReadSQLTableNames(
                                                host = known_args.host,
                                                hostaddr = known_args.hostaddr,
                                                dbname = known_args.db_name,
                                                username = known_args.user,
                                                password = known_args.password))

I hope this solution helps others with similar problems

A: I managed to find better or at least easier solution.
In DoFn setup function use cloud proxy to setup pre connection
class MyDoFn(beam.DoFn):
 def setup(self):
    os.system("wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy")
    os.system("chmod +x cloud_sql_proxy")
    os.system(f"./cloud_sql_proxy -instances={self.sql_args['cloud_sql_connection_name']}=tcp:3306 &")

A: The easy and right thing to do in 2022 is to use the cloud sql connector which will work with postgres, sqlserver, and mysql running on gcloud sql.
https://cloud.google.com/sql/docs/mysql/connect-connectors#python_1
https://pypi.org/project/cloud-sql-python-connector/
No need to white list IPs, manually load certificates, or leave your database wide open.
You use this format for the host: "project:region:instance" and connect as usual.


text:
Q: When can I not replace a random variable with its mean? A frequent simplification in modeling and simulation is to replace a random variable by its mean value.
When would this simplification lead to the wrong conclusion?

A: If you replace a missing value by some point estimate, you disregard all its variability. Thus, you will not propagate all the original variability to your model. Your parameter estimates will appear to have too low standard-errors. If you do inference, your p values will be biased low. Your confidence-intervals will be too narrow. If you do prediction, your prediction-intervals will be too narrow.
Overall: you will be too sure of your conclusions.

A: In addition to Stephan's points:

*

*In almost any application where you're interested in nonlinear functions of the random variable, substituting the mean will generally introduce bias and possibly contradictory results. The average velocity and average mass of a particle will generally not be consistent with average kinetic energy, because energy scales with V^2.

*The mean value may not even be a possible outcome for the random variable. If my possible outcomes are 0 "patient dies" and 1 "patient lives", it's probably not helpful to have a model that describes the patient as 0.1 "mostly dead but slightly alive".

A: A real life example (related to the two answers you got), in the financial markets. The price of an option is based in the probability that the price of an asset goes above (or below) a given level.
For example, the price of an option for buying an asset at a price 100 when the expected value of the asset is 80. If you substitute the random variable (the asset price) by its mean, you would get a price of zero (as you would never by at 100 an asset that costs 80). When you take into account the stochasticity of the asset (and that's the right way of doing it) you get a positive price, as there is some probability that the asset price goes above 100.


text:
Q: Solid state physics: When do I use classical laws? Let's say I am given the dispersion relation for nearly-free electrons:
$$ E(k) = \frac{\hbar^2}{2m}(k^2+c\,k^4)$$
Where $c$ is a small constant of appropiate dimension.
How do I calculate the velocity of an electron given a fixed $k_1$ ?
Applying "classical" laws results in
$$v(k_1)=\sqrt{\frac{2E(k_1)}{m}} = \frac{\hbar k_1}{m}\sqrt{1+c k_1^2}$$
On the other hand, applying $$v(k_1) = \frac{\partial \omega(k)}{\partial k}\bigg|_{k=k_1} = \hbar^{-1} \frac{\partial E(k)}{\partial k}\bigg|_{k=k_1} = \frac{\hbar}{2m}(2k_1+4ck_1^3) = \frac{\hbar k_1}{m}(1+2c k_1^2)$$
Obviously both terms are not the same, so can anyone explain to me where is the difference ? I guess it has something to do with mixing up the velocity-concept of classical particles (1) and the group-velocity of electrons as waves (2).

A: For wave mechanics there is the phase velocity and group velocity. For the energy $E~=~\hbar\omega$ the phase velocity is
$$
v_p~=~\frac{\omega}{k}~=~\frac{\hbar}{2m}(k~+~ck^3).
$$
This is the velocity of a wave front, or where the phase of the wave is constant. There is also the group velocity that is
$$
v_g~=~\frac{\partial\omega}{\partial k}~=~\frac{\hbar}{m}(k~+~2ck^3).
$$
The classical idea suggested in this question is that $k^2~+~ck^4~=~k'^2$ so that
$$
p'~=~\hbar k'~=~\hbar k\sqrt{1~+~ck^2}
$$
This is a different definition of the momentum and thus velocity. I would say that a better approach is to write the Hamiltonian or energy according to $p~=~\hbar k$
$$
H~=~\frac{1}{2m}\left(p^2~+~\frac{c}{\hbar^2}p^4\right).
$$
This Hamiltonian is an operator for $p~\rightarrow~-i\partial_x$. Now put the wave function $\psi(x,t)~=~Ae^{-ikx~+~i\omega t}$ in the Schrodinger equation to arrive at
$$
H\psi~=~i\hbar\frac{\partial\psi}{\partial t}
$$
to find
$$
\hbar\omega~=~\frac{\hbar^2}{2m}\left(k^2~+~ck^4\right),
$$
which agrees with the phase velocity above.
If you were to insist on doing a sort of classical form with the Hamiltonian above with $H~=~E$ you will arrive at a rather complicated equation
$$
p^2~=~-\frac{\hbar^2}{2c}\left(1~-~\sqrt{1~+~\frac{8mc}{\hbar^2}E}\right).
$$
This is from the quadratic equation and the choice with $p^2~=~0$ at $E~=~0$. If you let $E~=~\hbar\omega$ it is not hard to see this recovers the above result with the Schrodinger equation.


text:
Q: How to use domain url with kestrel in Asp.Net core app? I have a project with asp.net core 2.2 in windows os.
I deploy the project and run with kesterl with this command:
dotnet myapp.dll

that's run in http://localhost:5000.
I need to run the website in mydomain.com.
I set mydomain.com in hosts for 127.0.0.1 ip.
how to set this configuration?

A: When you run an ASP.NET Core application directly through Kestrel, without an additional reverse proxy like IIS or nginx, you will need to configure the hosting URL properly. There are a few options that are described in detail in the endpoint configuration chapter of the documentation:

By default, ASP.NET Core binds to:

*

*http://localhost:5000

*https://localhost:5001 (when a local development certificate is present)

  Specify URLs using the:

*

*ASPNETCORE_URLS environment variable.

*--urls command-line argument.

*urls host configuration key.

*UseUrls extension method.

A very common solution for this is to change the environment variable. This allows you to set the URL in a very flexible way which is very useful for quickly launching the application. When you start the server from the command line, this could look like this:
# PowerShell
PS> $env:ASPNETCORE_URLS = 'http://example.com'
PS> dotnet myapp.dll

# cmd
> set ASPNETCORE_URLS=http://example.com
> dotnet myapp.dll

# bash
$ ASPNETCORE_URLS=http://example.com dotnet myapp.dll

A more permanent (but still flexible) solution would be to specify the Kestrel configuration as part of the appsettings.json file. This also allows you to configure a HTTPS certificate if you want to host over HTTPS.
This could for example look like this:
{
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://example.com"
      },
      "Https": {
        "Url": "https://example.com",
        "Certificate": {
          "Path": "<path to .pfx file>",
          "Password": "<certificate password>"
        }
      }
    }
  }
}

For more details, check the documentation on hosting with Kestrel.
If you want to host the application on a common port, you should remember that there can only ever be a single process that listens on a port. So if you have some other application already listening on port 80 and 443, you will not be able to host your application with Kestrel on those ports. This is a limitation of the hosting model with just Kestrel since every application is a separate process. In contrast, hosting through a reverse proxy, such as IIS or nginx, allows you to to host multiple applications on the same port because it is the reverse proxy process that is listening on those ports.


text:
Q: NOSQL (RavenDB) Query from a folder on C: Drive I have a database on the C drive and I need to query from it to get all of the names of restaurants. I'm new to RavenDB and can't seem to find any documentation on how to query from a folder that sits on the C drive of the computer. Does anyone have any idea on how to do this?

A: If the database was created in drive C at creation time, then RavenDB knows where it is located.
Run your RavenDB server.
Specify your localhost URL when initializing the store:
  var store = new DocumentStore
            {
                Urls = new[] {"http://127.0.0.1:8080"},
                Database = "your-database-name"
            };

  store.Initialize();

After that, you just query your database.
If you manually moved the database from its original created location to some other folder then you couldn't query.
You can Export the database and Import it to a new database in a new location.

A: You can point RavenDB server to a specific data directory - in this way you can load your database and query it.
Simply edit settings.json in the folder where you find Raven.Server.exe and write the desired data folder in DataDir property. In the end, your settings file would look similar to this:
{
  "DataDir": "D:\\foo\\bar",
 /* other settings... */
}

Note, if you run RavenDB in Docker, you can adjust the configuration using environment variables. (more about this here: https://ravendb.net/docs/article-page/4.2/csharp/start/installation/running-in-docker-container)


text:
Q: How to setup multiple cakephp projects with 1 app folder? I would like to run multiple projects frontends in the same webroot with 1 app production folder as per below:
cake/
app/
controllers/
webroot/
--project_1/index.php
--project_2/index.php
I am doing this so that i can manage version control using the same admin panel. And when i need to deploy each site i will upload the latest app and webroot folder.
Thank you

A: You have to create different folder for different frontend like below folder structure for Cakephp 2.2.4
app
---->Config
---->Controller
---->Model
---->Views
---->webroot
---->.htaccess
---->index.php
admin
---->Config
---->Controller
---->Model
---->Views
---->webroot
---->.htaccess
---->index.php
lib
plugins
vendors
.gitignore
.htaccess
index.php

Means you have to copy app folder multiple times for setup multiple frontend. setup database same, so you can use admin folder as admin and other app1,app2 folders as frontend.


text:
Q: Java offline generation polkadot address I used SCALE Codec for java offline address generation.  but I see that generated address and polkadot.js generated address are not alike.
I use bitcoinj 's MnemonicCode generation mnemonic, and I toseed the mnemonic get seed;
this is my code;
public void createAddress() throws Exception {
    System.out.println("Generate a new Root Key + derive a `demo` address from that key");
    int number = 0;
    byte[] initialEntropy = new byte[128 / 8];
    SecureRandomUtils.secureRandom().nextBytes(initialEntropy);
    String mnemonic = "devote fatigue dice clock lock cross creek neutral minute achieve betray curve";
    String[] mm = mnemonic.split(" ");
    List<String> strings = Arrays.asList(mm.clone());
    System.out.println(mnemonic);
    String n =  Utils.SPACE_JOINER.join(strings);
    System.out.println(n);
    byte[] seed = toSeed(strings, "");
    String s = Hex.encodeHexString(seed);
    System.out.println(s);
    Schnorrkel instance = Schnorrkel.getInstance();
    Schnorrkel.KeyPair rootKey = instance.generateKeyPairFromSeed(seed);
    System.out.println("  Root Key: " + Hex.encodeHexString(rootKey.getSecretKey()));
    Schnorrkel.KeyPair key = instance.deriveKeyPair(rootKey, Schnorrkel.ChainCode.from("".getBytes()));
    Address address = new Address(SS58Type.Network.LIVE, key.getPublicKey());
    System.out.println("   Address: " + address);
    System.out.println("Public Key: " + Hex.encodeHexString(key.getPublicKey()));
    System.out.println("Secret Key: " + Hex.encodeHexString(key.getSecretKey()));
}

 public static byte[] toSeed(List<String> words, String passphrase) {
    checkNotNull(passphrase, "A null passphrase is not allowed.");

    // To create binary seed from mnemonic, we use PBKDF2 function
    // with mnemonic sentence (in UTF-8) used as a password and
    // string "mnemonic" + passphrase (again in UTF-8) used as a
    // salt. Iteration count is set to 4096 and HMAC-SHA512 is
    // used as a pseudo-random function. Desired length of the
    // derived key is 512 bits (= 64 bytes).
    //
    String pass = Utils.SPACE_JOINER.join(words);
    String salt = "mnemonic" + passphrase;

    final Stopwatch watch = Stopwatch.createStarted();
    byte[] seed = PBKDF2SHA512.derive(pass, salt, 2048, 32);
    watch.stop();
    System.out.println("PBKDF2 took {}" +  watch);
    return seed;
}

polkadot.js generated address is "12EgmkT6NHjTjtwcvfBFu1dkPEN9TLFo3ftA4L2ZcmkCfQCp";
i use my code generated address is "12YTJRjPRsw34wBp2Ewfr9oBP9w47RpKKw4CPZF2zaCga1Hk"
how do I generate similar polkadot.js' address ?


text:
Q: StyleCop For Resharper - Where's It Gone Im a great fan of resharper, and used to use the stylecop for resharper plugin a while back.
I wanted to use it again today but the stylecop for resharper codeplex site says that stylecop for resharper is now integrated into stylecop.
So I installed stylecop (4.6), but my resharper (5.1) appears to be unchanged.
I particularly liked using the code formatting settings that were included in the stylecop for resharper package (I think the file was 'StyleCopCodeStyle.xml', which could be used in the resharper options to set the code formatting and cleanup behaviour) - this xml file is now gone.
Am I missing something. Theres zero doumentation about this stylecop/resharper marriage, and I clueless as to what I am actually getting
Can anyone shed some light on this ?

A: Just an update for ReSharper 9:
To install ReSharper & StyleCop together follow these steps:

*

*Close all Visual Studio Applications (Important!!).

*Install ReSharper by double clicking the executable and following the installation process. This step will require administration rights (most likely). The precise steps to follow are unknown as they are likely to be different in the trial versus full version.

*Download the stylecop msi file from here: https://stylecop.codeplex.com/releases/view/79972

*Install it by double clicking and following a standard install process.
NOTE: It might be required to move the install files into a different directory from C: because otherwise if the user does not have administration rights they will not be able to supress rules.

*Open Visual studio and there should be a new menu item in the top menu bar called ReSharper. Select Extension Manager…

*A new window should open with a list of all of the possible extensions for resharper. Search (top right of the window) for "ReSharper.StyleCop" and press the install button.

*Follow the basic installation instructions for this add-on.

*Restart visual studio.

*All done!!

A: On the StyleCop project home page, it is quite clearly states that StyleCop 4.5 is the version that is compatible with Resharper 5.1.


text:
Q: Адаптирование анимации в android Помогите, пожалуйста, разобраться. Я окончательно запутался.
Есть у меня условно кнопка, её размеры заданны в dp - тут все понятно, она отображается на всех устройства +/- одинаково.
Но как её одинаково перемещать на всех устройствах? Есть ли какой-то способ задать перемещение в dp? Или я что-то упустил?

button10 = ObjectAnimator.ofPropertyValuesHolder(pr10,
                PropertyValuesHolder.ofFloat("x", 0, 250),
                PropertyValuesHolder.ofFloat("y", 1050, 140));
        button10.setDuration(getSpeed());
        button10.setRepeatCount(ObjectAnimator.INFINITE);
        button10.setRepeatMode(ObjectAnimator.REVERSE);
        button10.start();

up:
По экрану движутся кнопки (около 10 шт), пример анимации выше, при нажатии на любую из них создается новая кнопка, которая отправляется на свое расположение (зависит от очередности нажатия):

ObjectAnimator button_copy_button10 = ObjectAnimator.ofPropertyValuesHolder(copy_pr10,
                PropertyValuesHolder.ofFloat("x", ListCoordinateX_1.get(0)),
                PropertyValuesHolder.ofFloat("y", LineY_1.get(0)));
        button_copy_button10.setDuration(1500);
        button_copy_button10.start();

Координаты ListCoordinateX_1.get(0) и  LineY_1.get(0)) берутся из списка. Вот эти  точки мне и надо задавать так, что бы они были одинаковы под все разрешения.

up:
Разобрался, сделал так:
        protected ArrayList LineY_1 = new ArrayList();
    public Point viewLocatedAt(View v) {
    int[] location = new int[2];
    v.getLocationOnScreen(location);
    int x = location[0];
    int y = location[1];
    return new Point(x, y);
    } //определение координат

    int f = viewLocatedAt(imv5).y - (pr1.getHeight()/4 );
    LineY_1.clear();
    LineY_1.add(f);

*

*imv5 - элемент куда должна переместиться кнопка

*pr1 - кнопка. Так как все они одинаковы, то используются размеры первой.

A: Например можно решить проблему в лоб - переводить нужное количество dp в пиксели в рантайме. px = dp * scale, где скейл можно получить из описания дисплея
float scale = getContext().getResources().getDisplayMetrics().density;


text:
Q: Install Selenium webdriver with intellij on mac os x I am a newbie in selenium, trying to learn step by step. I have a system - Mac os x 10.6.8 with current jdk 1.6. Please help me with the instructions on how to install Selenium webdriver  set up with Intellij 12 on this mac. I found various articles on windows but I have a hard time to find one for mac.
Thanks.

A: You can use Maven to manage your dependencies, but if it is too complicated for your project - just add the Java? webdriver to your path in intellij
See example: how to add a jar to my lib/ directory in intelliJ and have the classes available for my web.xml?


text:
Q: `[react/jsx-max-props-per-line]` eslint rule, compound settings I'm looking at adding [react/jsx-max-props-per-line] to my config based on a request from the devs and I'm trying to find out...
Is there a way to have a rule that applies on when: multiline and another on when: always?
I'm wanting a maximum of five when we are within the always and a max of one on the multiline.

A: No there is currently no way to use the rule the way you want. This feature request is being tracked in the following issue:
https://github.com/yannickcr/eslint-plugin-react/issues/2735
But for your specific case you can try using prettier. It enforces maximum 1 prop per line in case of multi-line tags. And with its printWidth property you may get similar effect to around 5 props.


text:
Q: Python : Using regex to select a text in a big text s="""set(Q)
    {
information 1
    }

set(CP)
    {
information 2
    }
set(R)
    {
information 3
    }
"""

how can a make a function f that takes as input a identifier like (CP , R) to select exactely set
example :   f("R") ------> set(R)
    {
information 3
    }
NB : Whene I used this code :  it gave me :
set(Q)
    {
information 1
    }
set(CP)
    {
information 2
    }
set(R)
import re
def f(identifier) :

re.findall(r"set\({}\.+set)".format(identifier),s)

A: You have to use re.finditer to get the index of your search pattern, then looping through string until }, saving at the same time content you need
import re

s = """set(Q)
    {
information 1
    }

set(CP)
    {
information 2
    }
set(R)
    {
information 3
    }
set(Q)
    {
information 13
    }
"""
# print (s)

def f(identifier=''):
    var_to_return = []
    search_result = re.finditer(r'set\('+identifier+r'\)', s)
    for result in search_result:
        str_to_save = ''
        idx = result.span()[1]
        while True:
            str_to_save += s[idx]
            idx += 1
            if str_to_save[-1] == '}':
                break

        var_to_return.append(str_to_save)
    return var_to_return

print(f('Q'))

prints an array with elements found:

['\n    {\ninformation 1\n    }', '\n    {\ninformation 13\n    }']


text:
Q: SQL Error wp_commentmeta - incorrect table definition I'm trying to import a database and wonder how I can stop getting the following error?

"#1075 - Incorrect table definition; there can be only one auto column
  and it must be defined as a key "

Here's the result when importing using PHPMyAdmin.
SQL query:
--
-- Database: `db_factorypattern`
--

-- --------------------------------------------------------

--
-- Table structure for table `wp_commentmeta`
--

CREATE TABLE IF NOT EXISTS `wp_commentmeta` (
  `meta_id` bigint(20) unsigned NOT NULL auto_increment,
  `comment_id` bigint(20) unsigned NOT NULL default '0',
  `meta_key` varchar(255) default NULL,
  `meta_value` longtext
) ENGINE=MyISAM AUTO_INCREMENT=2610 DEFAULT CHARSET=utf8;

MySQL said: Documentation

"#1075 - Incorrect table definition; there can be only one auto column
  and it must be defined as a key "

A: I am not sure where you got that export code but I don't see the PRIMARY KEY defined as it should be. Take a look at the code from Core that creates the table:
87  CREATE TABLE $wpdb->commentmeta (
88    meta_id bigint(20) unsigned NOT NULL auto_increment,
89    comment_id bigint(20) unsigned NOT NULL default '0',
90    meta_key varchar(255) default NULL,
91    meta_value longtext,
92    PRIMARY KEY  (meta_id),
93    KEY comment_id (comment_id),
94    KEY meta_key (meta_key($max_index_length))
95  ) $charset_collate;

Take a look at line 92. That is missing from your "create" statement.

A: This technique worked for me

*

*Click the "Export" tab for the database

*Click the "Custom" radio button

*Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.

*Scroll to the bottom and click "GO".
I'm not certain if doing this causes any data loss, however in the one time I've tried it I did not notice any. Neither did anyone who responded in the forums linked to above.


text:
Q: Ajustar Paneles Automaticamente Buenas tardes, este día mi pregunta es un tanto simple pero no se como resolverlo, estoy creando un windows forms principal, en el que tengo dos panel, y los cuales requiero se ajusten de forma automatica a la resolución de mi pantalla sin tener que modificar todo el tamaño de mi form y estar jugando con los tamaños.
Si alguien sabe como hacerlo le estare muy agradecido saludos.

A: Sería mas fácil si colocaras una imagen del formulario con los páneles para tener una mejor idea de lo que quieres hacer.
Pero bueno, lo que entiendo es que, si cambias la resolución, los páneles se ven, o muy grandes, o muy pequeños, y quieres que siempre se vean del mismo tamaño, independientemente de la resolución de pantalla.
Si es eso lo que quieres, tienes que reajustar los tamaños obteniendo el radio de aspecto, por ejemplo en esta respuesta dan el siguiente código: https://stackoverflow.com/questions/2802015/controls-resize-based-on-screen-resolution
Primero guardas el alto y ancho de la pantalla en pixeles:
int i_StandardHeight = 768;// la resolución de pantalla (alto en pixeles) inicial
                int i_StandardWidth = 1024; ;// resolución de pantalla (ancho en pixeles) al iniciar la aplicación

Y cuando redibujes los páneles:
                int i_PresentHeight = Screen.PrimaryScreen.Bounds.Height;
                int i_PresentWidth = Screen.PrimaryScreen.Bounds.Width;
                float f_HeightRatio = new float();
                float f_WidthRatio = new float();
                f_HeightRatio = (float)((float)i_PresentHeight / (float)i_StandardHeight);
                f_WidthRatio = (float)((float)i_PresentWidth / (float)i_StandardWidth);
                foreach (Control c in this.Controls)
                {
                    if (c.GetType().ToString() == "System.Windows.Forms.Button")
                    {
                        Button obtn = (Button)c;
                        obtn.TextAlign = ContentAlignment.MiddleCenter;
                    }
                    if (c.HasChildren)
                    {
                        foreach (Control cChildren in c.Controls)
                        {
                            cChildren.SetBounds(Convert.ToInt32(cChildren.Bounds.X * f_WidthRatio), Convert.ToInt32(cChildren.Bounds.Y * f_WidthRatio), Convert.ToInt32(cChildren.Bounds.Width * f_WidthRatio), Convert.ToInt32(cChildren.Bounds.Height * f_HeightRatio));
                            //cChildren.Font = new Font(cChildren.Font.FontFamily, cChildren.Font.Size * f_HeightRatio, cChildren.Font.Style, cChildren.Font.Unit, ((byte)(0)));
                        }
                        c.SetBounds(Convert.ToInt32(c.Bounds.X * f_WidthRatio), Convert.ToInt32(c.Bounds.Y * f_WidthRatio), Convert.ToInt32(c.Bounds.Width * f_WidthRatio), Convert.ToInt32(c.Bounds.Height * f_HeightRatio));
                       // c.Font = new Font(c.Font.FontFamily, c.Font.Size * f_HeightRatio, c.Font.Style, c.Font.Unit, ((byte)(0)));
                    }
                    else
                    {
                        c.SetBounds(Convert.ToInt32(c.Bounds.X * f_WidthRatio), Convert.ToInt32(c.Bounds.Y * f_WidthRatio), Convert.ToInt32(c.Bounds.Width * f_WidthRatio), Convert.ToInt32(c.Bounds.Height * f_HeightRatio));
                       // c.Font = new Font(c.Font.FontFamily, c.Font.Size * f_HeightRatio, c.Font.Style, c.Font.Unit, ((byte)(0)));
                    }
                }
                this.Height = Convert.ToInt32(i_StandardHeight * f_HeightRatio);
                this.Width = Convert.ToInt32(i_StandardWidth * f_WidthRatio);

Ya solo tienes que capturar el evento de cambio de resolución y ahí redibujar los páneles:
Microsoft.Win32.SystemEvents.DisplaySettingsChanged

Pero si lo que quieres es que los páneles se mantengan siempre en un lugar y con un espaciado aunque cambie el tamaño del formulario, puedes jugar con la propiedad 'Anchor' o meter los páneles en un TableLayoutPanel.


text:
Q: Invoking Ember.js controller function by automating action Currently my site includes a search bar in my index.ejs file that uses {{action createSearch}} to call my controller's "createSearch" function when a user presses enter or clicks my search button. This works perfectly! Now I am testing out new functionality and want to call my newSearch function directly from my index.ejs file without any user interaction. I've tried using jquery on load to simulate the key press / click but the controller but that doesn't seem to invoke the action event.
edit: functional index.js code included
         {{view Ember.TextField id="new-search" placeholder="enter a few keywords"
             valueBinding="newSearch" action="createSearch"}}

SEARCH

A: For system-level actions like this you are better off using events on the ApplicationRoute. Your controllers/views can send an event like createSearch that the route handles typically via the controller that knows how to do this.
App.ApplicationRoute = Em.Route.extend({
  events: {
    createSearch: function(query) {
      var controller = this.controllerFor('search');
      controller.doSearch(query);
    }
  }
});

From any controller's action handler you can trigger the event with,
this.send('createSearch', query);

Or from a view,
this.get('controller').send('createSearch', query);

You will need to wire your individual action handlers to do this event triggering.


text:
Q: str_replace spaces with hyphens in A tag's name attribute $string = preg_replace("#[name=([a-zA-Z0-9 .-]+)*]#",''."$1",$string);
This part of script doesn't work:
str_replace(' ', '-', "$1")

I need to replace " " with "-",
i also try preg_replace inside main preg_replace, str_ireplace also
But this is still don't working

A: The replacement is evaluated upfront and not on each replace. But you can do so by either using the e modifier in your regular expression:
$string = preg_replace("#\[name=([a-zA-Z0-9 .-]+)*]#e", '"$1	"', $string);

Or by using preg_replace_callback:
function callbackFunction($match) {
    global $front_page;
    return ''.$match[1].'	';
}
$string = preg_replace_callback("#\[name=([a-zA-Z0-9 .-]+)*]#", 'callbackFunction', $string);

A: I guess you will have to do it in two steps, since $1 cannot be used in str_replace(). $1 doesn't really exist as a variable, it is only a placeholder in the replacement string.


text:
Q: Assign 0 to variable in gcc extended assembly I have the following code:
#include <stdio.h>
void main(){
    int x=0, y=0,i=100;
    for (;i<1000; i++,x+=32){
        if (x == 25*32) {
            y+=32;
            asm volatile("pushl %%eax\n\t"
                         "movl $0, %%eax\n\t"
                         "popl %%eax\n\t"
                         :"=a"(x)
                         :"a"(0)
                         );
        }
        printf("%d %d\n", x, y);
    }
}

Basically, what I want to do is, set the variable x to 0 but I don't quite understand what the assembly code does, and it actually does set x to 0 but I'm not sure whats going on. can somebody explain what's going on? (just for the sake of learning assembly and C).

A: Here is what your asm construct says:

*

*In "=a"(x), you tell the compiler that the assembly will write (=) to the %eax (a) register, and you want the compiler to assign that result to x ((x)).

*In "a"(0), you tell the compiler you want it to put a 0 ((0)) in %eax (a), and the assembly will read it.

*Then push %%eax saves %eax on the stack, movl $0, %%eax puts 0 in %eax, and popl %%eax restores the saved value to %eax.

So, what happens is:

*

*The compiler puts 0 in %eax.

*Your instructions save 0 on the stack, move 0 into %eax, and restore 0 from the stack.

*The compiler uses the 0 in %eax as the value of x.

So, this works, but it is inefficient. You can get the same effect with this:
asm volatile("movl $0, %[MyName]"
    : [MyName] "=r" (x)
);

What this says is:

*

*There are no inputs (because the second ":" is absent).

*As before, the = tells the compiler these instructions will write a result.

*The r says the result will be written to a register, but the compiler gets to pick the register.

*The [MyName] tells the compiler to change %[MyName], where it appears in the assembly code, to the name of the register the compiler picks.

*As before, the (x) says to use the value in the register after the assembly code as the new value of x.

*Finally, the instruction movl $0, %[MyName] says to move 0 to the register named by %[MyName].

Because the compiler gets to pick the register, you do not have to save and restore it in the assembly language. The compiler is responsible for making sure it does not need that register for anything else.
Being able to name the operands as I have done with [MyName] is a new feature in GCC. If your version does not have it, you can do this instead:
asm volatile("movl $0, %0"
    : "=r" (x)
);

Without names, each operand gets a number, starting at 0, and incremented in the order the operands appear in the input/output specifiers. Since we had only one operand, it was %0.


text:
Q: Get data from cell and pass to app script and run API when cell gets update I'm using an app script to get data from cells and pass that data to API. So whenever a color gets the change we have to take that value pass in APIs and store response in G Column. Can someone help
function callNumbers() {

  // Call the Numbers API for random math fact
  var response = UrlFetchApp.fetch("http://numbersapi.com/random/math");
  Logger.log(response.getContentText());

  var fact = response.getContentText();
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(sheet.getLastRow() + 1,1).setValue([fact]);

}
function onEdit(e) {
var row = e.range.getRow();
if (row > 1 && e.source.getActiveSheet().getName() === "Sheet1") {
   e.source.getActiveSheet().getRange(row, 14).setValue(new Date());
} else {
   if ((row > 1 && e.source.getActiveSheet().getName() === "Sheet2") || (row > 1 && e.source.getActiveSheet().getName() === "Sheet3")) {
       e.source.getActiveSheet().getRange(row, 6).setValue(new Date());
   }}}


text:
Q: What should be the prop type of passing a variable down in a child component via function Given the following component:
Component.propTypes = {
  // not right:
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]),
}

export default function Component({ children }) {
  return children({ someValue: "foobar" });
}

AnotherComponent.propTypes = {
  value: PropTypes.string,
}

export default function AnotherComponent({ value }) {
  return <p>{value}</p>
}

Used like:
<Component>
 {(someValue) => (<AnotherComponent value={someValue} />)}
</Component>

Gives the error: Warning: Failed prop type: Invalid prop 'children' supplied to 'Component'.
What is the proptype for this?

A: Try PropTypes.func:
Component.propTypes = {
  children: PropTypes.func
};

As for "real-life" example, you can check the children type of AutoSizer [2]