text:
Q: PWA is still using old index.html file in Safari IOS The problem was due to white screen of death after deploying PWA (This is really hard to reproduce but it is an ongoing issue for my clients). It seems to be the problem with cache. It is causing Uncaught SyntaxError: Unexpected token '<'. I know many thread talked about this but it doesn't seem to directly let me tackle and reproduce the issue.
The closest to be able to reproduce is by doing this.

*

*Add PWA to home screen

*Open PWA

*Edit index.html to have .js file pointing to wrong hash in /var/www/my-server

*When I reopen the PWA it is still serving the old index.html file.

*Clearing Safari cache in my iPhone does nothing. PWA still serving old index.html file.

How can I debug what causing the phone to be using the old index.html file even when server already change the index.html file content?

*

*I am using cloudflare

*I am not configuring any Service Worker


text:
Q: Update existing unique keys columns in MYSQL I have a table in that i have unique key .Now because of some reasons i want to update the unique key. AS of now unique key is having 4 columns now i want to add 2 more columns in that
 CREATE TABLE abc (
  id int(10) unsigned NOT NULL AUTO_INCREMENT,
  one varchar(64) NOT NULL,
  search_id varchar(64) NOT NULL,
  session_id varchar(64) NOT NULL,
  pnr varchar(64) NOT NULL,
  origin varchar(5) NOT NULL,
  destination varchar(5) NOT NULL,
  type varchar(15) NOT NULL,
  name1 varchar(55) NOT NULL,
  name2 varchar(55) NOT NULL,
  number varchar(55) DEFAULT '',
  text text,
  cr_dt timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
   UNIQUE KEY aedi_id (one,search_id,session_id,origin,destination,pnr,number) //I have this
  UNIQUE KEY aedi_id (one,search_id,session_id,origin,destination,pnr,name1,name2,number) I want this
)

A: The syntax is:
alter table drop key aedi_id;

alter table add key aedi_id (one, search_id, session_id, origin, destination, pnr, name1, name2, number) ;

Note that a unique key is implemented as an index, which will be used for queries.  This means that the order of the columns matters in the key definition -- some orderings will work better for your queries.  So, depending on your queries, you may want to re-arrange the columns.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Combination of CUDA 9 and GCC4.3 compiled C++ Software I currently need to write a project paper for my studies. My challenge will be to find some calculations in a given software, that can be put on a graphics card to speed up the whole software.
The problem I currently have is to decide whether to use CUDA or OpenCL.
I wanted to start checking if CUDA would be a good choice for my aims, but i cannot find any posts about the following problem:
The software I should analyze uses GCC 4.3 and c++03 standard (I know that's very old, but these are requirements by the client).
Is it possible to take a newer CUDA version and make it work with software compiled by gcc4.3?
I hope somebody might help me with this.

A: Okay, I tested linking of nvcc 9 compiled cuda kernel against gcc4.3 compiled C++ code and it worked fine.


text:
Q: Non-stationary Lamé equation and WZW/Virasoro conformal blocks The non-stationary Lamé equation
$\left(2i \pi \kappa \partial_\tau -\partial_x^2+g(g-1)\wp(x)\right)\psi(x,\tau)=E \psi(x,\tau)$
appears as a BPZ type equation (for the 2 points Virasoro conformal blocks with one degenerate field on the torus), and as a KZ type equation (for the one point conformal blocks on the torus of a WZW model).
1) I am not familiar with the WZW model. Why does this equation appear twice? Is it just a coincidence?
2) Do these conformal blocks give different kind of solution to this equation?

A: There are known relations between KZ and BPZ equations. For the torus, see https://arxiv.org/abs/0706.1030 . That article describes relations between correlators of the H3+ model and Liouville theory from a path integral point of view.
This implies relations between differential equations. In Appendix A genus one differential equations are worked out.
Of course, this also implies relations between conformal blocks. Virasoro conformal blocks provide a particular basis of affine conformal blocks, for a particular choice of isospin variables.


text:
Q: Prove that a vector outside of Span join to an independet set Given vector space $V$, $B = \{{v_1, v_2, ... , v_n\}}$ an independent set in $V$.
The vector $w \notin Sp(B)$. I need to prove that $\{{v_1, v_2, ... , v_n, w\}}$ is an independent set.
I think - I can say that beause $w$ is not in $Sp(B)$ then it's not a linear combination of $\{{v_1, v_2, ... , v_n\}}$ and therefore $\{{v_1, v_2, ... , v_n, w\}}$ is an independent set.
But it is too short and I don't think it's enough for a proof... Can you help me understand how to write it more mathimatically?

A: To prove $v_1,\dots,v_n,w$ is a linearly independent set, take an arbitrary linear combination of these vectors and show the coefficients must all be zero. Say $c_1,\dots,c_{n+1} \in \mathbb{R}$ such that
$$c_1 v_1+ \cdots + c_nv_n + c_{n+1}w=0.$$
What happens if $c_{n+1} \neq 0$? (Hint: solve for $w$.) What about if $c_{n+1}=0$? (Use the fact that $v_1,\dots,v_n$ are linearly independent.)

A: Linear independence means that you cannot write a linear "dependence" on the vectors. So suppose that $\{v_1, \dots, v_n, w\}$ are not linearly independent. We can write a non-trivial linear relation (i.e., at least one of the coefficients is nonzero):
$ c_1 v_1 + \dots + c_n v_n + c w = 0$.
If $c = 0$, then you have a linear relation $c_1 v_1+ \dots + c_n v_n = 0$, but the set $\{v_1, \dots, v_n\}$ was linearly independent, so this cannot be a non-trivial linear relation.
If $c\neq 0$, then you can write $\frac{-1}{c} \left ( c_1 v_1 + \dots + c_n v_n\right) = w$, which means $w$ is in the span of $\{v_1, \dots, v_n\}$.  Specifically $w = \frac{-c_1}{c} v_1 + \dots + \frac{-c_n}{c} v_n$, so I can write $w$ as a linear combination of $\{v_1, \dots, v_n\}$. This contradicts that $w$ is not in the span of $\{v_1, \dots, v_n\}$.
It is also worth clarifying what linear independence means. When we say $\{v_1, \dots, v_n\}$ is linearly independent, we mean that if $c_1 v_1+ \dots+ c_n v_n = 0$ then $c_1 = c_2 = \dots = c_n = 0$. The only way to "combine" the vectors to get zero is to (scalar) multiply each by 0.
When you first learn linear algebra, it is easy to misunderstand the definition of "linear independence". You might think it means one vector is not in the span in the remaining vectors (like you hinted at in your question). For example, $[1 ~ 0]$ is not in the span of $[0 ~ 1]$ and $[0 ~ 2]$. However, $[1 ~ 0]$, $[0~1]$, and $[0~2]$ is not a linearly independent set. So the precise definition is actually important.


text:
Q: Is it possible to trigger events for google spreadsheet API V4 on save of new data on googlesheet? I am trying to fetch data from a google sheet using Google sheet API V4. Is it possible anyhow to know if someone has saved a data or made changes on the sheet? Based on that I want to make call to the api to get the data?
More like I am trying to keep my application synced with the google sheet. As soon as someone update the data, my application gets updated too.
I am using Nodejs.
How  do I do that?
Thanks in advance


text:
Q: How do I get windows version as a variable? I'm making some batch files to personalise my windows installations faster, but I need my batch to take a road depending on which Windows version it's running on.
If i could get the windows version into a variable i could build a conditional to take the right path.
I've been looking for an answer on google and even here but... the answers i've got dont meet what i need.
could someone help me please?...

A: If you're looking for the version number, that has been answered here: https://stackoverflow.com/a/13212088/1337519
C:\Users\somedude>wmic os get version
Version
6.1.7601

C:\Users\somedude>

and here: https://stackoverflow.com/a/13212116/1337519
@echo off
setlocal
for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" == "6.3" echo Windows 8.1
if "%version%" == "6.2" echo Windows 8.
if "%version%" == "6.1" echo Windows 7.
if "%version%" == "6.0" echo Windows Vista.
rem etc etc
endlocal


text:
Q: C#: How can I make the clock work correctly? I'm working on a new GitHub repository called Charms Bar Port using Visual Studio 2022 that requires the UI to show a clock and date at the lower left, as seen on this image.
However, the clock seems to never update regardless of the presence of:

*

*Background workers

*Timers

Is there a good way to continuously keep track of the time in a loop?
Using some code for background workers and/or timers from external sources have never functioned. For example: "8:34" will be stuck on the screen even if the time is "9:00".
    Timer t = new Timer();
    private void Form1_Load(object sender, EventArgs e)
    {
        // Normally, the timer is declared at the class level, so that it stays in scope as long as it
        // is needed. If the timer is declared in a long-running method, KeepAlive must be used to prevent
        // the JIT compiler from allowing aggressive garbage collection to occur before the method ends.
        // You can experiment with this by commenting out the class-level declaration and uncommenting
        // the declaration below; then uncomment the GC.KeepAlive(aTimer) at the end of the method.
        //System.Timers.Timer aTimer;

        // Create a timer and set a two second interval.
        t = new System.Timers.Timer();
        t.Interval = 2000;

        // Create a timer with a two second interval.
        //t = new System.Timers.Timer(2000);

        // Hook up the Elapsed event for the timer.
        t.Elapsed += OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        t.AutoReset = true;

        // Start the timer
        t.Enabled = true;

        // If the timer is declared in a long-running method, use KeepAlive to prevent garbage collection
        // from occurring before the method ends.
        GC.KeepAlive(t);

    }

    //timer eventhandler
    private void OnTimedEvent(object sender, EventArgs e)
    {
        //update label
            Date.Content = DateTime.Today.ToString("MMMM d");
            Week.Content = DateTime.Today.ToString("dddd");
            Clocks.Content = DateTime.Now.ToString("hh:mm");
        t.Enabled = true;
    }
}

A: You should use dispatcher to update UI from different thread.
Your code should be:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        _initTimer();
    }

    private Timer t = null;
    private readonly Dispatcher dispatcher = Dispatcher.CurrentDispatcher;

    private void _initTimer()
    {
        t = new System.Timers.Timer();
        t.Interval = 1000;
        t.Elapsed += OnTimedEvent;
        t.AutoReset = true;
        t.Enabled = true;
        t.Start();
    }

    private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        dispatcher.BeginInvoke((Action)(() =>
        {
            DateTime today = DateTime.Now;
            Clocks.Content = today.ToString("hh:mm:ss");
            // do additional things with captured 'today' variable.
        }));
    }
}


text:
Q: Joining two queries with different where clauses into 1 table This is probably a pretty simple question, but I have two separate queries that I would like to join into one table. One of the queries shows sign ups to my website by month and the other query shows sign ups that have made a purchase. I would like to combine the two queries into one table so I have the following table:
Month      Sign-ups  Sign-ups with Purchase
Jan 2019   250       40
Feb 2019   500       120

How can I do that? Here's my two queries:
Sign ups:
select
  count(u.id) as Sign_Ups
  , month(From_iso8601_timestamp(u.created)) as Month
from
   prodjoinreel.users u
where
  year(From_iso8601_timestamp(u.created)) = 2019
group by
  2
order by
  2 asc

Sign ups with purchase:
select
  count(distinct g.owner) as Sign_Ups_with_Reel
  , month(From_iso8601_timestamp(u.created)) as Month
from
  prodjoinreel.goals g
  right join prodjoinreel.users u on
    g.owner = u.id
where
  year(From_iso8601_timestamp(u.created)) = 2019
group by
  2
order by
  2 asc

thank you!

A: I think that you can just add a count(distinct u.id) to the second query:
select
  month(From_iso8601_timestamp(u.created)) as Month,
  count(distinct u.id) as Sign_Ups,
  count(distinct g.owner) as Sign_Ups_with_Reel
from
  prodjoinreel.users u
  left join prodjoinreel.goals g on g.owner = u.id
where year(From_iso8601_timestamp(u.created)) = 2019
group by 1
order by 1

Note: I changed your right join to a left join; most people tend to consider that right joins are rather counter-intuitive, and favor left joins instead.


text:
Q: Issue with updating Realm objects I have two Realm model classes
class ModelA: Object {
    let id = RealmOptional<Int>()
    dynamic var name: String!
    // some other variables that are also String! type
}

class ModelB: Object {
    let id = RealmOptional<Int>()
    let models = List<ModelA>()
    // other variables
}

And I have some JSON object which contains data for that models. I create ModelB instance then populate it with ModelA instances list the following way:
let json: JSON = ... // get it from somewhere, then use SwiftyJSON
let myModelB = ModelB()
myModelB.id.value = json["id"].object as? Int
// set other properties
let modelsA = json["models"].map { ModelA(value: $0.1.object) }
myModelB.models.appendContentsOf(modelsA)

The reason why I am using different approaches here is that propery names in JSON doesn't match to my property names for ModelB but for ModelA it is ok.
Somewhere later I use realm.add(objects, update: true) (inside realm.write) and that leads to the following exception:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key (null).'

According to the documentation:

If your model class includes a primary key, you can have Realm intelligently update or add objects based off of their primary key values using Realm().add(_:update:).

so both ModelA and ModelB has primaryKey() function and I believe that should work but it is not.
Furthermore, I removed update parameter in the call and added call to the realm.deleteAll() before adding new objects (both in write callback). In that case I get the following exception:

Terminating app due to uncaught exception 'RLMException', reason: 'Can't set primary key property 'id' to existing value 'xxxxxxx'.

Additionally if I try to go through the call stack, Xcode crashes. It also crashes if I try to inspect any Realm object in the debugger. I already have installed Realm Xcode plugin but nothing changes. I cannot understand what is going wrong here and why I get so strange behavior. Could someone tell me where is my mistake please?

A: I start project from scratch, base on example project. So I finished with:
import UIKit
import RealmSwift

// Dog model
class Dog: Object {
    dynamic var name = ""
    dynamic var age = 0
    dynamic var owner: Person? // Properties can be optional

    override class func primaryKey() -> String? { return "name" }
}

// Person model
class Person: Object {
    dynamic var name = ""
    let dogs = List<Dog>()

    override class func primaryKey() -> String? { return "name" }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        do {
            try NSFileManager.defaultManager().removeItemAtPath(Realm.Configuration.defaultConfiguration.path!)
        } catch {}

        let dogRexJSON: AnyObject = ["name": "Rex", "age" : 20]
        let dogLuckyJSON: AnyObject = ["name": "Lucky", "age" : 25]
        var somePerson = Person(value: ["name" : "Shurik", "dogs" : [dogRexJSON]])

        // Realms are used to group data together
        let realm = try! Realm() // Create realm pointing to default file

        // Save your object
        realm.beginWrite()
        realm.add(somePerson)
        try! realm.commitWrite()

        somePerson = Person(value: ["name" : "Shurik", "dogs" : [dogRexJSON, dogLuckyJSON]])
        try! realm.write { () -> Void in
            realm.add([somePerson], update: true)
            return
        }

        let val = realm.objectForPrimaryKey(Dog.self, key: "Lucky")
        print(val!.name) // as expected log >> Lucky

        return true
    }
}

Seems all works fine.


text:
Q: Check if a point (x0,y0,z0) lies inside a tetrahedron in Matlab I have a tetrahedron defined by 4 points xi,yi,zi (i = 1 to 4)
To check if an arbitrary point x0,y0,z0 is inside the tetrahedron, I am taking the volume route i.e. I replace one of the points by x0,y0,z0 and obtain the volume of the tetrahedron. I say that if all the 4 computed volumes turn out to be positive, then it lies with in the tetrahedron. Is there a better way of doing this ?
Details of calculation here

A: To know if a point is inside a tetrahedron the best/more robust way is computing on which side of each of the 4 planes is, and compare that to a point that is know to be inside.
Step by step:

*

*Compute geometric centre of tetrahedron

*Compute each of the 4 plane equations, in the form of ax+by+cz+d=0. (i.e. compute a,b,c,d from the points).

*Plug geometry centre of tetrahedron in each plane equation (x,y,z), and store the sign of the result (it will be positive on one side, negative on the other, zero if the point lies  in the plane)

*Plug desired point in each of the plane equations. If the sign of the result is the same for all 4 as the geometric centre, then it is inside of the equation


text: Q: discord-buttons This tag should be used for any questions regarding the JavaScript discord-buttons npm package. Please, do not use this tag for questions related to the built-in buttons in discord.js v13 and later or about Discord buttons in general.


text:
Q: VBA to update formula when a value changes in a refence range I have an Excel formula that gives me the last Friday's date "=TODAY()-WEEKDAY(TODAY())-1" in cell A1
I want to update cell A1 only when the values in reference range in another worksheet B2:D469 changes.
Below is the code i am using but the issue is code only works when i manually make a change in the range. However values in the range gets updated when source pivot table refresh. I want code to get updated when i refresh the pivot table and the values in the range "B2:D469" changes.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range

Set KeyCells = Worksheets.("Source").Range("B2:D469")

If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then

Worksheets.("Dashboard").Range ("A1").EnableCalculation = True

End If
End Sub

A: Range.Dependents
Range has a property Dependents which is a Range containing all cells that this Range affects, even if they are several steps removed. For example if C4 is "=B4" and B4 is "=A4", Range("A4").Dependents will include both B4 and C4.
So, in your case, if Target affects a cell you care about, it's included in the Range Target.Dependents. You can use this to accomplish your goal.
How to use it
Use the following as the code of ThisWorkbook. I've commented the heck out of it, but if you have questions feel free to ask in the comments.
Option Explicit

Private RangeToMonitor As Range
Private RangeToChange As Range

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

    '---If this is the first change since the workbook has been opened, define the ranges---
    If RangeToMonitor Is Nothing Then
        Set RangeToMonitor = Worksheets("Source").Range("B2:D469")
        Set RangeToChange = Worksheets("Dashboard").Range("A1")
    End If
    '---------------------------------------------------------------------------------------

    'First, check to see if Target is in the RangeToMonitor
    If Not Application.Intersect(Target, RangeToMonitor) Is Nothing Then
        'If so, set your date. Rather than using a formula in the cell - which could go haywire if someone messes with it - just set it straight from VBA
        RangeToChange.Value = Date - Weekday(Date) - 1
    'Second, check to see if a change to Target *triggers* any recalculation of cells in RangeToMonitor.
    'You can do this by looking at Dependents, which is all the cells affected by a change to Target, even several steps removed
    ElseIf hasDependents(Target) Then
        '(The above and below criteria cannot be done in one if condition because VBA boolean operators do not short circuit)
        If Not (Application.Intersect(Target.Dependents, RangeToMonitor) Is Nothing) Then
            RangeToChange.Value = Date - Weekday(Date) - 1
        End If
    End If
End Sub

'The reason for this function is that trying to use Target.Dependents when Target has no Dependents causes an error
'I use this function to verify that Target DOES have Dependents before attempting to find out if any of them affects RangeToMonitor
Private Function hasDependents(rng As Range)
On Error GoTo ErrHandler
    Dim test As Long
    test = rng.DirectDependents
    hasDependents = True
    Exit Function

ErrHandler:
    If Err.Number = 1004 Then
        '"No Cells Were Found"
        'This error signifies that Target has no Dependents, so we can safely ignore the change and exit the event.
        hasDependents = False
    Else
        Err.Raise Err.Number, , Err.Description
    End If
End Function


text:
Q: How to inherit from a style and to reach a deep element? I have a MenuItem-Style called "Home". The new MenuItem-Style "Right" shall inherit from it. The only thing which shall be overwritten is the ImageSource of the Image inside the style. This fancy trick from the last answer isn't doable here, because a style itself does not have a ImageSource-Property.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
    <Style x:Key="Home" TargetType="{x:Type MenuItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type MenuItem}">
                    <ControlTemplate.Resources>
                        <Storyboard x:Key="OnMouseEnter" />
                    </ControlTemplate.Resources>
                    <Grid x:Name="Grid" d:DesignWidth="150" d:DesignHeight="150">
                        <Image x:Name="Image" HorizontalAlignment="Center" VerticalAlignment="Center"
                   Source="/WpfControlLibrary_Battleship;component/Resources/MenuItemBackgrounds/Home.gif" />
                        <Viewbox x:Name="Viewbox">
                            <Label x:Name="Label" Content="{TemplateBinding Header}" />
                        </Viewbox>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="Mouse.MouseEnter" SourceName="Grid">
                            <BeginStoryboard x:Name="OnMouseEnter_BeginStoryboard" Storyboard="{StaticResource OnMouseEnter}" />
                        </EventTrigger>
                        <EventTrigger RoutedEvent="Mouse.MouseLeave" SourceName="Grid">
                            <StopStoryboard BeginStoryboardName="OnMouseEnter_BeginStoryboard" />
                        </EventTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="MinHeight" Value="0" />
        <Setter Property="Padding" Value="0" />
        <Setter Property="VerticalContentAlignment" Value="Center" />
        <Setter Property="HorizontalContentAlignment" Value="Center" />
        <Setter Property="Background" Value="{x:Null}" />
        <Setter Property="Foreground" Value="{x:Null}" />
        <Setter Property="MinWidth" Value="0" />
        <Setter Property="Header" Value="" />
    </Style>
    <Style x:Key="Right" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource Home}">

    </Style>
</ResourceDictionary>

The last question and its solution: How to inherit from a style and to overwrite something?(The following solution isn't adoptable in this case.)
<Style x:Key="Water" TargetType="Button">
    <Setter Property="Background">
        <Setter.Value>
            <ImageBrush ImageSource="/WpfControlLibrary_Battleship;component/Resources/ButtonBackgrounds/Water.jpg"/>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Grid">
                <Grid Background="{TemplateBinding Background}" ...
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="SomeOtherWaterStyle" BasedOn="{StaticResource WaterStyle" TargetType="Grid">
    <Setter Property="Background" Value="Red"/>
</Style>

A: In your case why dont you just use the Icon property of MenuItem to set the image? Use this instead of your Image:
 <ContentPresenter HorizontalAlignment="Center"
                      VerticalAlignment="Center"
                      ContentSource="Icon" />

and set the Icon property
 <Setter Property="Icon">
      <Setter.Value>
        <Image x:Name="Image"
               Source="/WpfControlLibrary_Battleship;component/Resources/MenuItemBackgrounds/Home.gif" />
      <Setter.Value>
 </Setter>

Then you can change the Image easily in your inherited Style:
<Style x:Key="Right" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource Home}">
   <Setter Property="Icon">
      <Setter.Value>
        <Image x:Name="Image"
               Source="/WpfControlLibrary_Battleship;component/Resources/MenuItemBackgrounds/Right.gif" />
      <Setter.Value>
 </Setter>
</Style>

As a general solution or if you could not use the Icon property to this problem i would externd the MenuItem Control, add my desired property and bind to that property in the template.
regards
flusser


text:
Q: Coroutines how to wait for the data and then continue process I'm learning coroutines with kotlin, and I have problem how process can wait until process 1 finished then it continue to process 2, from my sample below I have object Network which access API server using getNews(it's running well and get the data)
I called this getNews from refreshNews using asynch - await, with the purpose it wait for the data then it continue running, but "The program Not Wait", it just running process 2 then process 1 finish, so I cannot capture data from API in refresh news
// process 1 - calling api this running well can get the data see process 2

object Network {
    var status : NewsApiStatus =  NewsApiStatus.LOADING

    private var viewModelJob = Job()
    private val coroutineScope = CoroutineScope(viewModelJob + Dispatchers.Main)

    fun getNews(filter: String, page: Int =1) : newsData? {
        var allNews : newsData? = null
        coroutineScope.launch {
            RetrofitClient.instance.getAllNews(filter, page).enqueue(object: Callback<newsData>{
                override fun onFailure(call: Call<newsData>, t: Throwable) {
                    status = NewsApiStatus.ERROR
                }

                override fun onResponse(
                    call: Call<newsData>,
                    response: Response<newsData>
                ) {
                    status = NewsApiStatus.DONE
                    var listResult = response.body()
                    if (listResult != null) {
                        if (listResult.data.isNotEmpty())  {
                            allNews = listResult
                            Timber.tag(TAG).i( "process 1 total allNews = ${allNews!!.data.size}")
                        }
                    }
                }
            })
        }
        return(allNews)
    }
}

// process 2 - calling process 1 with runBlocking

fun refreshNews() = runBlocking{
    val newsData = async {
        Network.getNews("")
    }
    Timber.tag(TAG).i("proses 2 ${newsData.await()?.data?.size}")
    // here I want newsData to wait until it has data
}

// this main program that call process 2

class NewsListViewModel(application: Application) : AndroidViewModel(application) {
    init {
        refreshNews()
    }
}

A: launch returns a reference to the started job. You can use it to wait for the job to finish by calling join():
val job = GlobalScope.launch { // launch a new coroutine and keep a reference to its Job
    // ...
}
runBlocking {
    job.join() // wait until child coroutine completes
}

Currently, your getNews() launches a coroutine and immediately returns.  allNews isn't initialised at that point yet.
You need to either call job.join() inside getNews() (would make it blocking), or use async inside getNews() and return its result if you want to keep it asynchronous (you'd need to take the result differently from your http client as you won't be able to initialise the variable declared outside).
It's worth to go through the official coroutine docs:

*

*https://kotlinlang.org/docs/reference/coroutines/basics.html

*https://kotlinlang.org/docs/tutorials/coroutines/coroutines-basic-jvm.html


text:
Q: SQL Server Express 'NEW TRIGGER' BUTTON IS DISABLED I am new to SQL Server Express and I want to create a new trigger on my table.
But I found that the 'New trigger' button in my table's trigger folder shows Disabled.
When I right click on trigger folder it shows 'New trigger' button disabled and in gray color.
I am using SQL Server 2014 Express and Management Studio 2014.
Does anybody have any idea why it is happening?
Please suggest me some way out.

A: This a known issue (bug) with SSMS 2014.
Reference : https://connect.microsoft.com/SQLServer/feedback/details/873249/ssms-2014-new-trigger-is-disabled-for-older-2012-2008r2-versions-of-sql-server
Alternately, you can use something like :
CREATE TRIGGER TriggerName
    ON [dbo].[TableName]
    FOR DELETE, INSERT, UPDATE
    AS
    BEGIN
    SET NOCOUNT ON
    END

A: I know this post is older but I came across it when I was trying to use SQL Server Management Studio (SSMS) 2014 (12.0.5000.0) and found the New Trigger option grayed out when I was connecting to a SQL Server 2008 R2 Enterprise Database.  After further investigation Microsoft states that SSMS versions after 2014 SP1 (Not including SP1) have a fix for this.  Unfortunately, I did not find an update for SSMS 2014 that fixes this but posted by Ayo Olubeko on 4/8/2016, instructs people here (comments section) to download the latest version from Microsoft's download site that it now has a standalone installer and can easily be updated to resolve this specific issue.  Previous versions such as the June 2016 release should have this fixed and can be found (https://learn.microsoft.com/en-us/sql/ssms/previous-sql-server-management-studio-releases) but I decided to download the latest.
After downloading the 898MB installer for SSMS 2016 (13.0.16106.4) it appears that this option is no longer grayed out when I am connecting to the same database!

I hope this helps others who just have not made the jump to the latest SSMS yet like me.  Note that this does just open the template file that Vishal Gajjar mentioned in the comments of the question, and for me is not auto-populating the Table Name or any fields, but I also don't know if it is supposed to.  The interface looks similar so I don't see any reason why I am not going to be able to use this to replace and uninstall the 2014 version to get all of the updates and improvements.

A: It is worth noting that you can generate the skeleton script for creating the trigger through Visual Studio.
Simply make a connection to the database using server explorer, expand the tables folder, right-click on any table and hit New Trigger.

A: SSMS packaged in the Express versions are a subset of the full feature set of SSMS.
There are several other options that don't exists, including the GUI to enable and disable triggers.  I believe control over the SQL agent is another one of them.  If you connect to the Express DB engine with full version of SSMS the option would be present.
If you need that option try downloading the full trial version or developer version of SQL and install the SSMS that comes packaged with the full version.
Brad


text:
Q: MongoDB SECONDARY becoming RECOVERING at nighttime I am running a conventional MongoDB Replica Set consisting of 3 members (member1 in datacenter A, member2 and member3 in datacenter B).
member1 is the current PRIMARY and I am adding members 2 and 3 via rs.add(). They are performing their initial sync and become SECONDARY very soon. Everything is fine all day long and the replication delay of both members is 0 seconds until 2 AM at nighttime.
Now: Every night at 2 AM both members shift into the RECOVERING state and stop replication at all, which leads to a replication delay of hours when I am having a look into rs.printSlaveReplicationInfo() in the morning hours. At around 2 AM there are no massive inserts or maintenance tasks known to me.
I get the following log entries on the PRIMARY:
2015-10-09T01:59:38.914+0200 [initandlisten] connection accepted from 192.168.227.209:59905 #11954 (37 connections now open)
2015-10-09T01:59:55.751+0200 [conn11111] warning: Collection dropped or state deleted during yield of CollectionScan
2015-10-09T01:59:55.869+0200 [conn11111] warning: Collection dropped or state deleted during yield of CollectionScan
2015-10-09T01:59:55.870+0200 [conn11111] getmore local.oplog.rs cursorid:1155433944036 ntoreturn:0 keyUpdates:0 numYields:1 locks(micros) r:32168 nreturned:0 reslen:20 134ms
2015-10-09T01:59:55.872+0200 [conn11111] end connection 192.168.227.209:58972 (36 connections now open)

And, which is more interesting, I get the following log entries on both SECONDARYs:
2015-10-09T01:59:55.873+0200 [rsBackgroundSync] repl: old cursor isDead, will initiate a new one
2015-10-09T01:59:55.873+0200 [rsBackgroundSync] replSet syncing to: member1:27017
2015-10-09T01:59:56.065+0200 [rsBackgroundSync] replSet error RS102 too stale to catch up, at least from member1:27017
2015-10-09T01:59:56.066+0200 [rsBackgroundSync] replSet our last optime : Oct  9 01:59:23 5617035b:17f
2015-10-09T01:59:56.066+0200 [rsBackgroundSync] replSet oldest at member1:27017 : Oct  9 01:59:23 5617035b:1af
2015-10-09T01:59:56.066+0200 [rsBackgroundSync] replSet See http://dochub.mongodb.org/core/resyncingaverystalereplicasetmember
2015-10-09T01:59:56.066+0200 [rsBackgroundSync] replSet error RS102 too stale to catch up
2015-10-09T01:59:56.066+0200 [rsBackgroundSync] replSet RECOVERING

Which is also striking - the start of the oplog "resets" itself every night at around 2 AM:
configured oplog size:   990MB
log length start to end: 19485secs (5.41hrs)
oplog first event time:  Fri Oct 09 2015 02:00:33 GMT+0200 (CEST)
oplog last event time:   Fri Oct 09 2015 07:25:18 GMT+0200 (CEST)
now:                     Fri Oct 09 2015 07:25:26 GMT+0200 (CEST)

I am not sure if this is somehow correlated to the issue. I am also wondering that such a small delay (Oct  9 01:59:23 5617035b:17f <-> Oct  9 01:59:23 5617035b:1af) lets the members become stale.
Could this also be a server (VM host) time issue or is it something completely different? (Why is the first oplog event being "resetted" every night and not "shifting" to a timestamp like NOW minus 24 hrs?)
What can I do to investigate and to avoid?

A: Upping the oplog size should solve this (per our comments).
Some references for others who run into this issue

*

*Workloads that Might Require a Larger Oplog Size

*Error: replSet error RS102 too stale to catch up link1 & link2


text:
Q: Magento applies tax on product prices that already including tax I've added products prices with tax included (in the field Price [EUR] [ Including Tax])
Now when I put a product in the cart, Magento applies the tax to price that already including the tax!
Example: if the product has "Price [EUR] [ Including Tax]"=100€ in the cart I have:

Product price  € 100
Sub total     € 100
Taxes     € 20
Totale  €120 (but the correct price including taxes is 100€!)

instead I want this:

Product price  € 100
Sub totale     € 80
Taxes     € 20
Total  €100

I'v tried all the settings and I'm going mad! is there a solution?

A: I will repost idophir's comment, that fixed my issue that led me to this question. I wasted hours looking at tax settings and tax rules, to finally find my culprit in shipping origin settings:

Check out the link below. It says that the shipping origin country
  (System > Configuration > Sales > Shipping Settings > Origin) affects
  the the way the price is displayed in the cart. Strange.. http://www.magentocommerce.com/boards/viewthread/78069/

A: Make sure that the Origin Country is correctly specified under Configuration > Sales > Shipping Settings.

A: Go to System->Configuration->Sales->Taxes->Calculation
and search for Catalog Prices. Set the switch to "yes", then Magento assumes, that the tax is included in the catalog price.
Also check these setting in your store configuration scope, not only in default config.

A: I had the same issue and i was checking for soutions and came through this topic. Right now i got solution to my problem so telling you here.
In my case i previously selected 'Default Country' as United Kingdom in Default Tax Destination window, and i was signed in from an account with address other than United Kingdom. So all was fine, i tried every option and the tax was not updating on products and shopping cart page. When i logged out and found that it is working ;) Then i relized the issue. So if you have default country for tax calculation, check out the taxes with or without that. Hope it work for you.
And sorry i am late :)

A: when you go to TAX calculation section (Thats System->Configuration->Sales->Taxes->Calculation) you will find "catalog prices" you can customize whether you want to include price with TAX or not.


text:
Q: Java Anonymous Inner Class Calling Static Method I have the following code in an eclipse application:
import org.eclipse.swt.widgets.Listener;
public class X {
  public void test() {
     Listener eclipseListener = new Listener() {
        public void handleEvent(Event evt) {
            System.err.println("starting");
            Y.externalMethod();
            System.err.println("finished");
        }
    }
}

public class Y {
    public static void externalMethod() {
        System.err.println("in class Y");
    }
}

When I run method test in class X, I get the following output:

starting

I don't understand why externalMethod didn't run in class Y and why control didn't return to class X (it never prints 'finished' or 'in class Y').
Any ideas about why externalMethod doesn't run? Are anonymous inner classes not permitted to call static methods outside their class? If so, why does this code compile?

A: Instead of
    public void handleEvent(Event evt) {
        System.err.println("starting");
        Y.externalMethod();
        System.err.println("finished");
    }

you might have better luck with:
    public void handleEvent(Event evt) {
        System.err.println("starting handleEvent");
        try {
            Y.externalMethod();
        } finally {
            System.err.println("finished handleEvent");
        }
    }

That is,

*

*Put the method exit trace in finally

*Add method names to trace lines

A: The method handleEvent() is not invoked here. What you did is defining anonymous class and create an instance from it on the fly.
You need to register this listener (eclipseListener) to some event handler which will invoke the method handleEvent() when an event fires.


text:
Q: Angular ng-content use component data I'm trying to use the ng-content in Angular 5.
import { Component, Injectable } from '@angular/core';

@Injectable()
@Component({
 selector: 'my-component',
 template: '<ng-content></ng-content>',
})
export class PrintComponent {
  data = 'test'
}

And use it like:
<my-component>
  {{data}}
</my-component>

How can i access data in a similar manner?

A: After some trial and error i found a hacky solution.
Component:
import { Component, DoCheck, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'dynamic-tempate',
  template: '<ng-content></ng-content>'
})
export class DynamicComponent implements DoCheck {
  data = 'done'
  @Output() get = new EventEmitter()

  ngDoCheck() {
      this.get.emit(this.data)
  }
}

Usage:
<dynamic-template (get)='data = $event'>
  and the hack is {{data}}
</dynamic-tempate>

A: Do something like this.
import { Component } from '@angular/core';

/**
 * Component class to represent side pane.
 * @class SidePaneComponent
 */
@Component({
  selector: 'app-side-pane',
  styleUrls: ['./side-pane.component.scss'],
  templateUrl: './side-pane.component.html'
})
export class SidePaneComponent {
}

Side-pane.component.html
<ng-content select=".right-pane"></ng-content>

And you can use app-side-pane component like this.
  <app-side-pane>
    <div class="right-pane">
     // your content goes here.
    </div>
  </app-side-pane>

Just remember to add the class right-pane wherever you use the component. And this is called content projection in angular. You can find more details in here.


text:
Q: Can I add Test Cases based on Tags to an requirement bases query to Azure Test Plans I would like to create a test plan in Azure using a requirements based query that filters out test cases with a specific tag.
I've tried all sorts of filter options, but it seems that the second part of the query, which filters on test cases, doesn't affect the result. All test cases that are linked to a user story using "Tested by" are displayed in the test plan - no matter how I change the query.
I have tried different types of queries and different filter settings for linked work items, but I'm not getting the desired result.
A query-based test plan is not possible for organizational reasons.
The picture shows one of the variants I tried.
Many thanks in advance!
query


text:
Q: How to find what fonts are in my module of tkinter? How do i know what fonts are available in my tkinter? I tried the answers of others code to this question but it just won't work. Is tkinter fonts based on the installed fonts on the system or it comes preinstalled with tkinter

A: This question seemed to be answered fully here, along with code to see what each font will look like.
Although this may not be the fastest way, I would encourage you to look into this. It will not only allow you to see every available font, but will also allow you to create more modern looking UI much faster using Tkiner library, and Python.
You can find a clearer tutorial here on how to transfer what you create to Tkinter here.


text:
Q: Segmentation fault when using PyQt4 with python3 I receive a segmentation fault when importing PYQt4 with python (3.5.2) using ubuntu 16.04. For instance, the following code produce a segmentation fault:
import PyQt4.QtCore

I imagine that there are mismatches whith some modules installations... Here is the backtrace:
Program received signal SIGSEGV, Segmentation fault.
0x000000000055c220 in PyType_IsSubtype ()
(gdb) backtrace
#0  0x000000000055c220 in PyType_IsSubtype ()
#1  0x00007ffff4969221 in vp_convertor () from /usr/local/lib/python3.5/dist-packages/sip.so
#2  0x00007ffff4969ab5 in sip_api_convert_to_void_ptr () from /usr/local/lib/python3.5/dist-packages/sip.so
#3  0x00007ffff5f41b7d in ?? () from /usr/lib/python3/dist-packages/PyQt4/QtCore.cpython-35m-x86_64-linux-gnu.so
#4  0x00007ffff5e1eb54 in PyInit_QtCore () from /usr/lib/python3/dist-packages/PyQt4/QtCore.cpython-35m-x86_64-linux-gnu.so
#5  0x000000000060605e in _PyImport_LoadDynamicModuleWithSpec ()
#6  0x0000000000606618 in ?? ()
#7  0x00000000004e9c56 in PyCFunction_Call ()
#8  0x000000000052ad74 in PyEval_EvalFrameEx ()
#9  0x000000000052d2e3 in ?? ()
#10 0x0000000000529332 in PyEval_EvalFrameEx ()
#11 0x0000000000528814 in PyEval_EvalFrameEx ()
#12 0x0000000000528814 in PyEval_EvalFrameEx ()
#13 0x0000000000528814 in PyEval_EvalFrameEx ()
#14 0x0000000000528814 in PyEval_EvalFrameEx ()
#15 0x000000000052e12b in PyEval_EvalCodeEx ()
#16 0x00000000004ebcc3 in ?? ()
#17 0x00000000005b7167 in PyObject_Call ()
#18 0x00000000005b7f8a in _PyObject_CallMethodIdObjArgs ()
#19 0x000000000051ba98 in PyImport_ImportModuleLevelObject ()
#20 0x00000000005c7688 in ?? ()
#21 0x00000000004e9bc7 in PyCFunction_Call ()
#22 0x00000000005b7167 in PyObject_Call ()
#23 0x0000000000523800 in PyEval_CallObjectWithKeywords ()
#24 0x0000000000526fbc in PyEval_EvalFrameEx ()
#25 0x000000000052d2e3 in ?? ()
#26 0x000000000052dfdf in PyEval_EvalCode ()
#27 0x00000000005fd2c2 in ?? ()
#28 0x00000000005ff76a in PyRun_FileExFlags ()
#29 0x00000000005ff95c in PyRun_SimpleFileExFlags ()
#30 0x000000000063e7d6 in Py_Main ()
#31 0x00000000004cfe41 in main ()

Do you have any idea on how to solve the issue?

*

*SIP version is 4.19.3

*PyQt5 version is 5.9  might it be the problem?

thanks in advance!

A: I also ran into this issue today. My Python 3 and pip were from the package manager. But I then installed newer pip by get-pip.py.
From the stacktrace I got from gdb, it seems that maybe there is an alternative SIP library (I am using Python 3.6 though):
/usr/local/lib/python3.6/dist-packages/sip.so and
/usr/lib/python3/dist-packages/sip.cpython-36m-x86_64-linux-gnu.so.
I tested by the following code you had provided. If I deleted that .so in /usr/local/lib, it didn't complain. Instead, the segmentation fault was gone.


text:
Q: Use SRTP for secure UDP multicast communication I am thinking about a way to achieve UDP multicast security. I know that this is a general known issue in networking and I couldn't really find a solution to achieve this.
During research I've found SRTP as an extension to RTP which implements security aspects and is based on UDP. I've also found out that SRTP supports multicast communication. So I am asking myself if it is possible to use SRTP to achieve my goal?
If yes why is SRTP not generally used to solve this issue? What are disadvantages of using SRTP to realize secure UDP multicast?

A: SRTP is part of the SIP VoIP model.  With SIP, two people are communicating.  The symmetric keys required by SRTP are exchanged during SIP communication within TLS.  You could, theoretically, communicate the same key material to each Multicast UDP listener through a secure channel. But each listener would need to have the same symmetric key that was used to encrypt the data.


text:
Q: Need help making changes to my RollUp Summary Trigger I have created a Rollup Summary Trigger that will display a count of Assignments__c on the parent Contact page layout. The process for this has changed and now I need this field to display a sum of the Level__c field on the Assignment object. The Level field can only be populated with the following values: 1, 2, 3, or 4.

So if there are 3 Assignments associated to the Contact and they all have the Level field populated with the number 2. Then on the Contact the Total_Levels__c field should read 6.

Below is the current Apex Class followed by the Apex Trigger that I am using.
public with sharing class AssignmentServices {
public static void updateContacts(List<pse__Assignment__c> assignments)
{
    Set<Id> contactIds = new Set<Id>();
    for (pse__Assignment__c assignment : assignments) contactIds.add(assignment.pse__Resource__c);
    setTotalLevels(contactIds);
}
public static void setTotalLevels(Set<Id> contactIds)
{
    List<Contact> records = new List<Contact>();
    for (AggregateResult aggregate : [
        SELECT pse__Resource__c, count(Id) records
        FROM pse__Assignment__c
        WHERE Active_Assignment__c = true
        GROUP BY pse__Resource__c
    ]) records.add(generateRecord(aggregate));
    update records; // proper error handling advised
}
static Contact generateRecord(AggregateResult aggregate)
{
    return new Contact(
        Id=(Id)aggregate.get('pse__Resource__c'),
        Total_Levels__c=(Integer)aggregate.get('records')
    );
}}

The trigger:
trigger pseAssignment on pse__Assignment__c (after insert, after update, after delete) {
if (trigger.isAfter)
{
    if (trigger.isInsert)
    {
        AssignmentServices.updateContacts(trigger.new);
    }
    if (trigger.isUpdate)
    {
        AssignmentServices.updateContacts(trigger.new);
    }
    if (trigger.isDelete)
    {
        AssignmentServices.updateContacts(trigger.old);
    }
}}

A: Assuming Level__c is a numeric field, this change:
SELECT pse__Resource__c, sum(Level__c) records

should do it.
See the Aggregate Functions documentation.


text:
Q: ASP.NET Membership setup - Database problems I am setting up a membership provider, and as a result, I am getting the following error message:

An attempt to attach an auto-named database for file

C:\Users\Mcoroklo\Desktop\Programmering\Private
  Projekter\ASP.NET\Helpdesk\Version4\HelpDesk\ClientSite\App_Data\ASPNETDB.mdf
  failed. A database with the same name
  exists, or specified file cannot be
  opened, or it is located on UNC share.

I am new to setting up membership so I can't deny something really crucial is missing! :-)
I am quite sure this has something to do with my connection string and/or SQL Membership provider. I've the following setup in my web.config:
My connection string:
  <connectionStrings>
<add name="MembershipServer" connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\ASPNETDB.mdf; Trusted_Connection=Yes;"/>

My SQL provider
 <membership defaultProvider="AspNetSqlProvider">
  <providers>
    <clear/>
    <add connectionStringName="MembershipServer"
         name="AspNetSqlProvider"
         applicationName="/"
         type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </providers>
</membership>

My authentication and authorization:
 <authentication mode="Forms">

  <forms name=".ASPXFORMSAUTH" loginUrl="Site/Login.aspx"
      cookieless="UseCookies"  >
  </forms>
</authentication>

<authorization>
  <deny users="?"/>
</authorization>

The file structure in my website is I've two local databases in my directory. The membership one (ASPNETDB.MDF) is the one i point at with my connection string. I've used the ASP.NET tool to create it.
The other database I connect to via LINQ TO SQL classes and is in a different project (using tier layers).
Thanks a bunch!!

A: Visual Studio will initialize all of that for you. You are getting in it's way. It has yet to create and provision that database for you.
Delete the connection strings element, the membership element, the authentication element and the authorization element.
or better yet Start with a fresh Asp.Net Application
Then click Project(or website)> Asp.net Configuration and follow the steps.
otherwise you will need to create and provision your own db with aspnet_reqsql.exe.

A:

Try removing the \ before the database name.
AttachDbFilename=|DataDirectory|ASPNETDB.mdf
instead of:
AttachDbFilename=|DataDirectory|\ASPNETDB.mdf
Oh and another thought, you do have SQL Express loaded on the machine, correct?

A: Remember that machine.config defines a Connection String with the name "LocalSqlServer" and by default your app will use that.
To fix the problem, either explicitly remove the name like this:
<connectionStrings>
    <remove name="LocalSqlServer" />
    <!-- your new connection string here -->
</connectionStrings>

or use clear, but I haven't tested it:
<clear/>

Usually what I do is just overwrite the LocalSqlServer, so my connection string is named the same, that seems to fix most problems.
Like others have mentioned, you are attaching the ASPNETDB when it should do that for you when you setup your app using the ASP.NET Site Manager.


text:
Q: How to disable page load? I have a SVG animation on my website,which placed in the middle of page, and when i enter to my website, page loading, and SVG animation automatically draw the image, so how can i do that SVG animation load when i scroll down?
<script type="text/javascript">

    (function(){

        document.onreadystatechange = () => {

            if (document.readyState === 'complete') {

                /**
                * Setup your Lazy Line element.
                * see README file for more settings
                */

                let el = document.querySelector('#case');

                let myAnimation = new LazyLinePainter(el, {"ease":"easeLinear","strokeWidth":4.6,"strokeOpacity":1,"strokeColor":"#2ECC70","strokeCap":"square","delay":320});
                myAnimation.paint();

                let el1 = document.querySelector('#clients');

                let myAnimation1 = new LazyLinePainter(el1, {"ease":"easeLinear","strokeWidth":2.6,"strokeOpacity":1,"strokeColor":"#2ECC70","strokeCap":"square","delay":210});

                myAnimation1.paint();
            }
        }

    })();

</script>

A: You can load it within scroll event handler when user scrolls down
// jquery solution
var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (lastScrollTop != 'loaded' && st > lastScrollTop){
            let el = document.querySelector('#case');

            let myAnimation = new LazyLinePainter(el, {"ease":"easeLinear","strokeWidth":4.6,"strokeOpacity":1,"strokeColor":"#2ECC70","strokeCap":"square","delay":320});
            myAnimation.paint();

            let el1 = document.querySelector('#clients');

            let myAnimation1 = new LazyLinePainter(el1, {"ease":"easeLinear","strokeWidth":2.6,"strokeOpacity":1,"strokeColor":"#2ECC70","strokeCap":"square","delay":210});

            myAnimation1.paint();
   }
   lastScrollTop = 'loaded';
});

This should start loading the svg first time user scrolls down on your page.


text:
Q: How can i download individual map tiles from the Google Maps SDK (for iOS)? I've been checking out the new Google Maps SDK for iOS that allows you to bypass Apple Maps for map related features in your app!
https://developers.google.com/maps/documentation/ios/intro
The SDK seems fairly easy to use, but i want to know:

*

*If it is possible to use the SDK (are there API's) to download individual Map tiles?

*If so, how?

Ive looked at the documentation given on their developer portal and it says the following:
https://developers.google.com/maps/documentation/ios/map

The key class when working with a Map object is the GMSMapView class. GMSMapView handles the following operations automatically:

*

*Connecting to the Google Maps service.

*Downloading map tiles.

*Displaying tiles on the device screen.

*Displaying various controls such as pan and zoom.

*Responding to pan and zoom gestures by moving the map and zooming in or out.

*Responding to two finger gestures by tilting the viewing angle of the map.

It seems like the downloading of the tiles happens automatically, or are there API's that allow manual access to the tiles?
If not, any workarounds would also help!

A: The documentation and header files do not indicate any way to download individual map tiles.
Even if you would find a workaround, you would not be allowed to use it. See clause 10.1.1 (a) in the Terms of Service:

No Access to Maps API(s) except through the Service. You must not access or use the Maps API(s) or any Content through any technology or means other than those provided in the Service, or through other explicitly authorized means Google may designate. For example, you must not access map tiles or imagery through interfaces or channels (including undocumented Google interfaces) other than the Maps API(s).


text:
Q: Compile PHP-CPP on Windows Machine I`m trying develop a extension to PHP with PHP-CPP on Windows. I build the .a and .so of PHP-CPP with MingW, but, when i go build the extension the compiler not found the phpcpp.h.
My file Makefile:
NAME                    =   Teste
INI_DIR             =   /etc/php5/conf.d
EXTENSION_DIR           =   $(shell php-config --extension-dir)
EXTENSION           =   ${NAME}.so
INI                     =   ${NAME}.ini
COMPILER                =   g++
LINKER              =   g++
COMPILER_FLAGS      =   -Wall -c -O2 -std=c++11 -fpic -o
LINKER_FLAGS            =   -shared
LINKER_DEPENDENCIES =   -lphpcpp
RM                  =   rm -f
CP                  =   cp -f
MKDIR                   =   mkdir -p
SOURCES             =   $(wildcard *.cpp)
OBJECTS             =   $(SOURCES:%.cpp=%.o)
all:                    ${OBJECTS} ${EXTENSION}
${EXTENSION}:           ${OBJECTS}
                ${LINKER} ${LINKER_FLAGS} -o $@ ${OBJECTS}
${LINKER_DEPENDENCIES}
${OBJECTS}:
                ${COMPILER} ${COMPILER_FLAGS} $@ ${@:%.o=%.cpp}
install:
                ${CP} ${EXTENSION} ${EXTENSION_DIR}
                ${CP} ${INI} ${INI_DIR}
clean:
                ${RM} ${EXTENSION} ${OBJECTS}

Folder Structure:

main.cpp
Makefile
phpcpp.a
phpcpp.so
Sorry for my bad English.

A: You can try to generate a visual studio project with cmake / cmake gui - there is a "CMakeLists.txt" in the root folder of "PHP-CPP" Directory.
Now you can compile it with msvc ... but be aware of the mixed code from c and c++ - there are some .c headers included - maybe you have to edit some compiler options ...

A: You can try the following to generate an .dll of phpcpp with Linux (here Ubuntu):
First be sure you have installed the PHP version 7.4. The "dev" as also the "standard" package of PHP 7.4.
Now compile the PHPCPP with "sudo make" in the main Folder of PHPCPP.
Now you got some ".o" files. These are located in the /shared/zend/ of the main PHPCPP Folder.
Now you can create an ".dll" File out of these ".o" files - like the following (extracted from here):
sudo g++ -shared -o phpcpp.dll zval.o zendcallable.o valueiterator.o value.o throwable.o super.o streams.o streambuf.o stream.o script.o sapi.o object.o namespace.o module.o members.o base.o callable.o eval.o classbase.o classimpl.o constant.o constantfuncs.o error.o exception.o exception_handler.o exists.o extension.o extensionimpl.o file.o function.o functor.o global.o globals.o hashmember.o ini.o inivalue.o iteratorimpl.o

it is not completely tested ... be careful ...


text:
Q: How to move an object in x y (diagnoal) direction in Silverlight C# i want to move an canvas in diagonal direction
when i tried to TranslateTransform in xaml it works but from code behind it is not working
<Canvas.RenderTransform>
   <TranslateTransform X="1" Y ="1"/>
</Canvas.RenderTransform>

code:-
public void AnimateTo(Canvas c)
{
        // update the value
        TranslateTransform translate = c.RenderTransform as TranslateTransform;
        translate.Y = --x;
        translate.X = --y;
}

Can some one help me

A: You cannot access the RenderTransform this way in code.  Set a name to your TranslateTransform tag like this :
<Canvas.RenderTransform>
    <TranslateTransform x:Name="myCanvasTranslate" X="1" Y ="1"/>
</Canvas.RenderTransform>

then in code, use :
myCanvasTranslate.X++;
myCanvasTranslate.Y++;


text:
Q: Kendo Mobile ListView not paging I'm using Kendo Mobile ListView, and I have problem with pagination, first page is displayed but after that my ListView seems stuck, i.e. loader appears, but no data is added to my list, also I can see in my debugger that data was pulled from the server. Here is my code:
m_userRoutines: new kendo.data.DataSource({
        serverFiltering: false,
        serverPaging: true,
        pageSize: 20,
        transport: {
            read: {
                url: pub.serverUrl + "api/Statistics/GetAllRoutinesUserHasDone",
                beforeSend: function (req) {
                    //radi uz data type json
                    req.setRequestHeader("Authorization", "Bearer " + app.loginToken);
                },
                dataType: "json"
            }
        },
        requestEnd: function (e) {
            console.log("user routines loaded", e.response);
        },
        schema: {
            data: function (data) {
                return data;
            },
            total: function (data) {

                return m_userWorkouts.get("workoutsCount");
            }
        }
    }),

A: I believe I found answer, according to Kendo Mobile documentation:

In order for the scrolling to occur smoothly, the page size should not
  be too low. For example, if 5 items are visible on the page, at least
  15 physical DOM elements are needed, which means that the DataSource
  page size should be 30 or greater.

Problem with my page size is that it was too low, when I set my pageSize to 60 everything worked fine :)


text:
Q: How to connect with multi mysql db how do i configure my php connection file to connect with 2 or more database ?
<?php
if(!isset($_SESSION))
    {
session_start();
}
date_default_timezone_set("Asia/Kolkata");
$uid=$_SESSION['user_id'];
$connect['database'] ='mydb';

/** MySQL database username */
$connect['user']='root';
/** MySQL database password */
$connect['password']='';
/** MySQL hostname */
$connect['host']='localhost';
$host= mysqli_connect($connect['host'],$connect['user'],$connect['password'],$connect['database']);
?>


text:
Q: PyQt5: Issues with a Mixin with a metaclass within a derived QWidget class I'm having issues trying to add a mixin with a metaclass to a class whose base is a QWidget. I'm aware that PyQt5 supports cooperative multiple inheritance and if my MixIn class has no metaclass then things work fine. However, if it has a metaclass - whether it be the pyqtWrapperType metaclass shared by QWidgets or a derived metaclass, then I receive the following error:
Process finished with exit code -1073741819 (0xC0000005)
The code for the rest of the script runs, but the QWidget does not show up. Here's the base code (stripped of the methods since I know they're not necessary for the problem)
import abc, sys
from PyQt5 import QtWidgets, QtCore

# Test Metaclass, will have more if metaclasses work
class MyMeta(abc.ABCMeta, QtCore.pyqtWrapperType):
    def __init__(cls, name, bases, attrs):
        super(MyMeta, cls).__init__(name, bases, attrs)

# MixIn class - ignore the calls to methods for now
# Have same issue if metaclass set to pyqtWrapperType
class LocatorWidget(metaclass=MyMeta):
    def __init__(self, locator=None, name='', parameters={}, **kwargs):
        super().__init__(**kwargs)
        # self.setup_parameters(parameters)
        self.locator = locator
        self.name = name if name else ''
        self.widgetType = self.__class__.__name__.replace('LW', '')
        # self.setup()

# Derived class with a QWidget base
class LWComboBox(QtWidgets.QComboBox, LocatorWidget):
    def __init__(self, locator, **kwargs):
        super().__init__(locator=locator, **kwargs)

def main():
    app = QtWidgets.QApplication(sys.argv)
    # locator is class in full code, using this as filler for now
    locator=[0,1,2,3]
    cb = LWComboBox(locator=locator)
    cb.addItems([str(x) for x in range(5)])
    # Test to see if attribute is set
    print(cb.locator)

    window = QtWidgets.QDialog()
    window.form = QtWidgets.QFormLayout()
    window.form.addRow(cb)
    window.setLayout(window.form)

    window.show()

if __name__ == '__main__':
    main()

I am not having the metaclass conflict error: The base class and derived classes do not have different metaclasses because MyMeta is derived from pyqtWrapperType.
If this process doesn't work I'm wondering if I should stick with my previous idea which was enveloping the widget with the attributes and methods I want to share in a separate class, the widget being one of the attributes, but it'll be nice to subclass QWidgets directly with the necessary abstract methods and attributes.
As an FYI I an running PyCharm 2016.2.3 in Anaconda with PyQt5 version 5.6 (PyQt can't be updated to later versions in Anaconda)

A: The pyqtWrapperType no longer exists. If you want the equivalent type in PyQt5, you can use either:
pyqtWrapperType = type(QtCore.QObject)

or:
from sip import wrappertype as pyqtWrapperType


text:
Q: Kopano LDAP unable to login when username has special character Ok, so I currently have a Kopano server working with Openldap to manage logins. The problem I currently have is that if I decide to define a user's login as his email, I can't send a message via Thunderbird (incoming server is an IMAP server going over port 993 and the outgoing server is SMTP with STARTTLS over port 587). Authentication keeps failing. I.E. like below:
username: john@test.com
password: whatever

Logs show me this:
Jun  6 17:32:50 courrier postfix/submission/smtpd[23440]: connect from modemcable202.76-70-69.static.videotron.ca[69.70.76.202]
Jun  6 17:32:50 courrier postfix/submission/smtpd[23440]: Anonymous TLS connection established from modemcable202.76-70-69.static.videotron.ca[69.70.76.202]: TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)
Jun  6 17:32:50 courrier postfix/submission/smtpd[23440]: warning: SASL authentication failure: Password verification failed
Jun  6 17:32:50 courrier postfix/submission/smtpd[23440]: warning: modemcable202.76-70-69.static.videotron.ca[69.70.76.202]: SASL PLAIN authentication failed: authentication failure
Jun  6 17:32:50 courrier postfix/submission/smtpd[23440]: warning: modemcable202.76-70-69.static.videotron.ca[69.70.76.202]: SASL LOGIN authentication failed: authentication failure
Jun  6 17:32:54 courrier postfix/submission/smtpd[23440]: disconnect from modemcable202.76-70-69.static.videotron.ca[69.70.76.202]

However, the strange part is that if I change the credentials to this:
username: john
password: whatever

Now I can send my emails normally and the logs show me this:
Jun  6 17:34:13 courrier postfix/submission/smtpd[23440]: connect from modemcable202.76-70-69.static.videotron.ca[69.70.76.202]
Jun  6 17:34:14 courrier postfix/submission/smtpd[23440]: Anonymous TLS connection established from modemcable202.76-70-69.static.videotron.ca[69.70.76.202]: TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)
Jun  6 17:34:14 courrier postfix/submission/smtpd[23440]: 27DF7307CBFF: client=modemcable202.76-70-69.static.videotron.ca[69.70.76.202], sasl_method=PLAIN, sasl_username=edastous
Jun  6 17:34:14 courrier postfix/cleanup[23195]: 27DF7307CBFF: message-id=<5ce1fb94-096b-e613-5686-77a2b631e6eb@addlys.com>
Jun  6 17:34:14 courrier postfix/qmgr[1843]: 27DF7307CBFF: from=<edastous@addlys.com>, size=780, nrcpt=1 (queue active)
Jun  6 17:34:14 courrier postfix/submission/smtpd[23440]: disconnect from modemcable202.76-70-69.static.videotron.ca[69.70.76.202]
Jun  6 17:34:15 courrier postfix/smtp[23447]: 27DF7307CBFF: to=<anonymous@hotmail.com>, relay=hotmail-com.olc.protection.outlook.com[104.47.49.33]:25, delay=1.6, delays=0.14/0.02/0.4/0.98, dsn=2.6.0, status=sent (250 2.6.0 <5ce1fb94-096b-e613-5686-77a2b631e6eb@addlys.com> [InternalId=37104222519256, Hostname=DM3NAM05HT118.eop-nam05.prod.protection.outlook.com] 6330 bytes in 0.280, 22.047 KB/sec Queued mail for delivery)
Jun  6 17:34:15 courrier postfix/qmgr[1843]: 27DF7307CBFF: removed

Does anyone have any idea what could be causing this?
EDIT: Here is the result of postconf -n | grep sasl
smtp_sasl_tls_security_options = noanonymous
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unknown_helo_hostname, reject_unauth_destination, reject_non_fqdn_hostname, reject_non_fqdn_sender, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unknown_sender_domain, reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net, reject_rbl_client cbl.abuseat.org, permit
smtpd_relay_restrictions = permit_sasl_authenticated, permit_mynetworks
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous

A: You're mentioning that SASL auth works until you change the username from "john" to "john@test.com", right? Unfortunately, you did not post your SASL configuration, e.g. /etc/sysconfig/saslauthd, thus I just can assume that you're not starting up saslauthd using -r, but without (because that's the default). See also man 8 saslauthd for what -r is doing.


text:
Q: When adding Facebook sdk as library project other libraries are not recognised by eclipse I am integrating Facebook sdk for social login to my app. Fo that I created one separate app first and made sure everything working fine. After that when I am trying to do same with my app I am getting compilation errors.
As soon as I include Facebook sdk as library project to my project, other imports being used in my project become unrecognized:
import org.achartengine.chart.PointStyle;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.MultipleCategorySeries;
import org.achartengine.model.TimeSeries;

I tried including facebooksdk.jar to accomplish this task. This way I did not get any compilation error, but now application crashes at run time saying :
01-14 14:56:57.092: E/AndroidRuntime(12753): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.app/com.test.app.ui.login.LoginActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class com.facebook.widget.LoginButton
...
01-14 14:56:57.092: E/AndroidRuntime(12753): Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class com.facebook.widget.LoginButton
...

Project.properties:
Project target.
target=android-21

    android.library.reference.3=../FlowLayout
    android.library.reference.4=../library
    android.library.reference.1=../AndroidUtils
    android.library.reference.2=../AudioPlayer
    android.library.reference.6=../Scribble
    android.library.reference.5=../StoryRenderer
    android.library.reference.8=../VO
    android.library.reference.7=../Service
    android.library.reference.9=../Keyboard
    android.library.reference.10=../EventManager
    android.library.reference.11=../HoloGraphLibrary
    android.library.reference.12=../../../android-sdks/extras/android/support/multidex/library
    android.library.reference.13=../../../Downloads/facebook-android-sdk-3.22.0/facebook

Can anybody help me?
Thanks,
Rahul

A: I got the solution. I included FB Sdk as library project. FB SDK was also having android-support-v4.jar and my project was also having that. So this conflict made private libraries removed.(Do not know why.)
So I removed android-support-v4.jar from Facebook SDK and refered already existing one which resolved my problem.


text:
Q: Set environment variable from Azure Role to use in PHP I'm using this code:
Environment.SetEnvironmentVariable("ConnectionString", connString, EnvironmentVariableTarget.[User|Process|Machine]);
on OnRoleEnvironmentChanged event of Azure RoleEntryPoint class to set a connection string on an Environment Var and use it in PHP but it doesn't work.
Using User or Process as target it simply doesn't work, using Machine the role cannot execute the instruction (maybe because of user restrictions)
How can I set variable from Azure Role in .NET to consume in PHP?

A: Why don't you simply use the getConfigurationSettings() method in the Windows Azure PHP SDK? If you really want to set the environment variable, I suggest you try again with Machine but only after you changed the executionContext of your role to elevated.


text:
Q: Need to Sync Oracle DB table data with mysql I have a table with some data in oracle which i want to sync with mysql table once in a day, like a cron job.
Is there any tool available which i can use as a cron job in Linux?.
Thanks,


text:
Q: Emacs: Define macro in comment and automatically execute it I'm using Emacs/AucTeX for editing LaTeX files. In some of my LaTeX files, I have defined some "file-specific" command (e.g. \todo{...} in one file, \compute{...} in another, and so on), so I can keep track of what open problems I have in my documents.
The Emacs command highlight-regexp does quite a good joob in highlightning all occurences of \todo{...}s resp. \compute{...}s. But up to now I have to execute the highlightning manually every time I open the corresponding file.
Is there a way of telling Emacs/AucTeX to invoke specific commands when opening a particular file? I would like to define these commands inside the corresponding file, so I can easily adjust it for different files (maybe included in local variables).
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "master"
%%%
%%% here I would like to have something like:
%%% execute highlight-regexp for specific arguments
%%%
%%% End:

A: Try this,
%%% Local Variables:
%%% eval: (font-lock-add-keywords nil '(("\\\\todo" (0 font-lock-warning-face))))
%%% End:

See Section 57.3.4.1, Specifying File Variables, for more details.

A: You could use a hook in combination to local vars.  For example,  you could add a local variable dohighlight or something and then write a function like this:
(defun condhighl ()
 (when (boundp 'dohighlight)
 (highlight-regexp "regexp")))

and then add that function as a hook for AucTex
(add-hook 'tex-mode-hook 'condhighl)

You can then add the dohighlight var in your local vars to buffers you want to highlight the code in.

A: After using highlight-regexp to set up your highlighting, hi-lock-write-interactive-patterns (M-s h w) will write the patterns into the buffer as a magic comment.
You probably want to add a mode: hi-lock after the mode: latex line too, to activate the highlighting as soon as you open the file.


text:
Q: UWP: How to get list of all Page Objects and the corresponding TypeName in the Assembly In UWP, How do I get a list of all the Page Objects and their corresponding string name in the Assembly.  For Example, if I create a Page called Page1, Page2, and Page3 and populate these pages with XAML with controls, how can I can I dynamically create a list of all Page Objects and their corresponding string name?
I have some code that works for WPF and I want to know how to do something similar in UWP:
class MyPage : Page {
public List<Uri> GetXamlFiles()
{
    var pages = new List<Uri>();
    var asm = System.Reflection.Assembly.GetExecutingAssembly();
    Stream stream = asm.GetManifestResourceStream(
        asm.GetName().Name + ".g.resources");

    DataContext = pages;

    using (var reader = new System.Resources.ResourceReader(stream))
    {
        foreach (System.Collections.DictionaryEntry entry in reader)
        {
            pages.Add(new Uri(((string)entry.Key).Replace(".baml", ".xaml"),
                UriKind.Relative));
        }
    }
    return pages;
}

public ObservableCollection<TXamlPage> XamlPages = null;

private void Page_Loaded(object sender, RoutedEventArgs e)
{
        List<Uri> pages = GetXamlFiles();

        XamlPages.Clear();
        foreach (var uri in pages)
        {
            XamlPages.Add(new TXamlPage { uri = uri, Name = System.IO.Path.GetFileName(uri.LocalPath)});
        }
        A1ListBoxPages.ItemsSource = pages;
    }

} //class

public class TXamlPage
{
    public string Name;
    public Uri uri;

    public override string ToString()
    {
        if (Name == null) return "<null>";
        return Name;
    }
}

A: You could just search for all types deriving from Page:
private IEnumerable<TypeInfo> GetAllPageTypes()
{
    var currentAssembly = this.GetType().GetTypeInfo().Assembly;
    var pageTypeInfo = typeof(Page).GetTypeInfo();
    return currentAssembly.DefinedTypes.Where(t => pageTypeInfo.IsAssignableFrom(t)).ToList();
}


text:
Q: Laying out radio buttons with additional label in dojox.layout.TableContainer I have a problem laying out a number of rows each containing a label and two radio buttons with their own labels in a dojox.layout.TableContainer. When you use a normal label, it throws the layout out completely. As an alternative to using a label, I thought of using a dijit.form.TextBox, but this looks bad, so what I currently have is this (but it looks hideous because the text fields con):
            <div dojoType="dojox.layout.TableContainer" cols="3" customClass="labelsAndValues">
                <input dojoType="dijit.form.TextBox" readOnly value="Would you like to apply for residency?">
                <input type="radio" dojoType="dijit.form.RadioButton" name="residency"
                       value="No" title="No"/>
                <input type="radio" dojoType="dijit.form.RadioButton" name="residency"
                       value="Yes" title="Yes"/>
                <input dojoType="dijit.form.TextBox" disabled readOnly value="Are you currently residing overseas?">
                <input type="radio" dojoType="dijit.form.RadioButton" name="overseas"
                       value="No" title="No"/>
                <input type="radio" dojoType="dijit.form.RadioButton" name="overseas"
                       value="Yes" title="Yes"/>
            </div>

I guess it would be nice to have a dijit.form version of a label that plays together nicely with the TableContainer, but in the absence of that, what can I do?

A: Well, the solution I am using now is perhaps not the most elegant, but it plays together with the TableContainer, and that is to wrap the text for the long label in a dijit.layout.ContentPane.


text:
Q: java.net.SocketException: Connection reset in spring Rest template I have a strange problem here.
The below code is working fine until I restart the tomcat server at client side. Once I restart the tomcat server (client program is there in the war file) with the latest war file of the same code, it throws the below error.
I am using JDK 8.
Below is the sample code. From the browser, I am able to get a response from the URL used in the below program. but not able to get the data using java program or Postman also.
package com.example.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class TestService implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        download();
    }

    private void download() {
        System.out.println("Started download");
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://www.nseindia.com/live_market/dynaContent/live_watch/stock_watch/niftyStockWatch.json";
            byte[] forObject = restTemplate.getForObject(url, byte [].class);
            System.out.println(forObject);
            System.out.println("Downloaded");
        } catch (Exception e) {
            System.out.println("Exception " + e);
        }
    }
}

Here's the exception raised:
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://www.nseindia.com/live_market/dynaContent/live_watch/stock_watch/niftyStockWatch.json": Connection reset; nested exception is java.net.SocketException: Connection reset
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:751)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677)
    at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:345)
    at com.sudhasoft.service.impl.StocksServiceImpl.getNiftyData(StocksServiceImpl.java:183)
    at com.sudhasoft.service.impl.StocksServiceImpl.getNifty500Data(StocksServiceImpl.java:154)
    at com.sudhasoft.service.impl.PatternServiceImpl.getDataBySignal(PatternServiceImpl.java:444)
    at com.sudhasoft.service.impl.PatternServiceImpl.loadDataOnInit(PatternServiceImpl.java:1090)
    at com.sudhasoft.service.CacheServiceImpl.initCache(CacheServiceImpl.java:29)
    at com.sudhasoft.scheduler.job.CacheJob.clearCache(CacheJob.java:41)
    at com.sudhasoft.scheduler.job.CacheJob.executeJob(CacheJob.java:25)
    at com.sudhasoft.scheduler.StockScheduler$1.run(StockScheduler.java:120)
Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.security.ssl.InputRecord.readFully(Unknown Source)
    at sun.security.ssl.InputRecord.read(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
    at sun.security.ssl.AppInputStream.read(Unknown Source)
    at okio.Okio$2.read(Okio.java:139)
    at okio.AsyncTimeout$2.read(AsyncTimeout.java:237)
    at okio.RealBufferedSource.indexOf(RealBufferedSource.java:345)
    at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:217)
    at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:212)
    at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
    at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
    at okhttp3.RealCall.execute(RealCall.java:77)
    at org.springframework.http.client.OkHttp3ClientHttpRequest.executeInternal(OkHttp3ClientHttpRequest.java:73)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:742)
    ... 10 common frames omitted

A: The simplest answer is when you restart tomcat simply you close the socket and then you try to send more data to the closed socket.
that is why you get IO exception since you can't write data

A: This seems to be due to a firewall issue.
In order to solve this issue, you will need to use Proxy Server.
You can add proxy server and port using following 2 lines of code:
System.setProperty("proxyHost", "proxyServer.proxy.com");
System.setProperty("proxyPort", "9801");

A: This looks like proxy related error.
You need to provide proxy information in order to connect over that URL.
Its working in browser because an internet proxy might already be configured there, it needs to be explicitly provided at code level in order to connect over internet.
Same is the case with Postman. You have to provide proxy server information under Postman configuration.


text:
Q: Creation of datetime field in MongoDB not working properly I am trying to insert a document with datetime in Mongo through python fastapi. My code is as follows. The below code runs inside an API.
myclient = pymongo.MongoClient("mongodb://0.0.0.0:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydict = {"name": "John123", "address": "Highway 37", "timeCreated": datetime.datetime.utcnow()}
x = mycol.insert_one(mydict)

First time I am able to insert the document. Second time when I hit the same API with some other data say different name, I am getting the following error
"E11000 duplicate key error collection: lumin_ent_saas.temp_ent_saas_users index: _id_ dup key: { _id: ObjectId('6346b73e06b6b3e59e7d6cb7') }, full error: {'index': 0, 'code': 11000, 'errmsg': \"E11000 duplicate key error collection: mydb.mycol index: _id_ dup key: { _id: ObjectId('6346b73e06b6b3e59e7d6cb7') }\", 'keyPattern': {'_id': 1}, 'keyValue': {'_id': ObjectId('6346b73e06b6b3e59e7d6cb7')}}"

It is throwing error like object_id already exists but I am trying to insert new data.
But this code works perfectly when run standalone without an API. I am able to insert documents.
I am suspecting there is something wrong with the way Mongodb inserts time. I think it considers same time till I restart the API. Can anyone help here?


text:
Q: Reparametrization of a disk. I know what is a reparametrization of a curve, $\gamma(t)$, is. But what is the definition of a reparametrization of a domain $X(u,v) = (x(u,v), y(u,v))?$
For example, how do we reparametrize the disk $D_r = \{(x,y): x^2+y^2<r.\}$
Note that this is a question my friend who is taking calculus-III asked and I never came across such a concept.

A: $\bullet$ Let $f: U \subset \mathbb{R}^m \to \mathbb{R}^n$ and $g: U' \subset \mathbb{R}^m \to \mathbb{R}^n$ be $\mathcal{C}^k$. We say $f$ is a reparametrization of $g$ if there exists a $\mathcal{C}^k$-diffeomorphism $\varphi: U' \to U$ such that,
$$ (g \circ \varphi)(x^1,...,x^n) =f(y^1,...,y^m) $$
where we let $f = f(y^1,...,y^m)$ and $g = g(x^1,...,x^n)$ i.e just establishing the coordinates on these functions respectively.
$\bullet$ To reparametrize the disk, you notice that $(x,y)$ are traditionally take to be the identity variables of $\mathbb{R}^2$ i.e both $x,y: \mathbb{R}^2 \to \mathbb{R}^2$ defined by $x(a,b) = a$ and $y(a,b) = b$. Hence, to reparametrize the disk, you can use any diffeomorphism of $\mathbb{R}^2$. The most common is polar coordinates i.e,
$$x = R \cos \theta, y = R \sin \theta \Rightarrow D = \{(R, \theta): R<r\}$$
$\bullet$ The last thing I'm left with is to show you that this polar coordinate map is the reparametrization of some other map. Well,
$$ (f \circ \varphi^{-1})(R, \theta) = f(x,y)$$
where $R = \sqrt{x^2+y^2}$ and $\theta = \tan^{-1}(y/x)$ i.e,
$$\varphi(x,y) = \left(\sqrt{x^2+y^2}, \tan^{-1}(y/x)\right) = (R, \theta)$$

A: As an example.. Any contour line can be expressed either in the first or second system of parametrizations.
Say a circle through origin in first system  is
$$ r = a \, \cos\theta $$
With
$$ r \rightarrow  \sqrt {x^2+y^2} $$
$$ \theta \rightarrow \tan^{-1} \frac {y}{x} $$
it transforms to
$$ a \,x= (x^2+y^2) $$
in the second system.
Now, if you want to go back to first system, you re-parametrize by plugging in
$$ x= r \cos \theta, \, y= r \, \sin  \theta $$
to get back first original form
$$ r = a \, \cos\theta $$
Note that $ y= \cos x $ and $ r= \cos \theta $ are two entirely different curves.


text:
Q: I have integer variables, still Python says its a string Im programming in with python3 in Jupyter notebook.
I want to find the warmest temperature. The temperature are all numbers and in my code I also pushed the number to be an integer.
This is my code:
warm = -100

for i in range(4, len(climate)):
    temp = int(climate[i][3])
    if temp > warm:
        warm = climate[i][3]
print(warm)

I get this error message
TypeError: '>' not supported between instances of 'int' and 'str'

Somebody sees where the problem lies?


text:
Q: Set Root Mean Square Error (RMSE) as feature properties Using Landtrend library in Earth Engine, I can use a property that comes as default to calculate the square mean error (RMSE) and, then use this property to apply the current formula for this model:

(Math.round(ltData.rmse * 100) / 100).toString()

I just need to select 'rmse' property inside the 'LTRESULT'. First, I need to reduce to the level of each one of the fifth samples (samplesVegPrimaCinquenta).
LTresult.select("rmse").reduceRegion({
  reducer: ee.Reducer.first(),
  geometry: samplesVegPrimaCinquenta,
  scale: 30,
}).evaluate(function(ltData){ ...

I want to return this value (RMSE) as a property inside each feature in the FeatureCollection, but I can't do this.
var triplets = collection.map(
  function(image) {
  return image.reduceRegions({
    collection: samplesVegPrimaCinquenta,
    reducer: ee.Reducer.mean().setOutputs(image.bandNames()),
    scale: 30,
  }).map(
    function(feature) {
    return feature.set({
      'imageID': image.id(),
      'date': ee.Date(image.get('system:time_start')).format('Y-MM-dd'),
       // Calculate rmse and set as propertie inside each feature in featureCollection
      'Fit RMSE: ': (Math.round(ltData.rmse * 100) / 100).toString()
    })
  });
}).flatten();
print(triplets.limit(5),'triplets')

Here's the LINK code, the script is a little big so, this part it is in line 178-208


text:
Q: Android .aar dependencies aren't resolving in libraries My goal is to distribute an .aar file that can be used by other developers in their projects. The problem I find is when i try integrate my .aar into other project, is i need specify all of the dependencies in their build.gradle file that I have already included in my .aar build.gradle.
My question it if possible only include my library as a dependency and somehow the libraries that my library depends on will get included in the other project.
For example, my library defines the following dependencies in its build.gradle file:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'org.altbeacon:android-beacon-library:2.3.5'
    compile 'commons-codec:commons-codec:1.10'
}

I wrote a test app that uses my library and add like module in Android Studio interface
dependencies {
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.google.android.gms:play-services:7.5.0'
    compile project(':myLibrary')
}

However, this does not work. I get java.lang.VerifyErrors at runtime. What ends up working is to include this in the app's build.gradle file:
dependencies {
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.google.android.gms:play-services:7.5.0'

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'org.altbeacon:android-beacon-library:2.3.5'
    compile 'commons-codec:commons-codec:1.10'

    compile project(':myLibrary')
}

Why do I need to include dependencies in both the .aar and the final application? What am I not understanding about how dependencies work? Why isn't the final application able to grab the .aar's dependencies from maven or jCenter at build time?


text:
Q: How to calculate $\lim_{n\to+\infty}\frac{\Gamma(n)}{\Gamma\left(n-x\sqrt n\right)}\frac{1}{n^{x\sqrt n}}\,$ given that $x\in\mathbb R$? How to calculate $\displaystyle\lim_{n\to+\infty}\frac{\Gamma(n)}{\Gamma\left(n-x\sqrt n\right)}\frac{1}{n^{x\sqrt n}}\,$ given that $x\in\mathbb R$?
I know that it should be $e^{-\frac{x^2}{2}}$, but I don't know the steps.

A: Let us consider $$A_n=\frac{\Gamma(n)}{\Gamma\left(n-x\sqrt n\right)}\,\frac{1}{n^{x\sqrt n}}$$ Take logarithms $$\log(A_n)=\log\big(\Gamma(n)\big)-\log\big(\Gamma\left(n-x\sqrt n\right)\big)-x \sqrt n \log(n)$$ Now, use Stirling approximation $$\log\big(\Gamma(z)\big) \sim (z-\frac 12)\log( z) - z + \frac12\log(2\pi) $$ Applying it, we then have $$\log(A_n)\sim -x\sqrt{n} +\left(-x\sqrt{n} +n-\frac{1}{2}\right) \log (n)+\left(x\sqrt{n}
   -n+\frac{1}{2}\right) \log \left(n-x\sqrt{n} \right)$$ Now, rewrite $$\log \left(n-x\sqrt{n}\right)=\log(n)+\log(1-\frac x {\sqrt n})\sim \log(n)-\frac x {\sqrt n}-\frac{x^2}{2n}$$ Replacing in the previous expression, after simplifications, $$\log(A_n)\sim -\frac{x}{2 \sqrt{n}}-\left(\frac{1}{4 n}+\frac{1}{2}\right) x^2-\frac{x^3}{2
   \sqrt{n}}$$ So, for infinitely large values of $n$, $\log(A_n)\sim -\frac{x^2}2$


text:
Q: django newbie. Having trouble with ModelForm i'm trying to write a very simple django app. I cant get it to show my form inside my template.
<form ...>
{{form.as_p}}
</form>

it shows absolutely nothing. If I add a submit button, it only shows that.
Do I have to declare a form object that inherits from forms.Form ? Cant it be done with ModelForms?
[UPDATE]Solved! (apologize for wasting your time)
In my urls file I had:
(r'login/$',direct_to_template,   {'template':'register.html'}

Switched to:
(r'login/$','portal.views.register')

And yes, I feel terrible.
Background:
I have a Student model, and I have a registration page. When it is accessed, it should display a textfield asking for students name. If the student completes that field, then it saves it.
#models.py

class Student(models.Model):
   name = models.CharField(max_length =50)

#forms.py
class StudentForm (forms.ModelForm):
   class Meta:
       model = Student

So, here is my view:
def register(request):
          if request.method == 'POST':
                  form = StudentForm(request.POST)
                  if form.is_valid():
                          form.save()
                          return render_to_response('/thanks/')
          else:

                  student = Student()
                  form = StudentForm(instance =student)

          return render_to_response('register.html',{'form':form})

A: The problem is in your view. You will have no existing student object to retrieve from the database. The following code sample will help you implement an "create"  view.
As a side note, you might like using the direct_to_template generic view function to make your life a bit easier.
def add_student(request):
    if request.method == 'POST':
      form = StudentForm(request.POST)
      if form.is_valid():
        new_student = form.save()

        return HttpResponseRedirect('/back/to/somewhere/on/success/')
    else:
      form = StudentForm()

    return direct_to_template(request,
                              'register.html',
                              {'form':form})


text:
Q: How to write this JSON into Elasticsearch Java API? I have the following JSON query for Elasticsearch (which works fine) -
{
  "aggs": {
    "by_emotion": {
      "terms": {"field": "classifier_emotion"},
      "aggs": {
        "avg_probability": {
          "avg": {"field": "classifier_emotion_probability"}
        },
        "sum_probability": {
          "sum": {"field": "classifier_emotion_probability"}
        }
      }
    }
  }
}

I was trying to rewrite it using the Java API -
public AggregationBuilder<TermsBuilder> getClassifierAggregation(String classifierName) {
    String probailityField = classifierName + "_probability";
    return AggregationBuilders.terms("by_class")
        .subAggregation(
            AggregationBuilders.terms("classifier").field(classifierName)
        )
        .subAggregation(
            AggregationBuilders.avg("avg_probability").field(probailityField)
        )
        .subAggregation(
            AggregationBuilders.sum("sum_probability").field(probailityField)
        );
}

And then using it as -
SearchRequestBuilder request = elasticsearchClient.prepareSearch(index)
        .setSearchType(SearchType.QUERY_THEN_FETCH)
        .setFrom(0)
        .setSize(0)
        .addAggregation(getClassifierAggregation(classifierName));
SearchResponse response = request.execute().actionGet();

But I am getting the following exception -
org.elasticsearch.search.aggregations.AggregationExecutionException: could not find the appropriate value context to perform aggregation [by_class]

What am I doing wrong?

A: The method I mentioned was wrongly written. Here is the correct one -
public TermsBuilder getClassifierAggregation(String classifierName) {
    String probailityField = classifierName + "_probability";
    return AggregationBuilders.terms("by_class").field(classifierName)
        .subAggregation(
            AggregationBuilders.avg("avg_probability").field(probailityField)
        )
        .subAggregation(
            AggregationBuilders.sum("sum_probability").field(probailityField)
        );
}


text:
Q: How can I mark a chunk to extendable while adding a chunk to dbspace using onspaces command in Informix? I would like to know if I can mark a chunk to extendable while adding a chunk to a dbspace using the onspaces command itself. There is a column called is_extendable in the syschunks table in the sysmaster database. How do you enable it while adding a chunk to a dbspace?

A: Take a look at Automatic space management, it's only available since 11.70.
In particular, Marking a chunk as extendable or non-extendable indicates that you do not use onspaces but you use (for example) DB-Access to execute an administrative function:

To mark a chunk as extendable:

*

*Run the admin() or task() function with the modify chunk extendable argument, as follows:
  EXECUTE FUNCTION task("modify chunk extendable", "chunk number");

To mark a chunk as not extendable:

*

*Run the admin() or task() function with the modify chunk extendable off argument, as follows:
  EXECUTE FUNCTION task("modify chunk extendable off", "chunk number");


text:
Q: Could you extract energy from a rotational white hole? I understand it is possible to do it in a black hole, and its also possible to reach the event horizon of a black hole and increase its size.
But in a white hole, no wave (electromagnetic or gravitational) can reach the white hole's event horizon. So, if you apply the penrose process to a white hole, would you be affecting the speed of rotation near its event horizon?

A: A white hole is the time-reverse of a black hole.  So, a "white hole penrose process" necessarily is the time-reverse of the ordinary penrose process, which would be a particle absorbing a wave or particle coming from the event horizon, leaving the white hole "spun up".
If this sounds weird, it's because it is weird, in the same way that the advanced solutions of Maxwell's equations are weird.


text:
Q: Version mismatch for Searchd and Sphinxsearch I am using CakePHP behavior plugin with sphinx server
searchd error: client version is higher than daemon version (client is v.1.30, daemon is v.1.25)

A: Well you need to change the version of either the client or the server, so they match!
You could replease sphinxapi.php with the version from the package you installed of the server.
Or could find what version yuo have sphinxapi.php from and install the same server version.