text:
Q: Combining "if-let" with "OR" so functions may be executed several times on one value What I am trying to achieve is to execute functions on a value several times when several conditions are met. In particular say we have two variables a and b.
When a is true the value is transformed by the function associated to a, then
when b is true the new value is transformed by the function associated to b.
So when the initial value is 0 and the functions are inc and #(+ 5 %) we can get 0, 1, 5 or 6.
My approach was as following but not succeed
user> (def initial-number 0)
user> (if-let [a true b true] (cond-> initial-number a inc b (#(+ 5 %))))
IllegalArgumentException clojure.core/if-let requires exactly 2 forms in binding vector in user:  clojure.core/if-let (core.clj:1758)
user>

A: The code you have will work as described if you substitute if-let for let. All of your conditional logic exists within the cond->.
(def initial-number 0)

(let [a true  b true]  (cond-> initial-number a inc b (#(+ 5 %)))) => 6
(let [a false b true]  (cond-> initial-number a inc b (#(+ 5 %)))) => 5
(let [a true  b false] (cond-> initial-number a inc b (#(+ 5 %)))) => 1
(let [a false b false] (cond-> initial-number a inc b (#(+ 5 %)))) => 0


text:
Q: How do I use ChartJS with a background color in the space between two line charts? I would like to create a chart similar to the following it ChartJS. It's 2 line charts but with the space between the two lines filled in.

The X axis will be the time of each sample, the y axis the min & max temperature recorded at that time.
The area between the min/max is the only bit that needs to be filled in, outside the min/max lines should remain unfilled.
Is this possible with ChartJS?
Thanks
Shawty

A: Did you know abut hicgcharts

$(function () {
    $('#container').highcharts({
        chart: {
            type: 'area'
        },
        title: {
            text: 'Temp'
        },
        xAxis: {
            categories: ['1pm', '2pm', '3pm', '4pm', '5pm']
        },
        credits: {
            enabled: false
        },
        colors: [ '#910000', '#00FFFF'],
        series: [{
            name: 'Max Temp',
            data: [5, 3, 4, 7, 2]
        }, {
            name: 'Min Temp',
            data: [2, 2, 3, 2, 1]
        }]
    });
});

A: Taken from another answer but closer to what you wanted. (color only in middle).
So basically, in ChartJS you need to overlay 2 filled line charts, and make the bottom one white. (sadly it overwrites the gridlines)

$(function () {
    $('#container').highcharts({
        chart: {
            type: 'area'
        },
        title: {
            text: 'Temp'
        },
        xAxis: {
            categories: ['1pm', '2pm', '3pm', '4pm', '5pm']
        },
        credits: {
            enabled: false
        },
        colors: [ '#910000', '#FFFFFF'],
        series: [{
            name: 'Max Temp',
            data: [5, 3, 4, 7, 2]
        }, {
            name: 'Min Temp',
            data: [2, 2, 3, 2, 1]
        }]
    });
});
.highcharts-series-1 path{fill-opacity:1!important}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cloud Run deployment using image from last revision We need to deploy labels to multiple CLoud Run services using below API method
https://cloud.google.com/run/docs/reference/rest/v1/namespaces.services/replaceService
We are looking for options where we can apply labels using API without any new image deployment from Container Registry . We understand that there will be deployment and revision change while applying labels but we want that during deployment it should not pull new image from container registry rather it should use the image from last revision . Any configuration parameter in Cloud Run to prevent new images being pulled while applying labels using API or gcloud run services update SERVICE --update-labels KEY=VALUE

A: The principle of Cloud Run (and Knative, because the behavior is the same) is that the revision is immutable. Thus, if you change something in it, a new revision is created. You can't fake it!
So, the solution is to not use the latest tag of your image, but the SHA of it.
# the latest
gcr.io/PROJECT_ID/myImage
gcr.io/PROJECT_ID/myImage:latest

# A specific version
gcr.io/PROJECT_ID/myImage:SHA123465465dfsqfsdf

Of course, you have to update your YAML for this.


text:
Q: Jersey (REST) throw exception and map to HTTP error or return custom error code? Basically I written a REST service and my business logic requires me to validate the input. For instance make sure the format of phone number is (###)###-####. If it is not, it should return invalid phone number. Further more I need to record all actions of the service. So when the client queries the system, they can find out what was the last action. I.e:
ACTION: ADD - SUCCESS
ACTION: ADD - INVALID PHONE NUMBER
So now I'm thinking whether I need to create my own custom error codes or just use the default HTTP ones and also record those inside the "log"
Pretty new to REST style so if my logic is off let me know...
So should I...
public void callPerson(String phone)
{
    try
      validate(phoneNumber)
      call person
    catch
        throw Invalid Phone Number
    finally
       record status to DB
}

or
public myStatusCode callPerson(String phone)
{
    try
      validate(phoneNumber)
      call person
    catch
        return myStatusCode
    finally
       record status to DB

}

In fact I also want to make sure the status gets recorded as well other wise it would not be good if say the action worked but the status update didn't. So updating the status should really be part of the "transaction"
Also another thing to keep in mind this REST service some of the actions have to communicate with an older "message" oriented service where the response and error code are in the XML response message...
Any suggestions? Thanks

A: I would recommend a HTTP status code 412 (Precondition Failed) and a String message for the error.


text:
Q: Issue with data display and constructor I have a problem with understanding constructor and this is causing me problem while displaying data with string name and string position. the first character of name and position are removed and initialized with " " (space).
please ignore any indentation problems etc because this is my first time posting here...
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

class Employee
{
    private:
        string name ; // for employee's name
        int id ;      // for employee's id number
        string department ;  // for name department
        string position ; //for position employee holds

    public:

        Employee()  // constructor
        {
            name = " " ;
            id = 0 ;
            department = " " ;
            position = " " ;
        }

        Employee ( char a , int i )
        {
            name = a ;

            id = i ;

            position = " " ;

            department = " " ;

        }

        Employee ( char a , char b , char c , int i )
        {
            name = a ;

            id = i ;

            department = b ;

            position = c ;

        }

        Employee ( const Employee &obj )
        {
            name = obj.name ;

            department = obj.position ;

            position = obj.position ;

            id = obj.id ;

        }

        int set_Name( char a )
        {
            name = a ;

            return 0;

        }

        int set_Id( int i )
        {
            id = i ;

            return 0;

        }

        int set_Position( char b )
        {
            position = b ;

            return 0;

        }

        int set_Department( char d )
        {
            department = d ;

            return 0;
        }

        string get_Name( void ) const
        {
            return name ;

        }

        int get_Id( ) const
        {
            return id ;

        }

        string get_Position( void ) const
        {
            return position ;

        }

        string get_Department( void ) const
        {
            return department ;

        }

        int set_Info( char a , char b , char c , int i )
        {
            name = a ;

            id = i ;

            department = b ;

            position = c ;

            return 0;
        }

        void get_Info ()
        {
            cout << endl  << " Enter Employee name =  " ;
            cin.ignore();
            getline(cin , name);

            cout << " Enter id number of employee = " ;
            cin >> id ;

            cout << " Enter Employee department = " ;
            cin.ignore();
            getline(cin , department);

            cout << " Enter Emloyee position in company = ";
            cin.ignore();
            getline(cin , position);

        }

        void put_Info(  )
        {
            cout << "Employees info : - " ;
            cout << "   " << name << "   "  << id << "   " << department << "   " << position << endl ;

        }

        ~Employee()
        {
            cout << " destructor executed .... " ;
        }

};

int main()
{

    Employee obj1 , obj2 , obj3 , obj4 , obj5 ;

    obj1.get_Info();
    obj2.get_Info();
    obj3.get_Info();
    obj4.get_Info();
    obj5.get_Info();

    cout << endl;

    obj1.put_Info();
    obj2.put_Info();
    obj3.put_Info();
    obj4.put_Info();
    obj5.put_Info();

    return 0;
}

A: use cin >> name; or cin >> department; before cin.ignore();
You can remove cin.ignore() when you use getline see here


text:
Q: Polymer 2.0 errors I have worked with Polymer 1.x for a while and I want to start a project from scratch with Polymer 2.0 but I get many errors. I am building a PWA as I did before, therefor I included a service worker and a manifest.json file. The errors I get are, I think, most of incompatibility between versions since they claim some classes not defined or undefined "window" object (like in the second error)
For versions I followed this guide (point: Upgrade an existing project)
https://www.polymer-project.org/2.0/docs/about_20#polymer-1-compatibility-layer
First error:
platinum-sw-register.html:111
Uncaught ReferenceError: HTMLImports is not defined at platinum-sw-register.html:111

and
Uncaught TypeError: Cannot read property 'nativeMethods' of undefined
    at pa (style-util.js:243)
    at p.u (style-properties.js:499)
    at k.T (scoping-shim.js:299)
    at k.styleElement (scoping-shim.js:243)
    at Object.styleElement (scoping-shim.js:52)
    at HTMLElement.connectedCallback (element-mixin.html:636)
    at HTMLElement.connectedCallback (legacy-element-mixin.html:81)

I have the following index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">

    <title>AppTest</title>

    <link rel="import" href="bower_components/app-layout/app-layout.html"/>
    <link rel="import" href="bower_components/platinum-sw/platinum-sw-elements.html"/>
    <link rel="manifest" href="manifest.json"/>
    <script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
    <!-- <script src="bower_components/web-animations-js/web-animations.min.js" async></script> -->
    <link rel="import" href="bower_components/app-layout/app-drawer/app-drawer.html">
    <link rel="import" href="bower_components/app-layout/app-header/app-header.html">
    <link rel="import" href="bower_components/app-layout/app-toolbar/app-toolbar.html">
  </head>

  <body>
    <platinum-sw-register
      auto-register
      skip-waiting
      clients-claim
      reload-on-install
      href="sw-import.js">
      <platinum-sw-cache
        default-cache-strategy="networkFirst">
      </platinum-sw-cache>
    </platinum-sw-register>

    <app-header reveals>
      <app-toolbar>
        <div main-title>My app</div>
      </app-toolbar>
    </app-header>
    <app-drawer id="drawer" swipe-open></app-drawer>
  </body>

  <script>
  </script>
</html>

and my bower.json
{
  "name": "polymer-2-carousel",
  "private": true,
  "dependencies": {
    "polymer": "Polymer/polymer#^2.0.0-rc.3",
    "platinum-sw": "PolymerElements/platinum-sw#2.0-preview",
    "app-layout": "PolymerElements/app-layout#2.0-preview"
  }
}

As you can see the application is a skeleton very simple (just a test to start with) so there should not be much to get wrong or to investigate to find the cause of the error but I do not understand what is the problem and how to fix it. Any help would be appreciate.

A: I found this problem too, so I have to change these lines below in bower-components/platinum-sw/platinum-sw-register.html file:
value: document._currentScript ? document._currentScript.baseURI :
      (HTMLImports.importForElement ? HTMLImports.importForElement(document.currentScript).baseURI :
      (document.currentScript ? document.currentScript.baseURI : './'))

To:
value: document._currentScript ? document._currentScript.baseURI :
      (document.currentScript ? document.currentScript.baseURI : './')

I hope that helps.


text:
Q: How to include images into jsp with spring mvc I can't display my image into a jsp page.
my webapp structure
My configuration class
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "it.gruppoaton")
public class AppConfig extends WebMvcConfigurerAdapter{

@Bean
public ViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/images/**").addResourceLocations("/images/").setCachePeriod(31556926);
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

My Header
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<img align="left" src="<c:url value="/logoAtonBianco.png"/>" alt=""/>

I searched for hours on this site, and it looks like i did everything done, but it still don't working and can't display anything. Any advice?


text:
Q: Symfony2 Doctrine2 Cascading defined but not working I have an entity which has a relationship which contains settings (multiple). To add or delete an entity I have to use cascading, but it isn't working and I can't find the error in my code.
The entity:
/**
 * @var DepartmentSettings
 *
 * @ORM\OneToMany(targetEntity="DepartmentSettings", mappedBy="department", cascade={"persist", "refresh", "remove"}, orphanRemoval=true)
 */
protected $departmentsettings;

The error I'm getting:
An exception occurred while executing 'DELETE FROM department WHERE id = ?' with params [13]:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`hotflo20`.`department_settings`, CONSTRAINT `FK_DCFBBAEFAE80F5DF` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`))

Hopefully someone can solve this issue. I'm really stuck at the moment

A: cascade settings only appears then you operate with your entites via EntityManager. Then you make a DELETE query it doent care. You need to set onDelete="CASCADE" in DepartmentSettings entity which make a trigger in database.
/**
 * @ORM\ManyToOne(targetEntity="Department", inversedBy="departmentsettings")
 * @ORM\JoinColumn(name="department_id", referencedColumnName="id", onDelete="CASCADE")
 */
protected $department;


text:
Q: Is declaring "belongs_to model_name" less secure than declaring "belongs_to model_id"? Are there any differences? Say my Tweet belongs to a User
Is it better (as in are there any security, ease of use or other reasons...) to declare:
attr_accessible :user

OR
attr_accessible :user_id

OR just both
attr_accessible :user, :user_id

A: If your User has_many :tweets your user wouldn't have a tweet_id or a tweet. It would have an array of tweets. attr_accessible whitelists attributes so that they can be mass assigned.
What exactly were you trying to do by defining the attr_accessible :tweet?
Instead of using attr_accessible for :tweet, or :user Rails provides
accepts_nested_attributes_for :tweets
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html


text:
Q: how do i get a variables ASCII value and use it in a sum for(i=0;i < strlen();i++;)
{
postnum = argv[i] - k
}

i'm trying to write a Caesars encryption program for a course i'm taking, and pretty much i want to have the ASCII value of the i'th character in the string to have a key(k) added to the ASCII value to encrypt the string.
i know to get a chars ASCII number you do 'a' or what ever letter you need but how do i get it from a char variable?

A: Just treat each character as an int and add k to the char:
 int i, k = 1;
 char *str = "abc";
 char *ctext = malloc(sizeof(char) * (strlen(str) + 1));
 for (i = 0; i < strlen(str); i++) {
      ctext[i] = str[i] + k;
 }
 ctext[i] = '\0';

 printf("%s\n", ctext);

will output:
bcd

A: I did withouth the '' (using C with GCC ver 4.9.2).
I think it's because my array is a string, so is a char type variable.
Code:
while(string[i] != '\0'){

    string[i] = string[i] + key;

    i++;
}

printf("\n %s", string);


text:
Q: Font preload. Does this warning mean that woff wasn't loaded at all or it's okay for a fallback font? I added preload to woff2 and woff fonts, but only woff2 was preloaded (I guess).
This is what I have in html :
<link
      rel="preload"
      href="/assets/fonts/aclonica-latin-regular-65f8adef.woff2"
      as="font"
      type="font/woff2"
      crossorigin
    />

<link
      rel="preload"
      href="/assets/fonts/aclonica-latin-regular-f5a98d57.woff"
      as="font"
      type="font/woff"
      crossorigin
    />

Console warning message:
The resource at "http://localhost:3000/assets/fonts/aclonica-latin-regular-f5a98d57.woff" preloaded with link preload was not used within a few seconds. Make sure all attributes of the preload tag are set correctly.


text:
Q: Can I use the userId intead of the jwt token? What if I hash the userId and store it in the local storage. And then on every route, I send a request to the server and the server finds the user by that id ( unhashed ) which will be in the authorization header.
Will it be considered good practice and will it be safe ?

A: There are several points to consider here:

*

*Storing sensitive data (passwords, tokens etc.) is generally a bad idea, because it can be a security risk (XSS) and is also difficult to handle, because people clear their caches and you sort of give up control of the data you put in there. Another way would be to use cookies, but those can also lead to security vulnerabilities (CSRF/XSRF exploits)

*JWT is a very secure and commonly used strategy (if you use it right). It's important to store the secret safely. It enables you to authenticate users without the need to store a session in a database, because it has an expiration date. You should read more about JWT online to see how it works in detail.

*Hashing something doesn't mean it's secure. Sure, you can't just "unhash" it, hashing is usually a one way operation (there's a huge discussion about the possibilities of unhashing, but I'm not going to add my opinion to this, just consider it to be impossible at this point). Either way, hashing itself isn't enough to secure information. It matters where you place the hashed information (best to safely store it in a database, isolated from the user and other people).

*You CAN implement your own authorization strategy, but there are a lot of existing, safe authorization methods. OAuth, API Keys, bearer tokens, they all usually get sent through the authorization header. But you probably wouldn't want to store those keys in your browser.

Hope I could help a bit, if something's unclear, let me know :)


text:
Q: Does using CodeIgniter's XSS filtering avoid the need to escape when outputting? CodeIgniter provides a couple of convenient APIs for XSS filtering.

*

*'global_xss_filtering' in config.php.

*'xss_clean' rule for individual fields, when using the form validation library.

If you use this feature, does it avoid the need to escape fields when outputting them?

A: There are some situations where xss_clean will not protect you.  Issue 470 includes this example:
public function index()
{

    $name = $this->security->xss_clean('hover me" onmouseover=alert("XSS2") "');
    echo '
Name:<input value="'.$name.'">';
    echo '';
}

The response from developers was that this is by design, and to suggest that $name should have been escaped using form_prep().
If you use set_value('field-name', 'default') in order to preserve user input when a form fails validation), that will ... attempt to call form_prep() for you.  The caveat is that if you don't have the form validation library loaded, it won't escape the 'default' parameter.  (Issue 1781, fixed in 3.0-dev).
If you are running the current 3.0-dev, then form_prep() is more specific about which characters it escapes.  It should avoid XSS either way; it just has unexpected results in some situations.  E.g. if you try to enter a literal "&" in 3.0-dev, and then the form fails validation, the field value will change to & without warning.  This change was an attempt to work around problems with double-escaping (issue 1953).


text:
Q: DynamicResource doesn't work when combined with AppThemeBinding (Maui) I have a ResourceDictionary that contains a Style element.
    <Style TargetType="Page" ApplyToDerivedTypes="True">
        <Setter Property="Padding" Value="0"/>
        <Setter Property="BackgroundColor" Value="{AppThemeBinding Light={DynamicResource Primary}, Dark={DynamicResource Secondary}}" />
    </Style>

And I have created two different ResourceDictionies that contain Colors with identical keys.
    //Theme 1
    <Color x:Key="Primary">#512BD4</Color>
    <Color x:Key="Secondary">#DFD8F7</Color>
    <Color x:Key="Tertiary">#2B0B98</Color>

    //Theme 2
    <Color x:Key="Primary">#ff0000</Color>
    <Color x:Key="Secondary">#0000ff</Color>
    <Color x:Key="Tertiary">#00ff00</Color>

The goal is be able to dynamical swap the theme file at runtime. For now, I am just loading a single theme into my App's MergedDictionaries
<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles/Theme1.xaml" />
                <ResourceDictionary Source="Resources/Styles/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

However, when I run the app, my page background is White. It's not using any of the colors from my theme.
If I change my Style rule to not using AppThemeBinding, it works as expected. <Setter Property="BackgroundColor" Value="{DynamicResource Primary}" />
If I switch to StaticResources, it also works. <Setter Property="BackgroundColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource Secondary}}" />
Is it possible to combine AppThemeBinding with DynamicResource?
I've only tested this on Android.

A: Last time I checked this was an open issue, and I checked again just for this and it seems it's still open.
More information here: https://github.com/dotnet/maui/issues/13570
For the time being I would recommend having multiple static resources and switching between them on runtime, as long as you don't have a color picker or something, in that case you might have a hard time.
Update
Well before DynamicResources were a thing that worked in Xamarin Forms (there was a similar issue on XF as well when it first came out), I remember we used to conditionally compile our OnAppearing methods for the view's code-behind with dictionary calls to get the data for eg:
var tc1= (Color) Application.Current.Resources["TextColor1"];
var tc2= (Color) Application.Current.Resources["TextColor2"];

And now based on my condition I either bind my correct TextColor or just assign it directly to the control.
To avoid doing it over and over again you could just do this once in a base class (can also be done in the base constructor so it's always available).


text:
Q: Can I restore a PHP SESSION by its ID? Im uploading files with the uploadify plugin.
the PHP SESSION is lost during upload, is there a way to restore the session?
Perhaps by its id?

A: Yes. You need to add an option to uploadify:
$('#upload').uploadify({
    'scriptData':{'session_name':"<?php echo session_id(); ?>"}
});

And you need to add this to your PHP:
<?php
session_id($_POST['session_name']);
session_start();
?>

Then everything will be as expected.


text:
Q: Why do we need SSH keys in git? I am having a very little or no familiarity with git.I have been following a tutorial and there the person generate ssh keys, this was my first encounter with it.
Prior to it, i was following the command written in the git or adding it directly by JetBrains ide.
I know it should be encrypting the connection but when uploading to GitHub, it means I am making my code public. Then why encryption? Why going all these troubles in cmd.

A:
Why do we need SSH keys in git?

SSH keys identify the user that is interacting with the git remote repository.

I know it should be encrypting the connection but when uploading to GitHub, it means I am making my code public.

Not necessarily, there are private repositories in GitHub. Also, there are other hosting providers as well.

Why going all these troubles in cmd.

With SSH authentication you don't need to enter your credentials when interacting with the remote.


text:
Q: Make: Set shell and source a file at the same time? Suppose I would like to set a shell in make:
SHELL:=/usr/bin/env bash

Next, suppose I have some runcom/bash file I would like to source as well.  This file optionally activates a virtual environment:
if [ -d venv ]; then source venv/bin/activate fi;

However, if I write:
SHELL:=/usr/bin/env bash && source runcom/bash

This fails.  However, if I deposited the venv logic into the local ~/.bashrc and write:
SHELL:=/usr/bin/env bash -l

I can get the exact functionality I need.

But, I have to deposit something that should remain downstream from the local user into the user's upstream environment -- I'd rather not.
Is there a way to get the make shell to source a file at the declaration step in the make start-up process?

A: This can't work:
SHELL:=/usr/bin/env bash && source runcom/bash

Because SHELL tells make how to invoke the shell; if you make the contents of SHELL be a shell script then make has to invoke the shell to interpret how to invoke the shell, which means it has to invoke the shell to invoke the shell to interpret how to invoke the shell, etc.
So, SHELL must be either a simple command or, at most, a simple set of arguments that can converted into an argv list and passed to exec(2).
So, this is really a shell question not a make question: how can you get the shell to source arbitrary stuff when it starts without changing ~/.profile or whatever?
Luckily, this is possible; see the bash man page:
   BASH_ENV
          If  this parameter is set when bash is executing a shell script,
          its value is interpreted as a filename  containing  commands  to
          initialize the shell, as in ~/.bashrc.  The value of BASH_ENV is
          subjected to  parameter  expansion,  command  substitution,  and
          arithmetic  expansion  before  being  interpreted as a filename.
          PATH is not used to search for the resultant filename.

   ENV    Similar to BASH_ENV; used when the shell  is  invoked  in  posix
          mode.

So, in your makefile you can use something like:
SHELL := /bin/bash
export BASH_ENV := runcom/bash

and that should be sufficient.


text:
Q: CalledFromWrongThreadException  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final ThraedDemo objDemo = new ThraedDemo();
    Thread objThread = new Thread() {

        @Override
        public void run() {

            objDemo.firstMethod();
        }
    };
    objThread.start();
}

class ThraedDemo {

        private void firstMethod() {
            Thread objThread = new Thread() {

                @Override
                public void run() {
                    try {
                    ((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);

                        Thread.sleep(10000);
                        Log.v("Thread","1111111111111111sleep");
                    } catch (InterruptedException ex) {
                        System.out.println("interuped exception" + ex.getMessage());
                    }
                    secondMethod();
                }

                private void secondMethod() {
        Thread objThread = new Thread() {

            @Override
            public void run() {
                try {
                ((ImageView)findViewById(R.id.ImageViewResult)).setImageResource(nums[n+1]);

                n++;

                    Thread.sleep(10000);
                   Log.v("Thread","22222222222 sleep");
                } catch (InterruptedException ex) {
                    System.out.println("interuped exception" + ex.getMessage());
                }
                firstMethod();
            }
        };
        objThread.start();
    }

            };
            objThread.start();
        }

    }

I use the above code but it is not running.it got CalledFromWrongThreadException what is the problem  inb the above code.Please give me some suggestions.Thanks in advance

A: I think you can't do view modifications from another thread than the UI thread, so either create handlers in the oncreate and post your thread to it, or use AsyncTask, or runOnUIThread method to send portions of code directly to the UI thread.

A: I edited your 2nd function code,  I see your code is loop forever cause the firstMethod call secondMethod and the secondMethod call the new firstMethod to start and then loop forever. I removed it and moved the code update ImageView into the UI Thread, could you try this:
class ThraedDemo {

    private void firstMethod() {
        Thread objThread = new Thread() {
            @Override
            public void run() {
                try {
                    runOnUiThread(new Runnable() {
                        public void run(){
                            ((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
                        }
                    });
                    Thread.sleep(10000);
                    Log.v("Thread","1111111111111111sleep");
                } catch (InterruptedException ex) {
                    System.out.println("interuped exception" + ex.getMessage());
                }
                secondMethod();
            }
        };
        objThread.start();
    }

    private void secondMethod() {
        Thread objThread2 = new Thread() {

            @Override
            public void run() {
                try {
                    runOnUiThread(new Runnable() {
                        public void run(){
                            ((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n+1]);
                        }
                    });
                    n++;
                    Thread.sleep(10000);
                    Log.v("Thread","22222222222 sleep");
                } catch (InterruptedException ex) {
                    System.out.println("interuped exception" + ex.getMessage());
                }
            }
        };
        objThread2.start();
    }
}


text:
Q: POST fails when using replace in my Python API POST request I have a JSON dump that I am trying to post to a another application. In the payload there is a "pageGroups": "['TEST_TCIS:Oncall Schedule']", and the double quotes need to be removed to represent this output to pass the data: "pageGroups": ['TEST_TCIS:Oncall Schedule'],
I have tried to use replace but it fails. If I manually remove the double quotes out of the JSON payload it works.
Here is the code:
api_url_base = "some url"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer some token"
     }
data = {"abendCode": "",
        "action": "CREATE",
        "assignGroup": "TCIS-APP-SUPPORT",
        "component": "tcis",
        "description": "Test incident creation",
        "entered": "", "logicalName": "tcis",
        "pageGroups": "['TEST_TCIS:Oncall Schedule']",
        "priority": "",
        "racfId": "",
        "sendPage": "",
        "sysProdName": "tcis",
        "transactionId": "",
        "type": "SYSMAN"}

data = json.dumps(data)
data = data.replace("\"[", "[").replace("]\"", "]")
print(data)

response = requests.post("https://apistaging.csx.com/tcis-events/v1/events",
                         json=data, headers=headers)
response_url = json.loads(response.content.decode('utf-8'))
print(response_url)
print("response " + str(response))

Here is the output I am getting:
{"abendCode": "",
 "action": "CREATE",
 "assignGroup": "TCIS-APP-SUPPORT",
 "component": "tcis",
 "description": "Test incident creation",
 "entered": "",
 "logicalName": "tcis",
 "pageGroups": ['TEST_TCIS:Oncall Schedule'],
 "priority": "",
 "racfId": "",
 "sendPage": "",
 "sysProdName": "tcis",
 "transactionId": "",
 "type": "SYSMAN"}

{'traceId': 'd9dcd6ee-a0f3-170c-83e5-a52f2133cd31', 'error': {'code': 'APG400', 'message': 'The server could not process the request.'}}
response <Response [400]>
[Finished in 0.789s]

A: When you remove the double quotes from the already JSON-formatted data you get ['TEST_TCIS:Oncall Schedule'], but this isn't valid JSON anymore. If this is supposed to be a list containing one string, the string needs to be quoted with double quotes (") in JSON.
To do this properly, remove the quotes from the value first, and then convert it to a JSON string.
In fact, "removing the quotes" from "['TEST_TCIS:Oncall Schedule']" means to parse a string representation of a list into a list, for which there is ast.literal_eval.
import ast
import json

data = {"abendCode": "",
        "action": "CREATE",
        "assignGroup": "TCIS-APP-SUPPORT",
        "component": "tcis",
        "description": "Test incident creation",
        "entered": "", "logicalName": "tcis",
        "pageGroups": "['TEST_TCIS:Oncall Schedule']",
        "priority": "",
        "racfId": "",
        "sendPage": "",
        "sysProdName": "tcis",
        "transactionId": "",
        "type": "SYSMAN"}

data['pageGroups'] = ast.literal_eval(data['pageGroups'])
data = json.dumps(data)
print(data)

#response = requests.posts(..., json=data, ...)

Output (line breaks added manually):
{"abendCode": "",
 "action": "CREATE",
 "assignGroup": "TCIS-APP-SUPPORT",
 "component": "tcis",
 "description": "Test incident creation",
 "entered": "",
 "logicalName": "tcis",
 "pageGroups": ["TEST_TCIS:Oncall Schedule"],
 "priority": "",
 "racfId": "",
 "sendPage": "",
 "sysProdName": "tcis",
 "transactionId": "",
 "type": "SYSMAN"}


text:
Q: bind manual input value and report deviation into the other input column this question continue my first question about
how to make function which related comboboxes option
first the input constans so i made function like this
$("#pkategori").change(function () {
    var kategori = $("#pkategori").val();
    if (kategori == "TCA"){
        $("#quantity").val("120");
    }
    if (kategori == "BULK PACK"){
        $("#quantity").val("32");
 }
});

completely my code like this
but sometime user manually input on "Nomor Seri Produk".
my problem: how to bind what the user write manually on "Nomor Seri Produk" and show deviance on "Quantity".
for example: user manually write on BULK PACK category 1-20 so on quantity automaticly filled by 20

A: $("#seri").on("keyup", function() {
    var input = $(this).val();
    var matches = input.match(/(\d+)-(\d+)$/);
    if (matches) {
        var deviance = matches[2]-matches[1]+1;
        $("#quantity").val(deviance);
    }
});

FIDDLE


text:
Q: Is there any Python async library available for Google Cloud Bigtable? I am using Google Cloud Bigtable and looks like Google officially doesn't support async way of inserting data into Bigtable.
somethings like await client.mutate([data])

A: There is a similar request from January 2018 (See this GitHub issue).
For some context, this feature is generally used for higher throughput in batch jobs, and some "fire-and-forget" cases.  Integration with Apache Beam would benefit from this feature.
Unfortunately, this type of implementation is tricky, and other issues had to be dealt with first.  The Cloud Bigtable Python client recently achieved Beta status, which means that the team can start working on more complex functionality like async writes.
I would suggest either commenting on the original this GitHub issue if your use case is similar, or creating a new feature request that better matches with your use case.


text:
Q: PJSip : Making a call / Missing headers? I have implemented the PJSIP framework in to my Android app using the sample app PJSUA which works via telnet.
How do I now generate, access header files/ functions to make call etc.  Do I have to modify the SWIG script to generate more files.
I only get the following so far

*

*Pjsua.java

*pjsuaAppCallBack.java

*PjsuaJNI.java

Looking at iOS code and CSIPSimple, there seems to be a lot more header files
Update
I looked at this post, it seems I may need to use jni?? and run the direct commands, any advice would be great
Using pjsip with android
"Hello, in fact you don't need to implement the whole thing and SWIG makes your life more complicated when you need some callback from native. Take a look on how jni works try to call a native function from java using the tutorial and start implementing a simple app in native code like this one but with jni functions pjsip.org/pjsip/docs/html/… which helps you understand how to use it. Warning: the debug environment is a mess to set up, watch out the makefiles for jni and sometimes eclipse might be your ennemy. Have fun"

A: For anyone interested in this, basically at the moment they (PJSIP) are still working on a nice Android implementation.  I contacted support and they helped me through making all the header files etc.
I recommend contacting them for anyone looking in to PJSIP


text:
Q: How to add pop-up window/modal to dynamically created tables HTML

Javascript

The above code creates tables dynamically and displays data from my JSON file. I want to make this tables as buttons and add pop up windows to these tables, such that when a table is clicked a pop-up appears and each pop up should have different data. Any solution to this would be helpful. Thanks in advance.

A: The main trick is going to be binding your click handler to the document:
$(document).on("click", ".buttonInTd", function() {
    /* give your buttons the 'buttonInTd' class and add your onclick code here */
});

Doing this will allow you to dynamically create a table and still capture its events.
To handle modals and popups I would recommend just grabbing one of the multitude of plugins available for that. I really like featherlight

A: HTML:


text:
Q: motionBegan:withEvent: not called in AppDelegate in iOS 10 I used to detect a shake motion from the AppDelegate by simply implementing this method:
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    NSLog(@"shake shake shake");
}

which works fine in iOS 8 and 9. However it doesn't work in iOS 10 anymore.
I also tried adding
- (BOOL)canBecomeFirstResponder {
        return YES;
}

but that didn't help. This works fine in the UIViewControllers though. Did something change in iOS 10, or is it just a bug?

A: I had the same issue as you. Instead of implementing it on AppDelegate, I now use UIWindow, which works for me in iOS 8-10. Perhaps this is do-able for you as well?
extension UIWindow {

    override open var canBecomeFirstResponder: Bool {
        return true
    }

    override open func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
        if motion == .motionShake {
            //logic here
        }
    }
}

If you want to do it even cleaner, you might be able to set a specialized version of the UIWindow on the application.

A: I had a similar issue and I tried @jayjunck's answer but Xcode thrown Method does not override any method from its superclass. I fixed it by replacing public with open to access and override motionBegan function
In Swift 3,

*

*An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.

*A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.
enter code here
extension UIWindow {
override open func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
        super.motionBegan(motion, with: event)

        guard motion == UIEventSubtype.motionShake else {
            return
        }

        // Shake is detected
    }
}

Swift 5
extension UIWindow {
        open override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
            super.motionBegan(motion, with: event)

            guard motion == UIEvent.EventSubtype.motionShake else {
                return
            }

            // Shake is detected
        }
}

A: You should override motionBegan method in (all) View Controller(s).


text:
Q: How to view chapter wise bookmarks in Okular? Common pdf viewers like Document Viewer and Adobe Reader in Windows provide bookmarks for every chapter like so :

Is there anyway to get the same feature in Okular?

A: You're looking for the "Contents" tab on the left.

A: you can set a "special note" with a distinguishing icon marking the position of every bookmark. That way, you can have multiple bookmarks in a page and be able to remove any bookmark just removing the note.


text:
Q: How can I launch an application at startup just in a determined session?
Possible Duplicate:
How To Make Program Autostart only In GNOME

I set up my Gnome session to use tint2 as a window list panel, but I don't need it when using Xfce, therefore I'd like to have tint2 start only under "Classic Ubuntu" session. Is this possible? Editing the Startup Applications has effect on both sessions. Thanks for your help!

A: Yes , first place anything autostart file in ~/.config/autostart , and for each *.desktop file need only in GNOME , put a line like this into that file:

OnlyShowIn=GNOME;

Which means this application will only start in Gnome session.
If you take a look in /etc/xdg/autostart for specific application , thw following image is pretty clear on the basis of its structure:


text:
Q: What are the number of Hausdorff topologies on the set $X=\{x_1,x_2,x_3,x_4,x_5\}$? What are the number of Hausdorff topologies on the set $X=\{x_1,x_2,x_3,x_4,x_5\}$?
I had once  computed the the topologies on the set $X=\{x_1,x_2,x_3\}$ which comes out to be $29$.But,that was very tedious job to do.
I also tried computing the number of topoologies on $X=\{x_1,x_2,x_3,x_4,x_5\}$,but this seems to be more painstaking job even from before.
Now,restricting  condition of Hausdorffness on counting boggled my mind even more. I've tried a lot but every time I failed miserably.
Please suggest any elegant way so that I can classify which of the topology is Hausdorff.
Thank you

A: A finite set $X$ with a $T_1$ topology is discrete: if all $\{x\}$ are closed, all subsets of $X$ (which are finite too) are closed too (finite unions of closed sets are closed) and so all subsets are open (every complement is also closed).
There is only one discrete topology on $X$, namely $\mathscr{P}(X)$. No need for counting arguments: Hausdorff implies $T_1$, of course.

A: If any topology on $X$ is to be Hausdorff, for any two points $x_i \neq x_j$ there needs to be two disjoint sets, one containing $x_i$ and another containing $x_j$.
Since this has to be true for all pairs of points, each set of the form $\{x_i\}$ must be open, so by the axioms defining a topology, the power set on $X$ (the discrete topology) is the only Hausdorff topology on $X$.


text:
Q: Grails - Spring Security - authentication error I have a strange problem with an authentication of users in Grails using Spring Security plugin:

*

*When the user logs into his account, he sees credentials of completely different user (I print out the credentials)

*Sometimes the credentials switch to other user when user is already correctly authenticated.

This problem does occur neither on my development machine nor on a test serwer.
The evironment where problem is present:

*

*Students in a school are testing the system on school's computers

*Each student registers as a new user

*School's computers has some security restrictions (that I don't know)

*All computers has one IP assigned (I don't know how internal network is configured yet)

Firstly, I thought it had something to do with cookie storage (j_session_id), but students could log in to Facebook or Gmail, etc. without any unexpected account switches.
It looks as if all cookies on all computers are being overriden when new user logs in - this was my guess but I can't confirm that all consequent users have the same - last logged user's credentials.
Sadly, I can't debug it at school's place, because it's far away.
How can I find out what is going on?
What might be the possible cause of the problem?
Why have users often different credentials when they are logging in?


text:
Q: Want to know details and meaning about the trace of SQL Server I referred to this article: sp_trace_setevent (Transact-SQL).
And trace my SQL Server on production machine for months.
EventId of most of the traces were: 10,12,14,17
The MSDN says:

*

*10 RPC:Completed

*12 SQL:BatchCompleted

*14 Audit Login

*17 ExistingConnection

Please tell me what do they mean in the performance perspective. Which ones should I keep an eye on and examine in detail. Or am I missing something. Thanks!

A: You appear to have setup a trace with no understanding of why you've done so. There is little point in running a trace for 10 minutes, let alone months, without a reason.

Scenarios for using SQL Server Profiler
The first step in using SQL Server Profiler is to identify your
  reasons for monitoring an instance of SQL Server.

The most common scenarios (taken from the above link) which may be relevant to you are:

*

*Find the worst-performing queries.

*Monitor stored procedure performance.

A trace that captures RPC:Completed and SQL:BatchCompleted events (Stored Procedure and TSQL classes) with Duration, Reads and CPU data columns will provide you with a diagnostic log of how your queries are performing. You can import this trace file to a table and run queries against it to identify the slowest, highest IO or highest CPU consumers for example.
If you have direct access to the server and want to analyse performance, I'm inclined to suggest that you ignore profiler traces and start with the SQL 2005 Performance Dashboard Reports. When you've grasped the basic concepts of Troubleshooting Performance Problems, invest some time understanding Dynamic Management Views (DMVs) and how they can help with performance analysis.

A: The link you provided has very explicit descriptions, if you are trying to optimize some code in your database you probably need to look for some SQL:BatchStarting/SQL:BatchCompleted that is taking too long, and see if there is any way to optimize it
Note: i'm new here


text:
Q: Upload GeoJSON to GeoServer using CURL I tried to upload a zipped shapefile to GeoServer using CURL.
curl -v -u username:password -XPUT -H "Content-type: application/zip" --data-binary @D:\curl\bin\roads.zip https://DOMAIN/geoserver/rest/workspaces/geonode/datastores/my_geonode_data/file.shp

This above command works fine.
But I can't seem to upload a GeoJSON file to GeoServer.
 curl -v -u username:password -XPUT -H "Content-type: application/json" --data-binary @D:\curl\bin\countries.geojson https://DOMAIN/geoserver/rest/workspaces/geonode/datastores/my_geonode_data/featuretypes

I am attaching the error in geoserver.log. But the GeoJSON is not uploaded. I can't see it in the uploaded layers. Am I correct in the CURL command? Is the endpoint (URL address) okay?

A: By default GeoServer doesn't support GeoJSON as a storage format because it is a text format with no indexing.
It would be possible for an expert to add the GeoTools gt-geojsondatastore module to GeoServer to add this support but it would be very unwise for a production service as that jar is currently unsupported and it would be very slow.
You should convert your data to a better format such as a PostGIS data base or GeoPackage and upload that instead.


text:
Q: Sequlize generate a table with a foreign key while explicitly requested not to I have the following association in PersonEntity:

    @HasMany(() => SocialPostEntity, {
        foreignKey: 'parentId',
        foreignKeyConstraint: false,
    })
    posts?: SocialPostEntity[];

On the other hand the related column on SocialPostEntity:
    @Column(DataType.INTEGER)
    parentId: number;

The generated create table script has created the parentId column with a foreign key to PersonEntity. event though I have explicitly mentioned foreignKeyConstraint: false
Im not intended to use synchronize: true in production but I'm afraid that it means that my mapping is not accurate.
Bottom line I want parentId to be a simple integer, that's it.
Thanks


text:
Q: How to generate location independent code using GNU ARM toolchain? I am using ARM ELF toolchain for my project. I am working on a bootloader which needs to be location independent as it will relocate it self from flash to ram upon reset. I have tried hard to figure out how to compile location independent code using GNU ARM toolchain but can not seem to make it work.
I have tried using -fpic and -fpie options for the compiler and -pie for linker but when I use these options the compiler complains that no section is defined for either .got or .plt sections. I am not sure where these sections should go i.e in BSS or TEXT. After googling about this, I think I should only use -fpie but I am not sure.
Can someone with experience with this please help me. I am using GNU ARM 4.1.1

A: you can generate Position Independent Code [PIC] by supplying -mapcs-reentrant option to arm-linux-gnueabi-gcc and -Wa,-K option to fellow assembler.
like:
arm-linux-gnueabi-gcc <other option> -mapcs-reentrant -Wa, -K <other option> files..


text:
Q: Random Box Generator I'm trying to generate 100 random coloured boxes within the div with the existing by clicking generate button that has top and left position 0-400. Also if I hover over any coloured box it disappears until the last that will give me an alert last box with last box left.
I managed to create a box that generates different colours but im not sure how to generate a 100 let alone hover over and delete the boxes when it is, how would one go about doing that?
My HTML:
<!doctype html>

  <title> Generator </title>
  <meta charset="utf-8">

<button id="myButton"
onclick="createBoxes()"> Generate More
</button>

My JS
window.onload = function()
{
  createBoxes();
}
function createBoxes()
{
  var colors = ["red", "green", "blue", "purple", "yellow"];

  var newP = document.createElement("p");
  var top = 10 + "px";
  var left = 10 + "px";
  newP.style.top  = top;
  newP.style.left  = left;
  newP.style.backgroundColor = colors[ Math.floor( Math.random() *5 )];

  $("container").appendChild(newP);
}
window.onload = function() {
  createBoxes();

}

A: Let's get this done step by step.
While creating box element, you should not use p tag, div is the best choice here.
I have implemented as far as I understood from your question.
Let me know in the comments if I missed something.
I added comments in the code, check if you get it.

window.onload = function() {
  createBoxes();
}

function createBoxes() {
  var left = 0;
  var top = 0;
  var colors = ["red", "green", "blue", "purple", "yellow"];
  // create a for loop and run 99 times;
  for (var i = 1; i < 100; i++) {
    var newDiv = document.createElement("div");
    newDiv.classList.add('box')
    newDiv.style.backgroundColor = colors[Math.floor(Math.random() * 5)];
    newDiv.style.top = top + 'px';
    newDiv.style.left = left + 'px';
    // now add the event on this one;
    newDiv.addEventListener('mouseover', removeBoxes);
    $("#container").append(newDiv);
    left += 70; // increase left 70px each time in the loop
    if (i % 5 == 0) { // if the we have 5 boxes in one row, reset left to 0px and increase top property by 70px to get another row;
      left = 0;
      top += 70;
    }
  }
}

// function to remove the boxes on hover;
function removeBoxes() {
  $(this).remove();
}

// add the mouseover event listener;
$('div.box').on('mouseover', removeBoxes);
#container {
  min-height: 200px;
}

div.box {
  width: 70px;
  height: 70px;
  background-color: rgb(100, 100, 255);
  border: solid 2px black;
  display: inline-block;
  position: absolute;
  box-sizing: border-box;
}

#myButton {
  position: absolute;
  right: 0;
  top: 0;
}

<button id="myButton" onclick="createBoxes()"> Generate 99 More
    </button>


text:
Q: error: expected identifier before '(' token On the if statements, it keeps on giving me the error:

expected identifier before '(' token

I was banking on this to work.
void setup()
{
  Serial.begin(9600);
  Serial.println("We will be calculating whether or not ");
  Serial.println("you are underweight, normal, overweight, or obese. ");
}

void loop()
{
  float weight;
  float height;
  float BMI = (703 * weight) / (height * height);

  Serial.println("Please input your weight (pounds)");
  while (Serial.available() <= 0);
  weight = Serial.parseInt();
  Serial.println("Please input your height (inches)");
  while (Serial.available() <= 0);
  height = Serial.parseInt();

  if ( BMI < 18.5 )
  {
    Serial.println("Your body mass index is:");
    Serial.println(BMI);
    Serial.println("please wait while I calculate your weight status");
    Serial.println("...");
    delay(500);
    Serial.println("You are underweight, please go eat.");
  }
  if ( BMI >= 18.5 ) && (BMI <= 24.9)
  {
    Serial.println("Your body mass index is:");
    Serial.println(BMI);
    Serial.println("please wait while I calculate your weight status");
    Serial.println("...");
    delay(500);
    Serial.println("Congratulations! You are a normal");
    Serial.println("... kind of.");
  }
  if (BMI >= 25.0) && (BMI <= 29.9)
  {
    Serial.println("Your body mass index is:");
    Serial.println(BMI);
    Serial.println("please wait while I calculate your weight status");
    Serial.println("...");
    delay(500);
    Serial.println("You are Overweight");
    Serial.println("I suggest a jog");
  }
  if ( BMI >= 30.0)
  {
    Serial.println("Your body mass index is:");
    Serial.println(BMI);
    Serial.println("please wait while I calculate your weight status");
    Serial.println("...");
    delay(500);
    Serial.println("You are OBESE.");
    Serial.println("You have no hope.);
   }
}

A: That should be easy fixing.
Your Problem should be easily fixed, if you change these lines:
if ( BMI >= 18.5 ) && (BMI <= 24.9)

to the correct form is
if (( BMI >= 18.5 ) && (BMI <= 24.9))

your if statement should just have one pair of () around its conditions :)


text:
Q: Using react-router's history, is there a way to go back to a specific previously rendered page without using push() or replace()? To start, I'm using react-router's history prop.
So let's say I have 4 pages desiredPage, initialPage, addPage, and verifyPage. Every page has a back button.
I'm currently on initialPage, but the last item in my history is desiredPage.
I click the add button on initialPage, and it calls an action that basically performs ownProps.history.push(addPageRoute).
Now, I'm on the addPage. I click the verify button, and it calls an action that basically performs ownProps.history.push(verifyPageRoute).
Finally, I'm on the verifyPage. I click the done button, and it calls an action that basically performs ownProps.history.push(initialPageRoute).
I'm back to initialPage. Is it possible for me to use history to go back to desiredPage without pushing the page's route to history?
My hope is to basically pop history objects off of the stack so that when I click the back button on initialPage, history thinks that the previous page is desiredPage, because verifyPage and addPage no longer exist on the history stack.

A: You can go back n entries with history.go(n).


text:
Q: JMeter "Parameters" variable not convertable to Integer I can't get my ${invoiceTotalCsv} parameter to respond to math equations. I am taking it from from a CSV file in which it is a number, usually with a decimal place.
The below code works, but if ${invoiceTotalCsv} = 10, then the log writes 101, not 11. This leads me to believe the variable is passed as a string. BUT, I've tried Parameters.toInteger() which throws a NumberFormatException.
No other clues are given by JMeter.

A: You need to convert String to number/int, in groovy script:
 def total = Parameters as double

A: You can use JSR223 Sampler element and then convert your Jmeter variable in int, float or double as required.
For better understanding see this page


text:
Q: android home up icon is showing instead of action bar drawer toggle menu icon In my android app, I have navigation drawer and action bar drawer toggle icon with ic_menu icon which was working fine. Yesterday I added new dependency in my gradle file
compile 'com.android.support:design:22.2.0'
after added this, in main activity instead of ic_menu icon home up icon is appearing. If I click that it is working like drawer toggle. The only issue is icon.
Please help me to solve this issue.
find the below code which I used to initialize action bar drawer toggle
    actionBarDrawerToggle = new ActionBarDrawerToggle(this, navDrawerLayout, R.drawable.ic_menu_white_24dp, R.string.drawer_open, R.string.drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }

    };
    navDrawerLayout.setDrawerListener(actionBarDrawerToggle);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Thanks,
Sundar


text:
Q: Select the same file on Vuetify component v-file-input I am building a web app using nuxt, vuetify 2.x, and typescript.
I want to upload file using v-file-input but have some issue upon selecting the same file.
For example, when I select some file and then close the dialog without saving it,
I cannot select the same file(i.e.@change is not firing)
what I have tried:
<v-file-input
  accept="image/png, image/jpeg"
  ref="imageUploader"
  @click="resetImageUploader"
  placeholder="upload image"
  prepend-icon="mdi-camera"
  @change="changeImage"
></v-file-input>

script:
 methods: {
    resetForm() {
      (this.$refs.form as HTMLFormElement).reset();
    },
    resetImageUploader() {
      (this.$refs.imageUploader as any).reset();
    },
}

(resetForm() is called when dialog is closed)
I've tried resetting imageuploader when the input form is clicked, but it did not work.
I've tried (this.$refs.imageUploader as any).value = '' instead of reset() but it did not work.
Btw, When I select the file, clear icon appears like this

If I clear the form by clicking this icon, I can select the same file..
Does anyone have idea how I can solve this issue?

A: try to do like below to reset
<v-file-input
  accept="image/png, image/jpeg"
  ref="imageUploader"
  :value="internalVal"
  @click="resetImageUploader"
  placeholder="upload image"
  prepend-icon="mdi-camera"
  @change="changeImage"
></v-file-input>

script:
methods: {
    resetImageUploader() {
      this.internalVal = []
    },
}


text:
Q: Displaying very large images on the iPad I need to display some very large images on the iPad. The files are jpgs and are about 6700x2700 (maps). Is there any way around loading the entire image into memory?
Currently I load it int a scroll view for zooming/panning.
The images are stored locally on the device.

A: You need to use CATiledLayer to display images of that size. Refer to the CATiledLayer class reference and Core Animation programming guide.

A: Like they said, all you need is something like
+(Class)layerClass
{
    return [CATiledLayer class];
}

in your view.


text:
Q: Passing a struct pointer containing NULL all of a sudden contains a struct instead of NULL OKay I have recreated a smaller example and the problem persists...
Comments indicate whats going on. Expecting the pointer to be NULL but IM getting a struct with NULL values after passing it to another function a second time.
header.h
typedef struct node {
int data;
struct node *next;
} *List;

source.c
#include "Header.h"
#include <stdio.h>
#include <stdlib.h>

void two(List *self)
{
    //*self does not = NULL now
    //*self = a struct with null data and next values
}

void one(List *self)
{
    two(&self);
    // *self = 0x0000... NULL
}

int main()
{
    List test = NULL;
    one(&test);
}

A: Your one() function should be:
void one(List *self)
{
    two(self);
}

Please compile with arguments -Wall. Also, it is recommended to use -Wextra and -Werror.

A: List test = NULL;
one(&test);

test is a pointer to struct node. We pass the address of that
pointer to one, allowing one to change test (letting it return a
new pointer is a cleaner way to do this).
one then executes this:
two(&self);

two is now being passed the address of the address of test. This is
probably not what you intended. Passing the address of test still lets
you change test if that's what you want to do:
two(self);


text:
Q: How to postpone calculations in Tableau? In Tableau dashboard it is possible to create a number of elements (like sliders) which can be used by user to set values of some parameters. Further these parameters are used in combination with data as input for some calculations. The results of the calculations are displayed back to the user.
The default behavior of Tableau is that the calculations are triggered each time as soon as one of the parameters is changed by a user. It might be not optimal if there are many parameters and each recalculation takes several seconds. A user might want first to set the values of all parameters and only then trigger the calculations.
How can one get this behavior?
ADDED
I found out that I can choose "pause auto updates" (here). In this way a change in one of the parameters does not trigger the calculations (as I want). Then I can trigger the calculations (after all parameters are changed) by pressing "Refresh" button. The problem with this solution is that I, as a dashboard developer, have this button but the user will not have it. I guess the user can also update the dashboard by pressing F9 button on the keyboard, but it might be not user friendly. I would prefer to put a "Refresh" button into the UI (into dashboard directly). Is it possible?
ADDED 2
Here I see a question that is identical to mine. The proposed solution is to use "Pause" and "Run" buttons. However, as I have already mentioned, it does not seems to be a "full solution" since it works only for the developers of dashboard and not the final users (since they do not have access to these buttons). So, my question remains: How can I add the "Pause" and "Run" buttons to the dashboard?

A: You can factor out portions of your dashboard, such as user input, into HTML inputs and then use the Tableau JavaScript API to control aspects of Tableau's behavior, such as when it refreshes. You can then style your controls with CSS etc. At the cost of maintaining a bit of HTML and JavaScript.
It may not be worth the hassle compared to just putting a note on the dashboard to say, "use pause and resume when ..." but it does give you more control over look, feel, behavior and integration with other apps


text:
Q: Python make list of items according to a dictionary of key value pairs, but values have to be regex patterns I am trying to make a wrapper function for the existing itertags one here: https://github.com/streamlink/streamlink/blob/master/src/streamlink/plugin/api/utils.py#L16
Currently i have this:
def itertags_wrapper(html, tag, attrs=None, ret=False):

    try:

        result = list(itertags(html, tag))

        if isinstance(attrs, dict):

            attrs = list(iteritems(attrs))

            result = [i for i in result if any([a for a in attrs if a in list(iteritems(i.attributes))])]

        if ret:

            # noinspection PyTypeChecker
            result = [i.attributes[ret] for i in result if ret in i.attributes]

    except Exception:

        result = []

    return result

Now it returns the tags containing the exact same key-value pair as in attrs, but HOW do I have the value of the pair in a regex pattern and broaden possible results?
P.S. iteritems is passed through a "compat" module first to work on both python 2 & 3.

A: After lots of tests I came up with this solution:
def itertags_wrapper(html, tag, attrs=None, ret=False):

    try:

        result = list(itertags(html, tag))

        if isinstance(attrs, dict):

            attrs = list(iteritems(attrs))

            result = [
                i for i in result if any(
                    [a for a in attrs if any([a[0] == k and re.match(a[1], v) for k, v in iteritems(i.attributes)])]
                )
            ]

        if ret:

            # noinspection PyTypeChecker
            result = [i.attributes[ret] for i in result if ret in i.attributes]

    except Exception:

        result = []

    return result

All I did is add a second iteration of the attrs key value pairs.


text:
Q: validate numeric with 1 special character i want to validate numeric and allows the + (plus sign), but its not working
what i want
+63443 -> OK
8452 -> OK
s55sd -> Not OK

here's my code
var Nom = $("#addKonId1").val().split(" ").join("").replace(/^\s\s*/, '').replace(/\s\s*$/, '');

var intRegex = /^\d+$/;
if (!intRegex.test(Nom)) {
    alert("wrong Number");

} else {
    alert(Nom);
}

A: Try This
var Nom = $("#addKonId1").val().trim(" ");
var intRegex = /^\+?\d+$/;
            if(!intRegex.test(Nom)) {
                alert("wrong Number");

            }
            else{
                alert(Nom);
            }

DEMO HERE

A: The regular expression for what you're looking for is:
^\+?\d+$

Which means "a string beginning with optionally one plus sign followed by one or more digits".
Your regex right now only tests for a string beginning with one or more digit characters. Alter intRegex like so:
var intRegex = /^\+?\d+$/;

On a side note, what you're doing in your first line with the replacing can simply be done with trim():
var Nom = $("#addKonId1").val().split(" ").join("").trim();


text:
Q: SQL to Search for a particular VALUE in all COLUMNS of all TABLES in an entire SCHEMA in Oracle DB Is there SQL to Search for a particular VALUE in all COLUMNS of all TABLES in an entire SCHEMA in Oracle DB. Please explain.

A: You'll need dynamic SQL, as you have to compose select statement.
Here's an example; adjust it according to your needs because datatypes matter (e.g. you can't compare numbers to dates and such; I'm handling it simply by skipping over errors):
SQL> declare
  2    l_search_value varchar2(20) := '10';
  3    l_str varchar2(500);
  4    l_cnt number;
  5  begin
  6    for cur_r in (select table_name, column_name, data_type
  7                  from user_tab_columns
  8                 )
  9    loop
 10      begin
 11        l_str := 'select count(*) from ' || cur_r.table_name ||
 12                 '  where ' || cur_r.column_name || ' = ' || l_search_value;
 13        execute immediate l_str into l_cnt;
 14
 15        if l_cnt > 0 then
 16           dbms_output.put_line(rpad(cur_r.table_name ||'.'||cur_r.column_name, 30, ' ') ||
 17                                  ' found ' || l_cnt || ' time(s)');
 18        end if;
 19
 20      exception
 21        when others then
 22          --dbms_output.put_line(rpad(cur_r.table_name ||'.'||cur_r.column_name, 30, ' ')
 23          --                       ||' - ' || cur_r.data_type ||'; '|| sqlerrm);
 24          null;
 25      end;
 26    end loop;
 27  end;
 28  /
DEPARTMENTS.DEPARTMENT_ID      found 1 time(s)
DEPT.DEPTNO                    found 1 time(s)
EMP.DEPTNO                     found 3 time(s)
EMPLOYEES.DEPARTMENT_ID        found 3 time(s)

PL/SQL procedure successfully completed.

SQL>


text:
Q: How to make jquery use a named function I have been trying to do this for hours, and it's persisted in not working. I can't find why.
My HTML:

Description

(0 Chars. ±1):

<textarea name='dataDescr' id='metaDescr'>Some Text Here.</textarea>

What I have that Does not work . It does not give me any response, no console errors in firebug or any sort of feedback :
JQuery:

counterChecker = function() {
    var max = 800;
    var lengthVal = $('#metaDescr').val().length;
    var fl = $('#fieldLength');
    if (lengthVal >= max) {
        var char = lengthVal - max;
        fl.text('Over by ' + char);
    }
    else {
        fl.text(lengthVal);
    }
}

$(document).ready(function() {
    $('#metaDescr').on("change", counterChecker() );
 });

Edit: This also does not work if the function is set out within the
  document ready brackets.

But what DOES work is the same code directly inserted into the on change function as an anonymous function:
 $(document).ready(function() {

    $('#metaDescr').on("change", function() {
        var max = 800;
        var lengthTwo = $(this).val().length;
        var lf = $('#fieldLength');
        if (lengthTwo >= max) {
            var char = lengthTwo - max;
            lf.text('Over by ' + char);
        }
        else {
            lf.text(lengthTwo);
        }
    });
});

Can someone help me understand why this difference?
Why doesn't it work as a separate called function and yet does not give any errors to my firebug, yet it can work as directly referenced (anonymous?) function . How can I make it behave as intended but keeping the code in a separate self contained functional unit.
I'm using JQuery 1.11.3 and viewing many stackoverflow posts over the last few hours hasn't shown the light :-/

A: $('#metaDescr').on("change", counterChecker() );calls the counterChecker function and assigns the returned value to the onchange handler. In this case it returns undefined and uses that as the change listener. What you want is $('#metaDescr').on("change", counterChecker); which passes a refrence to the counterChecker function that will be called when the change event fires.


text:
Q: Using ISpecification in core layer violating OOP Using ISpecification (from the Ardalis.Specification package) in the Core layer, doesn't cause the tight coupling to a library? I think it's adding tight coupling to a specific library, and it violates OOP principles and impacts future development on it.

A: When following SOLID principles and specifically the Dependency Inversion Principle along with Clean Architecture (aka Onion, Hexagonal, Ports and Adapters, etc.), it's best not to have dependencies flowing from your high level business logic (domain layer) classes and types to your low level implementation details. I think this is what you're concerned about.
However, it can be useful to leverage libraries that only contain in-memory functionality and do not add any coupling to infrastructure concerns. For instance, it's not unusual in my projects to have dependencies from my Core domain project to packages like these:

*

*FluentAssertions

*Ardalis.GuardClauses

*Ardalis.Result

*Ardalis.SmartEnum

*Ardalis.Specification
None of these have dependencies on specific implementation details.
That said, I would not add a reference to or depend on implementation specific packages like:

*

*Ardalis.Specification.EntityFramework

*Ardalis.Result.AspNetCore
Part of the reason why these are separate packages is so that you can leverage the in-memory functionality of these packages while keeping the infrastructure-specific implementations separate (and only referencing these as and when appropriate).


text:
Q: Solr: How to partial update solr documents using regular expression Currently i am using this command:
curl 'localhost:8983/solr/update?commit=true' -H 'Content-type:application/json' -d '[{"id":"rekhta.org/ghazals/Alama_3.8","pr":{"set":100}}]'

But this update happens only on the document whose id is "rekhta.org/ghazals/Alama_3.8"
How can i update documents whose id contain "ghazals"
(e.g rekhta.org/ghazals/Alama_3.8).
I am getting documents using regular expression q=id:*ghazal* but couldn't update documents using curl with regular expression
curl 'localhost:8983/solr/update?commit=true' -H 'Content-type:application/json' -d '[{"id":"*ghazals*","pr":{"set":55}}]

Solr version: 4.10.3

A: You'll have to retrieve all the documents and perform the update yourself. There is no way currently in Solr to perform a single update against multiple documents (aka "Update by query").
The proper way to do this would be to perform a query (using a wildcard or a regular expression match), loop through the documents and then submit an update message (either as a bulk message or single requests, depending on how many updates you're performing) that changes the content of those documents you've retrieved.


text:
Q: swipe to delete when already in edit mode I have an iphone app using a uitableview where I'd like the "reorder" controls to always be displayed, and have the user swipe to delete rows.
The approach I'm currently taking is to put the tableview in edit mode and allow selection in edit mode
self.tableView.editing = YES;
self.tableView.allowsSelectionDuringEditing = YES;

I then hide the red delete circles using
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

I cant figure out how to get the swipe gesture to bring up the "delete" on the right side when the tableview is already in edit mode, can somebody point me in the right direction?
alternatively, if someone knows how to get the cell reordering controls to show when NOT in edit mode, that would also be a workable solution
cheers

A: When the user swipes on a given row, you need to store a reference somewhere so that you can change the value returned by editingStyleForRowAtIndexPath and shouldIndentWhileEditingRowAtIndexPath.  Your best bet is likely to use indexPathForCell on the cell that is swiped and store that.  Then in the two display methods above you need to check if the NSIndexPath is the same or not (I'm not sure if they will be the same pointer or if you'll need to compare the section/row values - testing required).  If they match, display the delete button.
Note that you may need to call reloadData on your tableView to have the effect appear without scrolling away and back again.

A: I'm wondering if the way you're headed now would break the Human Interface guidelines, which would result in the app not getting approved.
I can't see why you can't capture the swipe gesture and then use that to 'unhide' the red delete (stop sign) icons for the delete confirmation?


text:
Q: Given finite $G\subset O(n)$, is there a "standard" cell structure on $S^{n-1}$ with $G$ acting cellularly? Let $G\subset O(n)$ be a finite orthogonal group.

Is there a regular CW-complex structure on $S^{n-1}$ on which $G$ acts cellularly which is in any sense "natural"?

What I'm looking for is inspired by the following examples and ideally would generalize them:
(a) If $G$ is a reflection group, then the Coxeter complex, i.e. the regular CW structure given to $S^{n-1}$ by intersecting with all the reflecting hyperplanes.
(b) If $G$ is $\{\pm I\}$, then the standard cell-complex structure on $S^{n-1}$ with $2$ cells in each dimension from zero up.
(This question is a little soft because I'm not sure how much "naturality" it would be fair to ask for. Candidates include: (1) such that the action on top-dimensional cells is free and transitive [but this seems like it would be too much to hope for]; (2) such that the construction is functorial from the category of subgroups of $O(n)$ with inclusions as morphisms to the category of regular CW-complexes with cellular embeddings refinements as morphisms [again, maybe too much to hope for]; (3) a uniform general construction that specializes to both the special cases above. And I'm open to other ideas...)

A: For a first pass at an answer:
Fix a point of the sphere with trivial stabilizer in $G$ and take the Voronoi diagram of its orbit under $G$. The top-dimensional cells are the Voronoi cells, which are polyhedra, and the $d$-dimensional cells are the $d$-faces of these polyhedra.
This construction has property (1) - the action is free and transitive on top-dimensional cells. It does not have property (2). I believe it does have part of property (3) - generalizing the Coxeter complex - since reflecting hyperplanes should be the boundaries of Voronoi cells since the images of the point on either side of a given reflecting hyperplane are equidistant. However, it's unsatisfactory re: the other part of property (3), since I don't see how it constructs lower-dimensional cells (below $n-2$) for the example of $G=\mathbb{Z}/2$ acting by the antipodal map.
So, this is an imperfect but passable solution. (Tom Goodwillie shows in a comment that (1) and (2) are not simultaneously possible. More generally, (2) seems kind of ridiculous given how any reasonable cell decomposition for the antipodal map should depend on some arbitrary choice, since this map is central in $O(n)$ so cannot distinguish any points of the sphere. How could such a choice then be made functorial?) But I would be interested in others, so I'll leave the question open for a while.


text:
Q: Can I use group by in a subquery? I want to do the following:
select count(t) from Ticket t where t.id in (select st.id from Ticket st group by st.owner)

Unfortunately, I get a SQLGrammarException when doing this.
Any ideas?

A: If I follow what you're trying to do, try changing the query to this:
select count(t) from Ticket t where t.id in (select st.id from Ticket st group by st.owner, st.id)
What database are you querying? My familiarity is with SQL Server and in that case, yes, the group by in above subquery should work.

A: select st.id from Ticket st group by st.owner isn't a valid query, so it's not going to be a valid subquery.


text:
Q: Chromecast listener is not working when i create seperate class from Controller Created class:
class ChromeCast:NSObject {

    //MARK:Chromecast Vars
    var applicationMetadata: GCKApplicationMetadata?
    var selectedDevice: GCKDevice?
    var deviceManager: GCKDeviceManager?
    var mediaInformation: GCKMediaInformation?
    var mediaControlChannel: GCKMediaControlChannel?
    var deviceScanner: GCKDeviceScanner

    lazy var kReceiverAppID:String = {
        // You can add your own app id here that you get by registering with the
        // Google Cast SDK Developer Console https://cast.google.com/publish
        return kGCKMediaDefaultReceiverApplicationID
    }()

    override init() {

        let filterCriteria = GCKFilterCriteria(forAvailableApplicationWithID:
            kGCKMediaDefaultReceiverApplicationID)
        deviceScanner = GCKDeviceScanner(filterCriteria:filterCriteria)

    }

    func startChromeCastScanning() {
        // Initialize device scanner
        deviceScanner.addListener(self)
        deviceScanner.startScan()
        deviceScanner.passiveScan = false
        Log.Info("Start Scanning")
    }

}

extension ChromeCast: GCKDeviceScannerListener {

    func deviceDidComeOnline(device: GCKDevice!) {
        Log.Info("Device found: \(device.friendlyName)")

    }

    func deviceDidGoOffline(device: GCKDevice!) {
        Log.Info("Device went away: \(device.friendlyName)")

    }

}

and calling it from my view controller as:
someFunctionInViewController() {

 let chrome = ChromeCast()
 chrome.startChromeCastScanning()
}

Delegate is not getting called back . when device discovered.
But same works when i add all properties and function in view controller it self.
But i want to seperate it from controller. what is the issue?

A: I Figured out the problem
instead of local i declare global property for Chromecast in my controller
 var chrome : ChromeCast?

and then from my function i called it as
func someFunction() {
  chrome = ChromeCast()
  chrome?.startChromeCastScanning()
}


text:
Q: Labels that are parallel with edges of a triangle The following code is compiled to give a right triangle. The labels for the lengths of the legs and hypotenuse are present and "sloped."  I would like them to be outside the triangle.
\documentclass[10pt]{amsart}
\usepackage{tikz}
\usetikzlibrary{calc,angles,positioning,intersections,quotes,decorations.markings}
\usepackage{tkz-euclide}
\usetkzobj{all}

\begin{document}

\begin{tikzpicture}
\path (135:3) coordinate (A) (45:4) coordinate (B) (0:0) coordinate (C);
\draw (A)
-- (B) node [at start, above left]{$A$} node [midway, sloped]{$m + n$}
-- (C) node [at start, above left]{$B$} node [midway, sloped] {$2\sqrt{mn}$}
-- (A) node [at start, below]{$C$} node [midway, sloped]  {$m - n$} -- cycle;
\draw pic[draw, angle radius=7.5mm,"$\theta$",angle eccentricity=1.5] {angle = C--A--B};
\tkzMarkRightAngle(A,C,B);
\end{tikzpicture}

\end{document}

A: Just add above and below as required. See this:

The modified code:
\documentclass[10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc,angles,positioning,intersections,quotes,decorations.markings}
\usepackage{tkz-euclide}
\usetkzobj{all}

\begin{document}

\begin{tikzpicture}
\path (135:3) coordinate (A) (45:4) coordinate (B) (0:0) coordinate (C);
\draw (A)
-- (B) node [at start, left]{$A$} node [midway,above, sloped]{$m+n$}
-- (C) node [at start, right]{$B$} node [midway,below, sloped] {$2\sqrt{m n}$}
-- (A) node [at start, below]{$C$} node [midway, below, sloped] {$m-n$} -- cycle;
\draw pic[draw, angle radius=7.5mm,"$\theta$",angle eccentricity=1.3] {angle = C--A--B};
\tkzMarkRightAngle(A,C,B);
\end{tikzpicture}

\end{document}

A: Just for fun solution with PSTricks.
\documentclass[pstricks,border=12pt,12pt]{standalone}
\usepackage{pst-eucl}
\begin{document}
\begin{pspicture}(10,7)
    \pstGeonode[CurveType=polygon,PosAngle={180,-90,0}](1,4){A}(5,1){C}([offset=-7]{A}C){B}
    \pstRightAngle{A}{C}{B}
    \pstMarkAngle[MarkAngleRadius=1,LabelSep=1.5]{C}{A}{B}{$\theta$}
    \psset{shortput=nab,linestyle=none,nrot=:U}
    \pcline(A)(B)^{$m+n$}
    \pcline(A)(C)_{$m-n$}
    \pcline(C)(B)_{$2\sqrt{mn}$}
\end{pspicture}
\end{document}


text:
Q: How does Python evaluate this expression? How does Python evaluate the following expression? anim1 gets executed after anim2. How does a simple + operator that?
anim1 = Animation(duration=1, center=(100,100) type='delta')
anim2 = Animation(duration=1, rotation=45 type='delta')

anim = anim1 + anim2

A: This will call anim1.__add__(anim2).
In order to understand what is happening under the hood you have to inspect the definition of __add__ method from Animation class.

A: In Python, you can redefine the behavior of the mathematical operators. If I understood your question, Animation probably redefines the "+" operator using the __add__ method.
More info: Official Documentation

A: Check out the dis module. It has a function dis that will take a function/module/class and show you the byte code.


text:
Q: Encrypt (disk level) on Database Server MS SQL 2008 Has anyone tried to encrpyt disk drives for a database server running WANSync?
We used Arcserve WANSync for HA to our DB servers and we are planning to encrypt both the primary and secondary disks using a Bitlocker.
We would like to know the impact when all disks were encrypted on our database servers:
What will be the impact on MS SQL 2008?
When failover happened are there any impact?
Any observations to those who experience encrypting drives on a server running WANSync High Availability?
Thanks a lot!


text:
Q: Subtraction of Random Variables Let $T$(Talent Distribution) and $E$(Environment) be independently and uniformly distributed random variables over the interval [0,1] and [0,$c_1$] respectively. Considering $c_1>1$, I have now found out a distribution for $X_A=T+E$ for which I followed this blog:
$f_{X_A}(x){}={\bf{1}}_{\left\{0\le x \le 1\right\}}\dfrac{z}{c_1} +{\bf{1}}_{\left\{1 < z \le c_1\right\}} {}+{}{\bf{1}}_{\left\{c_1 < z \le c_1+1\right\}}\dfrac{c_1+1-z}{c_1}\,.$
Similarly, if we consider another distribution $X_B=T+E'$ where $E'$ is uniformly distributed between $[0,c_2]$ such that:
$f_{X_B}(x){}={\bf{1}}_{\left\{0\le x \le 1\right\}}\dfrac{z}{c_2} +{\bf{1}}_{\left\{1 < z \le c_2\right\}} {}+{}{\bf{1}}_{\left\{c_2 < z \le c_2+1\right\}}\dfrac{c_2+1-z}{c_2}\,.$
Then I am interested in finding the PDF for $X_A-X_B$.
Being new to probability distributions, I find it hard to compute it easily. Any thoughts appreciated.


text:
Q: Help running docker with GPU on Ubuntu 18.04.4 LTS I'm trying to follow https://www.tensorflow.org/install/gpu#ubuntu_1804_cuda_101 to get docker working with GPU on Ubuntu 18.04.4 LTS.
I'll copy the instructions here for reference:
# Add NVIDIA package repositories
wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-repo-ubuntu1804_10.1.243-1_amd64.deb
sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub
sudo dpkg -i cuda-repo-ubuntu1804_10.1.243-1_amd64.deb
sudo apt-get update
wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb
sudo apt install ./nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb
sudo apt-get update

# Install NVIDIA driver
sudo apt-get install --no-install-recommends nvidia-driver-430
# Reboot. Check that GPUs are visible using the command: nvidia-smi

# Install development and runtime libraries (~4GB)
sudo apt-get install --no-install-recommends \
    cuda-10-1 \
    libcudnn7=7.6.4.38-1+cuda10.1  \
    libcudnn7-dev=7.6.4.38-1+cuda10.1

# Install TensorRT. Requires that libcudnn7 is installed above.
sudo apt-get install -y --no-install-recommends libnvinfer6=6.0.1-1+cuda10.1 \
    libnvinfer-dev=6.0.1-1+cuda10.1 \
    libnvinfer-plugin6=6.0.1-1+cuda10.1

I made it halfway through the steps above and got an error:
$ sudo apt-get install --no-install-recommends nvidia-driver-430
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 nvidia-driver-430 : Depends: libnvidia-gl-430 (= 430.50-0ubuntu0.18.04.2) but it is not going to be installed
                     Depends: nvidia-dkms-430 (= 430.50-0ubuntu0.18.04.2)
                     Depends: nvidia-kernel-source-430 (= 430.50-0ubuntu0.18.04.2) but it is not going to be installed
                     Depends: libnvidia-decode-430 (= 430.50-0ubuntu0.18.04.2) but it is not going to be installed
                     Depends: libnvidia-encode-430 (= 430.50-0ubuntu0.18.04.2) but it is not going to be installed
                     Depends: nvidia-utils-430 (= 430.50-0ubuntu0.18.04.2) but it is not going to be installed
                     Depends: xserver-xorg-video-nvidia-430 (= 430.50-0ubuntu0.18.04.2) but it is not going to be installed
                     Depends: libnvidia-cfg1-430 (= 430.50-0ubuntu0.18.04.2) but it is not going to be installed
                     Depends: libnvidia-ifr1-430 (= 430.50-0ubuntu0.18.04.2) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I noticed that I already have an nvidia driver installed, but it is not version 430:  what I have in my apt list --installed includes:
nvidia-384/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed,upgradable to: 418.87.01-0ubuntu1]
nvidia-384-dev/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed,upgradable to: 418.87.01-0ubuntu1]
nvidia-common/now 1:0.5.3~ppa3 amd64 [installed,local]
nvidia-compute-utils-390/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed]
nvidia-container-toolkit/bionic,now 1.0.5-1 amd64 [installed]
nvidia-dkms-390/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed]
nvidia-driver-390/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed]
nvidia-headless-390/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed]
nvidia-headless-no-dkms-390/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed]
nvidia-kernel-common-390/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed]
nvidia-kernel-source-390/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed]
nvidia-libopencl1-384/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed,upgradable to: 418.87.01-0ubuntu1]
nvidia-machine-learning-repo-ubuntu1804/unknown,now 1.0.0-1 amd64 [installed]
nvidia-opencl-icd-384/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed,upgradable to: 418.87.01-0ubuntu1]
nvidia-prime/now 0.8.9~ppa3 all [installed,local]
nvidia-settings/unknown,now 440.64.00-0ubuntu1 amd64 [installed]
nvidia-utils-390/bionic-updates,now 390.116-0ubuntu0.18.04.3 amd64 [installed]

Here is what does currently work:

*

*I'm able to run nvidia-smi. It says I have Driver Version: 390.116

*I have Docker version 19.03.8, build afacb8b7f0

*My apt list --installed includes nvidia-container-toolkit/bionic,now 1.0.5-1 amd64 [installed], which I installed following some of the instructions at https://github.com/NVIDIA/nvidia-docker

*My apt list --installed includes cuda-repo-ubuntu1804/unknown,now 10.2.89-1 amd64 [installed]
Here is what does not work:
$ sudo docker run --gpus all nvidia/cuda:10.0-base nvidia-smi
docker: Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "process_linux.go:449: container init caused \"process_linux.go:432: running prestart hook 0 caused \\\"error running hook: exit status 1, stdout: , stderr: nvidia-container-cli: requirement error: unsatisfied condition: cuda>=10.0, please update your driver to a newer version, or use an earlier cuda container\\\\n\\\"\"": unknown.
ERRO[0000] error waiting for container: context canceled

The error says I need cuda>=10.0, which is why I was trying to follow https://www.tensorflow.org/install/gpu#ubuntu_1804_cuda_101.
What should I do to get sudo docker run --gpus all nvidia/cuda:10.0-base nvidia-smi working?

Edit: I noticed that https://github.com/NVIDIA/nvidia-docker/wiki/Frequently-Asked-Questions#how-do-i-install-the-nvidia-driver says to install the cuda-drivers package.  I got this error when attempting to install it:
$ sudo apt install cuda-drivers
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 cuda-drivers : Depends: libnvidia-encode-440 (>= 440.64.00) but it is not going to be installed
                Depends: libnvidia-fbc1-440 (>= 440.64.00) but it is not going to be installed
                Depends: libnvidia-ifr1-440 (>= 440.64.00) but it is not going to be installed
                Depends: nvidia-compute-utils-440 (>= 440.64.00) but it is not going to be installed
                Depends: nvidia-dkms-440 (>= 440.64.00)
                Depends: nvidia-driver-440 (>= 440.64.00) but it is not going to be installed
                Depends: xserver-xorg-video-nvidia-440 (>= 440.64.00) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

Are my apt install errors (E: Unable to correct problems, you have held broken packages.) related to the sources I have in my /etc/apt config?
$ rg "cuda" /etc/apt/sources.list.d
/etc/apt/sources.list.d/cuda.list.save
1:deb http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 /

/etc/apt/sources.list.d/cuda.list
1:deb http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 /

$ rg "nvidia" /etc/apt/sources.list.d
/etc/apt/sources.list.d/cuda.list.save
1:deb http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 /

/etc/apt/sources.list.d/nvidia-machine-learning.list
1:deb http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 /

/etc/apt/sources.list.d/cuda.list
1:deb http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 /

/etc/apt/sources.list.d/nvidia-docker.list.save
1:deb https://nvidia.github.io/libnvidia-container/ubuntu18.04/$(ARCH) /
2:deb https://nvidia.github.io/nvidia-container-runtime/ubuntu18.04/$(ARCH) /
3:deb https://nvidia.github.io/nvidia-docker/ubuntu18.04/$(ARCH) /

/etc/apt/sources.list.d/nvidia-docker.list
1:deb https://nvidia.github.io/libnvidia-container/ubuntu18.04/$(ARCH) /
2:deb https://nvidia.github.io/nvidia-container-runtime/ubuntu18.04/$(ARCH) /
3:deb https://nvidia.github.io/nvidia-docker/ubuntu18.04/$(ARCH) /

A: I was able to get sudo docker run --gpus all nvidia/cuda:10.0-base nvidia-smi working.
I had to first run
$ sudo apt-get install libnvidia-compute-430
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
  libnvidia-compute-390 libnvidia-decode-390 libnvidia-encode-390 nvidia-384 nvidia-384-dev nvidia-compute-utils-390 nvidia-driver-390 nvidia-headless-390
  nvidia-headless-no-dkms-390 nvidia-libopencl1-384 nvidia-opencl-icd-384 nvidia-utils-390
The following NEW packages will be installed:
  libnvidia-compute-430
0 upgraded, 1 newly installed, 12 to remove and 15 not upgraded.
Need to get 20.2 MB of archives.
After this operation, 13.0 MB of additional disk space will be used.

After that, I was able to run sudo apt-get install nvidia-driver-430 (the  https://www.tensorflow.org/install/gpu#ubuntu_1804_cuda_101 step on which I was originally blocked).
My nvidia-smi now says NVIDIA-SMI 430.50       Driver Version: 430.50       CUDA Version: 10.1.


text:
Q: Which order of words is more logical in a sentence? We are writing an error message for a user and we have two conflicting opinions at the moment. Since we're not native English speakers/writers we may have some issues with punctuation.
Here are the 2 options:

*

*"To avoid any further issues program will now close!"

*"The program will now close to avoid any further issues!"

Which one of those is grammatically correct? If both are correct which is better style?

A:
1."To avoid any further issues [the] program will now close!"
2."The program will now close to avoid any further issues!"

There is some subjectivity in this but my immediate instinctive reading without analysing the sentences was:
The first sentence implies
(1) that there is/has been an issue
(2) the user is already aware of that
(3) to avoid things going even more wrong the program is closing
The second sentence says
(1) The program is about to close
(2) The reason for closing is so that the program can spend some time avoiding issues (maybe it has family problems and needs time off work?)
(3) You already knew that the program had issues
In terms of grammar, both sentences are correct. Some people use more punctuation than others. I find your existing punctuation acceptable.

A: For clarity's sake, use a comma after issues in the first sentence.
To avoid any further issues, the program will now close.


text:
Q: How to AirPlay or stream video to PlayStation 3 from OS X? I'm hitting brick walls it seems on finding any topics that pertain to streaming video and / or live display to a PlayStation 3.  I am not sure if I'm just missing the correct terminology or if a solution simply doesn't exist.
My primary goal is to be able to stream videos to a PlayStation 3 similar to how Beamer works.  A bonus would be to stream AirPlay. Are there any solutions for such scenarios?

A: Just came looking to see if I could use Airplay, as it would be very convenient to be able to stream from any of my devices.
However, I have been using medialink for years, using my mac mini as a media server.  It had some troubles when it first came out, but in recent years I've found it extremely reliable, quality is excellent for all definitions.

A: Using airplay to stream music to your ps3 is not possible because airplay is a function that is only available on apple devices.
If you want to stream music to your os3, you will need a media server on your mac.
Most of the times I use vuse to stream my media to my ps3/4 or smart tv.