text:
Q: Has anyone gotten Powerlevel9k Theming to look good on the *new* Windows Terminal/WSL? I've been trying to use WSL and the new Windows Terminal and wanted to make it look nice.
I'm somewhat new to zsh and shell theming though I've multiple pieces of documentation which seemed pretty straight forward and I'm still having issues making things look nice.
1.) Segment separating Arrows appear just a tad off
2.) Black backgrounds appear transparent.
When I read online, I only see examples of those who use zsh and powerlevel9k on Macs or linux, or some alternative terminal for Windows, but have yet to see an example for the New Windows Terminal. Has anyone tried this? Are there bugs with the Windows Terminal preventing themes from rendering correctly, or is it all on me? :D
Also if you've been able to fix any of the above issues for the new Windows Terminal, let me know of course!

A: Making powerline connections look nice is difficult but there are good alternatives that may look even better.
The easier way to find the best prompt look for your terminal is to switch from Powerlevel9k to Powerlevel10k (it's backward compatible but faster and has extra features), restart zsh and then run configuration wizard. If you are using Oh-My-Zsh, here are the commands to run:
git clone https://github.com/romkatv/powerlevel10k.git $ZSH_CUSTOM/themes/powerlevel10k
( cd $ZSH_CUSTOM/themes/powerlevel10k && git pull )
sed -e 's/powerlevel9k/powerlevel10k/g' -i ~/.zshrc
exec zsh

Once prompt appears, type p10k configure. If it doesn't look good, install the recommended font.


text:
Q: Path.equals behaves different on Windows and Linux I use the following code to compare two Paths in Java:
import java.nio.file.Paths;

public class PathTest {
   public static void main(String args[]) {
      String path1 = "path1\\file1.jpg";
      String path2 = "path1/file1.jpg";
      System.out.println(Paths.get(path1));
      System.out.println(Paths.get(path2));
      System.out.println(Paths.get(path1).equals(Paths.get(path2)));
   }
}

I do get the following output on my Windows machine:
path1\file1.jpg
path1\file1.jpg
true

And on linux:
path1\file1.jpg
path1/file1.jpg
false

What's going on here?

A: Path separator is different for Windows and Linux.
For Windows is \
For Linux is /
Safe way in java of building paths that work on both evironments is
Path filePath = Paths.get("path1", "path2");

In your case you use a String to form a Path. So in Windows
 String path2 = "path1/file1.jpg";
 Paths.get(path2)  -> results in "path1\file1.jpg"

It converts the separator / to a windows separator \
After that conversion both path1 and path2 are the same
Now when you run in Linux the following code
      String path1 = "path1\\file1.jpg"; -> this will not be ok for linux and also will not try to convert it to / as the first \ is an escape character
      String path2 = "path1/file1.jpg";  -> this will be ok for linux /
      System.out.println(Paths.get(path1));
      System.out.println(Paths.get(path2));
      System.out.println(Paths.get(path1).equals(Paths.get(path2)));

A: / is the path separator on Unix and Unix-like systems like Linux.
Modern Windows operating systems can use both \ and / as path separator.

A: If you develop for Windows and Linux you can generally use / as a path separator and don't bother using File.separator. For example Java on Windows resolves all these pathnames correctly without "\\" in a String, even UNC format:
var unc =  Path.of("//storage/media/camera");
// ==> \\storage\media\camera
var mdrive = Path.of("M:/camera");
// ==> M:\camera
var build = Path.of("build/classes");
// ==> build\classes
var a= Path.of("/Temp");
// ==> \Temp

redpajama_set_name: RedPajamaStackExchange


text:
Q: Whats the difference between these two SQL queries? Question: Select the item and per unit price for each item in the items_ordered table. Hint: Divide the price by the quantity.
1.
select item, sum(price)/sum(quantity)
from items_ordered
group by item;

2.
select item, price/quantity
from items_ordered
group by item;

Have a look at the resultis for flashlights. First one shows average price correctly but 2nd one only takes 28/4 and shows 7, ignoring the 4.5 few rows down. Someone please explain why this is the case.
The used table data from an external website.

A: SUM() is a group function - so that essentially says go get me all the price and quantities by item, and add them all up to return them in one row.
MySQL is quite forgiving when grouping things and will try to retrieve a rowset (which is why your second example returns something - albeit wrong).
Generally, if you are GROUPing columns (items in your exmaple), you need to return one row per column (item).
Try running the SQL below to see what that looks like.
SELECT item
     , SUM(price) AS sum_price
     , SUM(quantity) AS sum_quantity
     , COUNT(*) AS item_count
     , SUM(price) / SUM(quantity) AS avg_price_per_quant
  FROM items_ordered
 GROUP BY item
 ORDER BY item ASC

A: The first query returns the average price for that item, the second query returns the price for the first item it encounters. This only works in MySQL, the second query would  error in SQL Server as no aggegrate function is used. See this post for more details Why does MySQL allow "group by" queries WITHOUT aggregate functions?.


text:
Q: CURLOPT_PINNEDPUBLICKEY not effective I am using CURLOPT_PINNEDPUBLICKEY to pin the certificate. I also set CURLOPT_SSL_VERIFYPEER to 1 and CURLOPT_SSL_VERIFYHOST as mentioned in the docs.
I took the certificate file of the destination server and created sha256 base64 string as mentioned in curl docs for CURLOPT_PINNEDPUBLICKEY. Setting the valid sha string as "sha256//sddgdSDFSQWbGGRFr9rugEih7jghJwjj0xqcvbo=", or changing few characters in this string, and setting it as PINNEDPUBLICKEY results in the curl call to be successful. I was expecting invalid sha to result in error CURLE_SSL_PINNEDPUBKEYNOTMATCH. But it did not.
I saved the certificate from chrome browser to der file and pem file, and gave the path to the curl opt PINNEDPUBLICKEY. Still valid key and invalid key, both result in success.
Shouldnt an invalid string result in error? I am not sure if PINNEDPUBLICKEY  is working or not. May be I am missing something? Any inputs would be of great help.
Thanks

A: Solution for my issue: I needed to upgrade my curl library from 7.42 to 7.48. That fixed the issue and provided the proper error code that I was expecting for a wrong public key.


text:
Q: Is there any way to install an app which need .net 3.5 without .net 3.5? I want to install vmware viclient 5.5, it need .net framework 3.5 for running.
But I cannot install .net 3.5, because I used Windows Thin PC, if I want to get 3.5, I have to customize and reinstall it.(seems)
However, I can and already installed .net 4.5, but the viclient installer still prompt need .net 3.5.
I heard .net app can redirect runtime from old version to new version in a config file, but it need the app has been installed at first.
So, Is there any method can let me use viclient under Windows Thin PC?

A: OK, I resolved it:

*

*Install viclient on another computer

*Install .net 4.0 on Thin PC.

*Copy installed viclient to Thin PC and run it.

It works fine.


text:
Q: Python SQLite Database Result has unwanted brackets and quotation marks I am doing an assignment from Coursera Course "Using Databases with Python" and in one of the assignment I ran into this issue where the column of my database result returned has brackets and quotation marks around it. (It should return org as iupui.edu instead of my current result ['iupui.edu']
Please refer to my code below:
import sqlite3
import re

conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()

cur.execute('DROP TABLE IF EXISTS Counts')

cur.execute('''
CREATE TABLE Counts (org TEXT, count INTEGER)''')

fname = input('Enter file name: ')
if (len(fname) < 1): fname = 'mbox-short.txt'
fh = open(fname)
for line in fh:
    if not line.startswith('From: '): continue
    pieces = line.split()
    email = pieces[1]
    org = str(re.findall('@(\S+)', email))
    cur.execute('SELECT count FROM Counts WHERE org = ? ', (org,))
    row = cur.fetchone()
    if row is None:
        cur.execute('''INSERT INTO Counts (org, count)
                VALUES (?, 1)''', (org,))
    else:
        cur.execute('UPDATE Counts SET count = count + 1 WHERE org = ?',
                    (org,))

conn.commit()

# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'

for row in cur.execute(sqlstr):
    print(str(row[0]), row[1])

cur.close()

The mbox file is here: https://www.py4e.com/code3/mbox.txt
I have a feeling I shouldn't convert org to string class but I don't know what else to convert it to because
I would greatly appreciate your help as I've been trying to fix it for hours!

A: This has to do with how you're saving it:
org = str(re.findall('@(\S+)', email))

Here, you find all email orgs, right? but how do you process them? Instead of taking the first value, you cast it into a string. Here's the problem. findall returns a list, even if there is only one result. This is what you can do:
org = re.findall('@(\S+)', email)[0]

Now, org is still a string, but it no longer has brackets, as you are not casting a list to a string.


text:
Q: How to enable the root element in tree view I am working on kendo tree view. Its working well in Google Chrome. When testing that the root node is not in a selected state in IE and firefox. Can any one tell what were the reasons that may occur.

var data = [
        {
            id   : 1, text: "My Documents", expanded: true, spriteCssClass: "rootfolder",
            items: [
                                { id: 2, text: "w" },
                                { id: 3, text: "wq" },
                                { id: 4, text: "q" },
                                { id: 5, text: "qq" },
                                { id: 6, text: "qeq" },
                                { id: 7, text: "gd" }
                            ]

               }
    ];

var treeview = $("#treeview").kendoTreeView({
    checkboxes: {
        checkChildren: true
    },
    dataSource: data
}).data("kendoTreeView");

A: Solving the problem for last comment:
please suggest me instead of using $("#treeview").find(":checkbox").attr("checked", true); any other function that enable all the checked item default in all browsers
Add change event and change whatever you want in each function.
$("#treeview .k-item input[type=checkbox]:checked").closest(".k-item").each(function(){
    // change whatever you want, for example:
    $(this).css("color","green");
});

This is similar to what you're using, but I've checked it in Chrome, Firefox and IE and works fine. See this Fiddle (adapted from KendoUI demos).


text:
Q: VirtualHosts on Debian not working I have setup a local server with debian 6 squeeze. But I cannot get virtualhosts to work. I would like to setup multiple virtualhosts but I just started with one.
I disabled the default apache virtual host
a2dissite default

Setup the virtual host and directories
/etc/apache2/sites-available/test.local
<VirtualHost *:80>
 ServerAdmin webmaster@test.local
 ServerName test.local
 DocumentRoot /srv/www/test.local/public_html/
 ErrorLog /srv/www/test.local/logs/error.log
 CustomLog /srv/www/test.local/logs/access.log combined
</VirtualHost>

I enabled the site
a2ensite test.local

Restarted server
/etc/init.d/apache2 restart

Added it to /etc/hosts
192.168.1.60 test.local

When I browse to test.local, I just get a server not found error. I have also cleared all cookies. It only works, if I just go to 192.168.1.60.
Also my apache2.conf in /etc/apache2/apache2.conf has
Include ports.conf

ports.conf in /etc/apache2/ports.conf has
NameVirtualHost *:80
Listen 80

<IfModule mod_ssl.c>
 # If you add NameVirtualHost *:443 here, you will also have to change
 # the VirtualHost statement in /etc/apache2/sites-available/default-ssl
 # to <VirtualHost *:443>
 # Server Name Indication for SSL named virtual hosts is currently not
 # supported by MSIE on Windows XP.
 Listen 443
</IfModule>

<IfModule mod_gnutls.c>
 Listen 443
</IfModule>

Am I missing anything?

A: "Server not found" implies a name resolution issue, which is backed up by it working correctly when using just the IP.
Keep in mind that a modification to the hosts file will only work for the local system - so you'll need to be browsing from the system that's had the modification made.
If you're doing that, I'd suspect that your modification to the hosts file didn't stick - did you make the change as root, and were there any issues with saving the file?


text:
Q: Change URL when using ngx-translate I am trying to change the URL when someone clicks on a choosen language using ngx-translate. I guess I should do it by subscribing to language change events and then modifying the current url to reflect the chosen language, Since I am a newbie I am not sure if I need a service to do it, or may be another way to solve it.
I want to change from this:
https://amarello.cloud/es/
To this:
https://amarello.cloud/en/
,depending on the choosen language.
This is my 'header.component.ts'

import { Component, OnInit } from '@angular/core';
//For translate language
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

  menu: boolean = false;
  submenu: boolean = false;
  submin: boolean = false;

  constructor(private translate: TranslateService)
    { translate.addLangs(['es','en']);
      translate.setDefaultLang('es');
    }

  ngOnInit(): void {
  }

  open() {
    if (this.menu == false) {
      this.menu = true;
    } else {
      this.menu = false
    }

    if (this.submin == false) {
      this.submin = true;
    } else {
      this.submin = false
    }
  }

  openSub() {
    if (this.submenu == false) {
      this.submenu = true;
    } else {
      this.submenu = false
    }
  }

  useLanguage(language: string): void {
    this.translate.use(language);

    // this.translate.onLangChange().subscribe(trans => {

    // })

  }

}


text:
Q: Wallaby.js: Test framework [mocha@2.0.1] is not supported Hi I'm getting an error that mocha is not supported:
wallaby.js started
Failed to load configuration file:  Test framework [mocha@2.0.1] is not supported

my wallaby.js file:
var babel = require('babel');

var es6ToEs5Preprocessor = function(file) {
    return babel.transform(file.content, {sourceMap: true});
};

module.exports = {
    files: [
        "src/**/*.js"
    ],
    tests: [
        "test/**/*.test.js"
    ],
    preprocessors: {
        '**/*.js': es6ToEs5Preprocessor
    },
    env: {
        type: 'node',
        runner: 'node'
    },
    testFramework: 'mocha@2.0.1',
    debug: true
};

I have tried running without setting the framework though just getting a different error, mocha ins installed both locally and globally in the correct version
Thanks for any help


text:
Q: How can I make animation duration more accurate based on setInterval (js) I'm writing an animation looks like number is rising in limited time.
use setInternal and clearInterval to implement it.(I don't want to use Jquery)
the interval time is 1 milliSecond. And limit time is 1000 milli seconds. But it is slower than expected. It went almost 10000 milliseconds.What am I doing wrong?
Here's my code.

    <title>A numeric test</title>


text:
Q: Powershell form: how can I find controls based on name-property How can I list all the controls in my form where (name)-property begins with something spesific and then use it in a foreach?
I have multiple groupboxes under multiple tabpages where the name starts with gbs (Example: gbs1, gbs2, gbs3 ++). Now I want to disable all the groupeboxes that begins with gbs* at say a click of a botton without having to list all the groupboxes manually.
I've tried to look it up, but I can't find good documentation on it. I might be searching for the wrong words...
I'm guessing this is a start, and it's as far as I've come, but I'm not sure where to go from here or if I'm way off;
$list = @($MainForm.Controls.Find -like 'gbs*')

foreach ($item in $list){$item.enabled = $false} #Just a example of what I'm thinking

Purpose:
I am creating a .exe form that is going to automate active directory. The form contains a bunch of settings, and all of them is within these groupboxes. I'm going to have a 'edit-mode', so that when it's active - the groupboxes are enabled. When not, disabled.

Solution, thanks to help from @Clijsters :
    #Get all the tabpages
    $script:tabpages = $tabTasks.Controls | Where-Object { $_.Name -like "tp*" } | select Name, Controls
    $script:tabpages += $tabSettings.Controls | Where-Object { $_.Name -like "tp*" } | select Name, Controls

    #Get groupboxes in tabpages
    $script:groupboxes = [System.Object]$tabpages.Controls

    #Disable
    $groupboxes | Where-Object { $_.Name -like "gbs*" } | ForEach-Object { $_.Enabled = $true }

A: For finding Items in a list, Where-Object is your CmdLet of choice!
In your case something like
$list = $MainForm.Controls | Where-Object {$_.Name -like "gbs*"}

will work fine. You can store the result in a variable (like shown above) and use it in foreach or pipe the resulting list directly to ForEach-Object and process it there like below:
$MainForm.Controls | Where-Object {$_.Name -like "gbs*"} | ForEach-Object {Do Something}


text:
Q: Read information from a serial port in VB.net 2008 I'm at a brick wall!
I have a teperature PCB that reports the temp back via serial port.
I can open Hyper Terminal and receive all the data I want - so I know the unit is working... but I want to create a VB app so I can use the data received.
When I run the program I get this error:
System.TimeoutException: The operation has timed out.
   at System.IO.Ports.SerialStream.Read(Byte[] array, Int32 offset, Int32 count, Int32 timeout)
   at System.IO.Ports.SerialStream.Read(Byte[] array, Int32 offset, Int32 count)
   at System.IO.Ports.SerialPort.InternalRead(Char[] buffer, Int32 offset, Int32 count, Int32 timeout, Boolean countMultiByteCharsAsOne)
   at System.IO.Ports.SerialPort.ReadTo(String value)
   at System.IO.Ports.SerialPort.ReadLine()
   at Temperature.Form1.ReadFromCom() in C:\Documents and Settings\asamuel\Desktop\VB Project Sollutions\Temperature2\Temperature\Form1.vb:line 43

Can someone PLEASE help me! I'm going mad!
In hyper terminal the data comes through like this:
R V1.0 2002-01-06 20:37:37 C
1 0027.00
2 0027.00
3 0027.06
4 0027.18
1 0027.00
2 0027.00
3 0027.06
4 0027.18
1 0027.00
2 0027.06

My VB app code looks like this:
Imports System
Imports System.IO.Ports
Imports System.Threading

Public Class Form1

    Dim SerialPort1 As New SerialPort
    Dim readThread As Thread = New Thread(AddressOf ReadFromCom)
    Dim abortThread As Boolean

    Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If Button1.Text Is "Start Capture" Then
            Try
                abortThread = False
                SerialPort1.Open()
                readThread.Start()
                Button1.Text = "Stop Capture"
            Catch ex As Exception
                MsgBox("Another program is already using COM1." & vbCrLf & vbCrLf & _
                       "Please try again later", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "COM1 Not Available")
            End Try

        ElseIf Button1.Text Is "Stop Capture" Then
            abortThread = True
            Button1.Text = "Start Capture"
        End If
    End Sub

    Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With SerialPort1
            .PortName = "COM1"
            .BaudRate = 2400
            .Parity = Parity.None
            .DataBits = 8
            .StopBits = 1
            .ReadTimeout = 500
        End With
    End Sub

    Public Sub ReadFromCom()
        While abortThread = False
            Try
                Dim message As String = SerialPort1.ReadLine
                updateStatus("Received: " & message)
            Catch ex As TimeoutException
                updateStatus(ex.ToString)
            End Try
        End While
    End Sub

    Public Delegate Sub updateStatusDelegate(ByVal newStatus As String)
    Public Sub updateStatus(ByVal newStatus As String)
        If Me.InvokeRequired Then
            Dim upbd As New updateStatusDelegate(AddressOf updateStatus)
            Me.Invoke(upbd, New Object() {newStatus})
        Else
            TextBox1.Text = newStatus & vbCrLf & vbCrLf & TextBox1.Text
        End If
    End Sub
End Class

A: I needed to set searialport1.DTREnable to true!
It now works - that's a 2 month headache gone!

A: You might wanna drop your design in favor of using the DataReceived-Event() of the SerialPort-Class.
The DataReceived-Event will be fired if a certain amount of data has arrived (DataReceivedThreshold-Property, I think). But the event will be fired on another thread, so make sure that you use Invoke() if you try to change any controls.

A: Maybe THIS post can help you. You need to change the open statement to
...
open "COM1:" for Input as #1
Input #1, MyString
...


text:
Q: Play framework anorm DB field with Long and default null I'm trying to create a case class and object as below
case class Log (
  id: Pk[Long],
  module: String,
  reference: Option[Long],
  remarks: String,
  at:  Option[Date] )

object Log {

  val simple = {
    get[Pk[Long]]("id") ~
      get[String]("module") ~
      get[Option[Long]]("reference") ~
      get[String]("remarks") ~
      get[Option[Date]]("at") map {
        case id ~ module ~ reference ~ remarks ~ at => Log(id, module, reference, remarks, at)
      }
  }

How to I create an object of Log with null values for reference & at, and save it?
 val log: Log = new Log(NotAssigned, "user", null, "DFD", null)

Could you please guide on what I'm doing wrong? Also, at (db column) has a default value to now [using mysql]

A: Since you are using scalas option class use None instead of null:
val log: Log = new Log(NotAssigned, "user", None, "DFD", None)


text:
Q: IIS 7 many website in one ip address I use IIS 7 and when I create new website I wont one IP adress. But I have one. I want this http/ipadress/mywebsite
how to do it?
thanks

A: sorry if there's a better way to show this, but this was already answered here...
multiple sites on IIS7 under the same URL and port but on different directories


text:
Q: Counting Characters in python grok there is a task where i have to enter names and at the end print how many different characters and how many repeats.
'Your program should read in multiple lines of input, until a blank line is entered. Then it should print out how many unique characters were named, and how many were repeated.'
This was my result:
Character: The doctor
Character: Rose
Character: Rory
Character: Clara
Character: K-9
Character: The Master
Character: The Doctor
Character: Amy
Character:
You named 8 character(s)
You repeated 1 time(s)
This was my code:
count = []
country = input('Character: ')
a = country.count(country)
b = 0
c = 0
while country:
 count.append(country)
  country = input('Character: ')
  if a == country:
    b = b + 1
  else:
    c = c + 1
c = c - b
count.sort()
print('You named',c,'character(s)')
print('You repeated',a,'time(s)')

Supposed to say:
Character: The Doctor
Character: Rose
Character: Rory
Character: Clara
Character: K-9
Character: The Master
Character: The Doctor
Character: Amy
Character:
You named 7 character(s).
You repeated 1 time(s).

A: country = input('Character: ')

a = country.count(country)
b = 0
c = 0

while country:

 count.append(country)
 country = input('Character: ')
 if country in count:
   b = b + 1
 else:
   c = c + 1

count.sort()
print('You named',c,'character(s)')
print('You repeated',b,'time(s)')

Result:

Character: "AA"
  Character: "BB"
  Character: "CC"
  Character: "BB"
  Character: ""
  ('You named', 3, 'character(s)')
  ('You repeated', 1, 'time(s)')

Key changes:
 if country in count:     //changed

   c = c - b             //removed

print('You named',c,'character(s)')        //changed
print('You repeated',b,'time(s)')          //changed

A: You can gather up the characters and their occurrence counts into a dict. (There's also collections.Counter() which is geared for this, but for simplicity, but a regular dict will do.)
character_counts = {}

while True:
    character = input("Character: ")
    if not character:  # Empty line?
        break  # Quit the loop
    # Get the current count for the character, or 0 if not found, increment with one,
    # assign back to the dict.
    character_counts[character] = character_counts.get(character, 0) + 1

# Get a list of characters who occur more than once.
repeated_characters = [
    character
    for (character, count) in character_counts.items()
    if count > 1
]

print("You named {} character(s)".format(len(character_counts)))
print("You repeated {} time(s)".format(len(repeated_characters)))

A: The following snippet can be used:

n<-ncol(data)

m<-mean(rowMeans(data))

exp_val<-mean(apply(data,1,var))

v<-var(rowMeans(data))-mean(apply(data,1,var))/n

z<-n/(n+exp_val/v)

premiums<-Z*rowMeans(data)+(1-z)*m


text:
Q: CSS height 100% not working in ipad browser I have tried to set equal height columns for my feature collection. Its everything working good in desktop and mobile ipad screens . But when I check real device the height:100%not working. I have tried 'height:100vh` also.

Featured Collection

Men

New Collection

Shirts

8 Item

Bags

8 Item

SALE

FASHION SHOES

my webiste url Featured Collection
My ipad this what I am getting as per below image.

A: Sometimes height and min-height will not work on ipad and safari browsers. You can use display:flex follow flexbox group to align equal column height as below example.

.row.mycolspce div[class^="col-"] {
    display: flex;
    flex-wrap: wrap;
}
.feature-imgitem img {
  object-fit:cover;
}
.feature-imgitem,.banner_effect {
  display:flex;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>


text:
Q: Force one or more checkboxes to be selected I have three checkboxes that have their own error checking as to whether them being checked is valid but I would also like to enforce that at least one must be checked before continuing. I'm currently using IDataErrorInfo for the individual error checking and have tried using BindingGroups to check that at least one is checked with no success.
Here's the XAML,
<StackPanel Orientation="Horizontal" Margin="5,2">
    <Label Content="Checkboxes:" Width="100" HorizontalContentAlignment="Right"/>
    <CheckBox Content="One" Margin="0,5">
        <CheckBox.IsChecked>
            <Binding Path="One" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <DataErrorValidationRule />
                </Binding.ValidationRules>
                </Binding>
        </CheckBox.IsChecked>
    </CheckBox>
    <CheckBox Content="Two" Margin="5,5">
        <CheckBox.IsChecked>
            <Binding Path="Two" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <DataErrorValidationRule />
                </Binding.ValidationRules>
                </Binding>
            </CheckBox.IsChecked>
    </CheckBox>
    <CheckBox Content="Three" Margin="0,5">
        <CheckBox.IsChecked>
            <Binding Path="Tree" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <DataErrorValidationRule />
                </Binding.ValidationRules>
            </Binding>
        </CheckBox.IsChecked>
    </CheckBox>
</StackPanel>

And the error checking code behind
public string this[string property]
    {
        get {
            string result = null;
            switch (property) {
                case "One":
                {
                    if (One) {
                        if (CheckValid(One)) {
                            result = "Invalid Entry";
                        }
                    }
                }
                break;
                case "Two":
                    {
                        if (Two) {
                            if (CheckValid(Two)) {
                                result = "Invalid entry";
                            }
                        }
                    }
                break;
                case "Three":
                {
                    if (Three) {
                        if (CheckValid(Three)) {
                           result = "Invalid entry"
                        }
                    }
                }
                break;
            }
        return result;
    }

Any suggestion on how I can get the checkboxes to display an error if at least one is not selected?

A: To keep your existing code you can modify your data validation rule to check the state of all three checkboxes at the same time.
case "One":
  {
    if (One)
    {
      if (CheckValid(One))
      {
        result = "Invalid Entry";
      }
    }
    else if (!CheckThreeValid(One, Two, Three))
    {
      result = "Invalid entry";
    }
  }

private static bool CheckThreeValid(bool one, bool two, bool three)
{
  bool rc = true;
  if ( !one && !two && !three )
  {
    return false;
  }
  return rc;
}

and notify all three CheckBoxes when one value changes so when you deselect the last CheckBox and then select another checkbox the model clears the validation error.
public bool One
{
    get { return one; }
    set
    {
        one = value;
        RaisePropertyChanged("One");
        RaisePropertyChanged("Two");
        RaisePropertyChanged("Three");
    }
}


text:
Q: 2 connections to the same API in the same script. Do I need to ping both? I'm connecting to an API that allows for subscriptions, so I read them every time there is a new message in the .recv() method and I pass them to the main function. This API will disconnect any connection automatically if my program is idle for a while. To solve this, they ping my program every 10 seconds (I can adjust that) and I need to respond to them sending a test_message to tell the server that I'm not idle.
I have a script with the form:
async def subscription_api(queue):
    #subscribe to various channels in the websocket and pass the response to the main function
    async with websockets.connect(api) as ws:
        await ws.send(json.dumps(subscription_msg))
        response = json.loads(await ws.recv())
        await queue.put(response)

async def main():
    queue = asyncio.Queue()
    subscription = asyncio.create_task(subscription_api(queue))
    #I need this api connection to send messages to the server in this function
    async with websockets.connect(api) as ws:
        subscription = await queue.get()
        if subscription == 'ping':
            #if the message I receive from the server is a ping, send a test_message
        else:
            #do stuff

Here I have 2 questions:

*

*Even though I'm sending these test_messages back to the server, it still disconnects from time to time (once every 2-5 minutes aprox) raising an exception with the code 1006 (it doesn't specify the reason). Any idea why might that be, any common errors that might force this? I've been checking my code and haven't found a reason yet.

*As you can see I have 2 connections in my code, one for each function (async with websockets.connect(api) as ws:). Are these 2 connections sharing every property, or do they count as 2 individual connections to the API and hence I should send the test messages for each one individualy so both of them 'tell' the server that they are not idle? Or is it enough to just send it in one connection because, again, they share the same properties?

Thanks!


text:
Q: Node.js nested callbacks I have  a very basic question in node.js programming .
I am finding it interesting as I have started understanding it deeper.
I came across the following code :
Abc.do1('operation',2, function(err,res1)
{
   If(err) {
        Callback(err);
    }
    def.do2('operation2',function(l) {
   }
  }

My question is :
since def.do2 is written in the callback of abc.do1 ,
is it true that def.do2 will be executed after the 'operation' of abc.do1 is completed and the callback function gets called . If yes, is this a good programming practice , because we speak only asynchronous and non blocking code in node.js

A: Yes, you're correct. def.do2() is executed after abc.do1() is done.  However, this done on purpose to make sure that do1() is done before do2() can start.  If it's meant to be done in parallel, then do2() would have been outside of do1()'s callback.  This code is not exactly blocking.  after do1() is started, the code is still continuing on to execute everything below do1() functon (outside of do1's callback), just not do2() until do1() is done which is meant to be.

A: Yes you are absolutely correct and you have given a correct example of callback function.
The main browser process is a single threaded event loop. If you execute a long-running operation within a single-threaded event loop, the process "blocks". This is bad because the process stops processing other events while waiting for your operation to complete. 'alert' is one of the few blocking browser methods: if you call alert('test'), you can no longer click links, perform ajax queries, or interact with the browser UI.
In order to prevent blocking on long-running operations, the XMLHttpRequest provides an asynchronous interface. You pass it a callback to run after the operation is complete, and while it is processing it cedes control back to the main event loop instead of blocking.
There's no reason to use a callback unless you want to bind something to an event handler, or your operation is potentially blocking and therefore requires an asynchronous programming interface.
See this video
http://www.yuiblog.com/blog/2010/08/30/yui-theater-douglas-crockford-crockford-on-javascript-scene-6-loopage-52-min/


text:
Q: How to print the number of occurrences of consonants for each file separately with awk? I am trying to count the occurrences of consonants in multiple files,
but I want the number of occurrences to be separately calculated for each file.
I use
awk -v FS="" '{for ( i=1;i<=NF;i++){if($i ~/[bcdfghjklmnpqrtsvwxyzBCDEFGHJKLMNPQRTSVWXYZ]/) count_c++}} END {print FILENAME,count_c}' file1 file2

file1 looks like this:
bac Dfeg
k87 eH

tRe
rt up

file2 looks like this:
hi
rt2w
Prt

but it prints the occurrences of both files (output=file2 19). How could I change this so the output would be like:
file1 12
file2 7

A: With GNU awk for ENDFILE and IGNORECASE:
$ awk -v IGNORECASE=1 '
    { cnt += ( gsub(/[[:alpha:]]/,"&") - gsub(/[aeiou]/,"&") )}
    ENDFILE { print FILENAME, cnt+0; cnt=0 }
' file1 file2
file1 12
file2 7

or with any POSIX awk:
$ awk '
    { lc=tolower($0); cnt[FILENAME] += (gsub(/[[:alpha:]]/,"&",lc) - gsub(/[aeiou]/,"&",lc)) }
    END { for (i=1; i<ARGC; i++) print ARGV[i], cnt[ARGV[i]]+0 }
' file1 file2
file1 12
file2 7

If you only want to count the specific characters b, c, d, etc. instead of all alphabetic characters that aren't aeiou, then just change ( gsub(/[[:alpha:]]/,"&") - gsub(/[aeiou]/,"&") ) above to gsub(/[bcdfghjklmnpqrtsvwxyz]/,"&"))
Note that, unlike any approach that prints results in an FNR==1 clause, both of the above scripts will handle empty files correctly by printing the file name and 0 as the count.
Also note the cnt+0 in the first script - the +0 ensures that the value printed will be a numeric 0 rather than a null string if the first file is empty.
If the same file name can appear multiple times in the input then  add FNR==1{cnt[FILENAME]=0} to the start of the script if you want it output multiple times or add if (!seen[ARGV[i]]++) { ... } around the print in the END section if you only want it output once.
See https://unix.stackexchange.com/a/642372/133219 for an answer to the followup question of also counting vowels.

A: FWIW, and probably not much, I'd be tempted to do this without awk:
consonants=bcdfghjklmnpqrtsvwxyz
for f in file*; do
    printf "%s %d\n" "$f" "$(< "$f" tr A-Z a-z | tr -dc "$consonants"  | wc -c)"
done

Though that, of course, is quite ASCII-centric (and if you have GNU tr, it doesn't deal with multibyte characters anyway.)


text:
Q: A comparison theorem between crystalline cohomology and étale cohomology Suppose $X/\mathbb F_q$ is a smooth projective variety. Katz-Messing (eudml) shows that the characteristic polynomial of the Frobenius on $H^i_{et}(\overline{X},\mathbb Q_\ell)$ and $H^i_{crys}(X)$ are equal. Suppose now that $G \subset Aut(X)$ is a finite group. Can we identify the two cohomologies as $G$-representations (over an algebraically closed field $K$ containing both $\mathbb Q_\ell$ and $W(\mathbb F_q)$)?

A: This is OK when  $X$ is projective and smooth, at least when the Kunneth
components of the diagonal are algebraic. Let $k$ be the algebraic closure of
a finite field. Define $M_{1}$ and $M_{2}$ to be the categories of motives
over $k$ for homological equivalence (w.r.t. some Weil cohomology $H$) and
numerical equivalence respectively. They are rigid tensor categories, and we
have a tensor functor $M_{1}\rightarrow M_{2}$ (which preserves traces). An
automorphism $a$ of $X$ defines automorphisms $h_{1}^{r}X$ and $h_{2}^{r}X$,
and $Tr(a|H^{r}(X))=Tr(a|h_{1}^{r}X)=Tr(a|h_{2}^{r}X)$, which is a rational
number (not depending on $H$). When applied to the powers of $a$, this shows
that the characteristic polynomial of $a$ on $H^{r}(X)$ has rational
coefficients independent of $H$ (by the Newton identities).
The following argument may prove the general case (or may not). Let $M(k)$ be a (good) triangulated category of motives with $\mathbb{Q}{}$-coefficients, and let $f\colon M(k)\rightarrow P$ be the universal determinant functor of $M(k)$ (Breuning 2011, 3.1). The determinant of an automorphism $a$ of an object $X$ of $M(k)$ is an element of $\pi _{1}(P)$, which contains $\mathbb{Q}^{\times}$. The result of Bondarko/Olsson should show that, for all integers $n$, $\det(1-na)\in \mathbb{Q}^{\times}\subset\pi_{1}(P)$. If so, then it follows that there exists a polynomial in $\mathbb{Q}[T]$ that is equal to characteristic polynomial of $a$ on the $l$-adic realization of $X$ for all $l$ (including $l=p$) (see Proposition 3.1 of arXiv:1311.3166).


text:
Q: How to set timer to call a function every n minutes? I want to set up a timer in an Android application that will call a function after every 15/30/45 and n minutes when user login. But also it will stop timer when user log off. and timer begin from start if user login again. I want that option(15/30/45/n miutes) to be saved in database so that I can update list after sync.
Is Timer a good approach or I need to use alarm services? Or is there any system services required?
Is it possible to change previous doc/file in local phone database storage to new doc that is receiving through web server? is there any system services required to do so?

A: Use following code to call your function every 15/30/45
 final Handler handler = new Handler();
Timer    timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                @SuppressWarnings("unchecked")
                public void run() {
                   try {
                        "Your function call  "
                       }
                 catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, "Timer value");


text:
Q: How to auto login after Windows Update restart? After my Windows 7/Server 2008 R2 finished updating (windows update) during the night it restarts. I want it to auto login to my (admin) account after it restarts, but only auto login after a windows update.
How can I achieve this?

A: I've not done this myself, but there's a couple of registry edits you can do to enable auto login. The doc linked at the link is for XP, but it will apparently work for Server 2008.
Technet link


text:
Q: Browser will move style tags in head to body I wrote the style tag in head, but the browser will move it to the body and leave an empty string on top of it. And it will have an empty space in the browser in Mac.
<!DOCTYPE html>

123

That extra spacing is an empty string in body (highlighted in image),
not margin or padding, and it will do the same thing in Firefox and Safari.
How do I get rid of it?
My HTML file

A: After View Your Source Code I Get The Idea Why This Happen, actually there is one special character I found In you code.
 It's your code link: https://www.w3schools.com/code/tryit.asp?filename=FK89ZCXW8WDC
You can see the special character before the style tag start.


text:
Q: Invariants of rational functions? I have a simple question on rational functions, which appear in the context of rational elliptic surfaces. Let $R$ be a rational functions over say $\mathbb C$, such that $R=P/Q$ with $P$ and $Q$ polynomials. We can study functions $f$ with the property that
$$ R(f(x))=R(x),$$
i.e. $f$ leaves $R$ invariant.
As an example, consider
$$R(x)=\frac{64 \left(4 x^2-3\right)^3}{x^2-1}.$$
Then for
$$f(x)=\frac{2 x \left(x-\sqrt{x^2-1}\right)-3}{2 \sqrt{2 x \left(\sqrt{x^2-1}-x\right)+2}},$$
I find that $R(f(x)=R(x)$.
What is the nature of such functions? Can they be found explicitly for given $R$? I would be grateful for any comments.


text:
Q: How do electrons and photons interact? Two electrons, or an electron and a proton, interact with each other because of the Coulomb potential, which can also be seen in the Schrödinger equation (which is the equation that describes the motion for elementary particles).
But how do an electron and a photon interact? Why can a photon kick up an electron to a higher atomic orbital, or why is a photon emitted when an electron jumps down to a lower orbital? A photon do not have any charge, so the interaction cannot be caused by the Coulomb potential. So what is it that causes the interaction, and how does that affect the Schrödinger equation? (Or well, the relativistic version of the Schrödinger equation, since we're dealing with photons.)

A: The details depend on exactly what level of theory you want to work at, but the basic principle is that electrons feel forces (and accumulate energies from them) whenever there are electromagnetic fields. A photon is essentially a quantum of excitation in the electromagnetic field, so when one is present there will be fields and these will affect the electron.
Anything after that depends on how you want to work: you can do a QFT type of treatment, or you can also quantize the field more naively and then heuristically give the interaction energies in analogy with the classical theory, or you can also work in a semiclassical treatment where the electron is quantized but the EM field is some fixed classical wave.
It's important to note, though, that even though the Coulomb fields of charged particles to induce electromagnetic fields, not all electromagnetic fields can (or at least should) be understood as the result of Coulomb interactions. Indeed, electromagnetic waves are fundamentally different to the Coulomb attraction fields; they are what is known as "null fields". Most importantly, trying to ascribe an origin to the field is misguided: fields create forces at different points in space based on what the value of the field is there, regardless of how that field was actually generated.

One nice way to put the problem is if you have an atom (single-electron for simplicity) interacting with photons at some wavelength below X-rays. The electric field of a given mode of the radiation can be written, classically, in the form
$$
\mathbf{E}(\mathbf{r},t)=\mathbf{E}_0a(t)e^{i\mathbf{k}\cdot\mathbf{r}}+\text{c.c.},
$$
where $a(t)$ is the interesting dynamical variable, whose real and imaginary parts follow simple harmonic motion (and will therefore vary as $a(t)=e^{-i\omega t}$ classically) and $\text{c.c.}$ denotes the complex conjugate. The corresponding quantized version of this quantity is given by
$$
\hat{\mathbf{E}}(\mathbf{r},t)=\mathbf{E}_0\, \hat{a} \, e^{i\mathbf{k} \cdot \mathbf{r}} +\text{h.c.},
$$
where $\text{h.c.}$ denotes the hermitian conjugate, and now $\hat{\mathbf{E}}$ is a position-dependent operator (or operator-valued function of position, however you want to see it). The 'core' dynamical variable $a(t)$ has been replaced by the operator $\hat a$, which is the annihilation operator of the corresponding quantum harmonic oscillator.
So what's a photon in this formalism? By the term "photon", we refer to an elementary excitation of the field, which is the state with one quantum of energy, i.e. the first Fock state, $$|1\rangle=\hat a^\dagger|0\rangle.$$ You can of course have more than one photon (e.g. a higher number state like $|7\rangle$), or superpositions of different numbers of photons (like $\frac1{\sqrt{2}}(|0\rangle+|1\rangle)$), or more complicated states such as classical-like coherent states.

OK, so that's how the photons look. (Or at least, they can be modelled like this.) Now for the interaction.
It turns out that atoms are much smaller than most of the wavelengths they interact with. That is, if $R$ is the largest distance an electron might get from the nucleus - a few Bohr or so - and $k=2p/\lambda$ is the wavenumber of the radiation, then the only way not to have $kR\ll 1$ is to be using fairly hard X-rays, in the sub-nanometre regime.
This means that as far as any electron will be concerned, the electric field is constant, and the $e^{i\mathbf{k}\cdot \mathbf{r}}$ term can be completely neglected. Taking this a bit further, you can use the classical formula for the corresponding potential energy, the dipole coupling
$$
V_\text{int}=e\mathbf{r}\cdot\mathbf{E},
$$
and simply upgrade all the quantities in it to operators to get the corresponding coupling operator:
$$
\hat{V}_\text{int}=e\hat{\mathbf{r}}\cdot\left(\mathbf{E}_0\hat a+\mathbf{E}_0^\ast\hat a^\dagger\right).
$$
This gives you, finally, your hamiltonian. You need to combine it with whatever the atomic hamiltonian, $\hat H_0$ of the electron is (including its kinetic energy and its Coulomb interaction with the nucleus) as well as the energy contained in the field, which is given by the good old harmonic oscillator formula. That means that the total energy, and the total hamiltonian, is
$$
\hat H
=\hat H_0
+e\hat{\mathbf{r}}\cdot\left(\mathbf{E}_0\hat a+\mathbf{E}_0^\ast\hat a^\dagger\right)
+\hbar\omega(\hat a^\dagger\hat a+\tfrac12).
$$
Note that the hatted position $\hat{\mathbf{r}}$, is of course the electron's position, which is now an operator. The corresponding Schrödinger equation is $i\hbar\tfrac{d}{dt}|\Psi\rangle=\hat H|\Psi\rangle$, and you must be careful to note that the state $|\Psi\rangle$ is now the combined state of both the atom and the field, which includes such superpositions as
$$
|\Psi\rangle=\frac1{\sqrt{2}}\left(
|\text{ground}\rangle|1\rangle+|\text{excited}\rangle|0\rangle
\right).
$$

Finally, then, what does one mean, for example, by a phrase such as "the atom was excited by absorbing a photon"? Suppose you start off with your field in the one-photon state $|1\rangle$ and the atom in the ground state $|g\rangle$. This is no longer an eigenstate of the system, because the coupling does not respect it:
$$
\hat V_\text{int}|g\rangle|1\rangle=e(\mathbf{E}_0\cdot \hat{\mathbf{r}})|g\rangle|0\rangle.
$$
Therefore, the state of your system must evolve. What will it evolve into? To a first approximation, you can take the time-evolution operator to first order,
$$\hat U(t)=e^{-i\hat H t}\approx1-i\hat H t;$$
this means, for example, that you will have transitions to any excited state $|e\rangle$ with amplitude
$$
\langle e|\langle 0|\hat V_\text{int}|g\rangle|1\rangle=e\mathbf{E}_0\cdot \langle e|\hat{\mathbf{r}}|g\rangle\langle e|0\rangle,
$$
which will tend to be nonzero.


text:
Q: geodjango error importing LayerMapping Setup:
Windows 10

Python 2.7

Django 1.11

Standalone GDAL install gdal-202-1911-core.msi from gisinternals

QGIS version 3

PostgreSQL 9.5 with Postgis 2.3

ERROR
from django.contrib.gis.utils import LayerMapping
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ImportError: cannot import name LayerMapping

I can open up the layermapping.py, the file is there. There needs to be something wrong with my setup here. what should I be doing to correctly import LayerMapping, why is this happening

A: Your geos/GDAL installation is probably broken.  Follow the instructions in this answer for properly installing geodjango on windows.


text:
Q: \tl_gput_right:Nx with argument containing \par causing error after a list I accidentally ran into this issue and don't understand why this happens. Consider the following code:
\documentclass{article}

\begin{document}

%% OK
Text
\ExplSyntaxOn
\tl_gput_right:Nx \l_tmpa_tl { \par }
\ExplSyntaxOff

%% Error
\begin{itemize}
    \item text.
\end{itemize}
\ExplSyntaxOn
\tl_gput_right:Nx \l_tmpa_tl { \par }
\ExplSyntaxOff

\end{document}

I'm simply putting something (containing \par) in an irrelevant macro, but why does it produce an error when following a list?
To be specific, the error is
TeX capacity exceeded, sorry [input stack size=10000].
\@restorepar ->\def \par
                         {\@par }
l.16 \tl_gput_right:Nx \l_tmpa_tl { \par }

A: after a list (or section headigs) \par is not the tex primive but a macro that is used to set up the paragraph shape after the first paragraph.
It is not safe to use in an \edef or x argument expansion.


text:
Q: ¿Cómo saber la cantidad de filas que tienen el checkbox habilitado en un JTable? Estoy haciendo un programa para invitar a personas a eventos.

La tabla de la izquierda, están todos los invitados de mi base de datos, yo selecciono los que deseo invitar al evento.
La tabla de la derecha muestra todos los eventos de mi base de datos, solo debo seleccionar 1 solo.
Luego, al hacer clic en el botón Enviar Invitación, debo tener una forma de saber el ID de todos los invitados seleccionados en la primera tabla, y el ID del evento seleccionado en la segunda tabla para luego, guardar todo eso en mi base de datos y mostrar la invitación creada en la tabla inferior.
Código:
JButton btnEnviar = new JButton("Enviar Invitaci\u00F3n =>");
        btnEnviar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                // Tabla de Invitados
                tableInvitados.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent a) {
                        // Obtener la fila seleccionada
                        for (int i = 0; i < tableInvitados.getRowCount(); i++) {
                            Boolean checked = Boolean.valueOf(tableInvitados.getValueAt(i, 4).toString());
                            int fila = tableInvitados.rowAtPoint(a.getPoint());

                            if (checked) {
                                ArrayList<Integer> selection = new ArrayList<Integer>();
                                selection.add(fila);
                                System.out.println(fila);
                            }
                        }
                    }
                });

                // Tabla de Eventos
                tableEventos.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent arg0) {
                        int fila = tableEventos.rowAtPoint(arg0.getPoint());
                    }
                });

            }
        });

No entiendo realmente cómo hacer todo esto.

*

*¿Cómo puedo guardar todos los ID de las filas que tengan el checkbox true?, con este ID, mas adelante podré enviar eso a la base de datos.

*¿Cómo hago lo mismo para la tabla Eventos?, saber el ID del evento seleccionado?.

¿Alguna idea?.

A: Primero, borra los dos listener que no te sirven para nada y seguro que tendrás un lio de código que cada vez que se pincha la tabla te cargan ids y por eso se te repiten.
Para lo que pides lo que tienes que hacer es lo que te puse en los comentarios:
Creas un método para leer las filas con invitados:
private List<Integer> leerIDsInvitados(){
    List<Integer> invitados = new ArrayList<>();
    TableModel model = table.getModel();

    for(int i = 0; i < table.getRowCount(); i++){
        //Si la columna 4 está true añadimos el ID
        if((Boolean)model.getValueAt(i, 4) == true)
            invitados.add((Integer)model.getValueAt(i, 0));
    }

    //Esta fila es sólo para que veas que funciona
    System.out.println(invitados);

    return invitados;
}

En tu botón "Enviar invitación" pones que lance este método, recoges la lista con los ids y ya cargas en tu BD lo que necesites.
JButton btnEnviar = new JButton("Enviar Invitaci\u00F3n =>");
btnEnviar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        List<Integer> invitados = leerIDsInvitados();

        //Añades el código para leer el valor del combobox del evento
        //Que ya has tenido que hacerlo antes con el perfil de usuario
        //Y cargas tu BD o lo que tengas que hacer
    }
});


text:
Q: Как вернуть определенный ответ при переборе массива? const errors = [
 {id: 'BAD_REQUEST'},
 {id: 'NOT_FOUND'}
];

const error = 'OTHER';

const result = errors.find((item) => {
  if (item.id === error) {
    return {status: 'error', message: item.id}
  } else {
    return {status: 'ok', message: 'Good'}
  }
});

Возвращает текущий json из массива.
Я пытался так же через map, но он возвращает массив с undefined [undefined, undefined, {...}], forEach просто undefined возвращает.

A: Так думаю хотели?

const errors = [
 {id: 'BAD_REQUEST'},
 {id: 'NOT_FOUND'}
];

let error = 'OTHER';

let result = errors.reduce((acc, item) => item.id === error? ({status: 'error', message: item.id}): acc,
  {status: 'ok', message: 'Good'});

console.log(result);

error = 'NOT_FOUND';

result = errors.reduce((acc, item) => item.id === error? ({status: 'error', message: item.id}): acc,
  {status: 'ok', message: 'Good'});

console.log(result);

Дело в том что методы find filter. Возращяют элементы из массива удовлетворяющие условию поиска. А вам пригодится метод reduce который вернет результат acc после пересмотра всех значений. Следовательно вам нужно пробежаться по массиву и протащить результат через все элементы.

A:

let errors = [
 {'BAD_REQUEST': 'message 1'},
 {'NOT_FOUND': 'message 2'}
];

let error = 'NOT_FOUND';
let index = errors.findIndex(el => el[error]);
console.log((index !== -1) ? errors[index][error] : 'Good');

//--------------------------------------------------
error = 'OTHER';
index = errors.findIndex(el => el[error]);
console.log((index !== -1) ? errors[index][error] : 'Good');


text:
Q: Add animation to UIImageView I am trying to animate an imageView with this CAAnimation so I added the following extension to UIImageView:
extension UIImageView {

var ovalPathSmall: UIBezierPath {
    return UIBezierPath(ovalInRect: CGRect(x: 50.0, y: 50.0, width: 0.0, height: 0.0))
}

var ovalPathLarge: UIBezierPath {
    return UIBezierPath(ovalInRect: CGRect(x: 2.5, y: 17.5, width: 95.0, height: 95.0))
}

var ovalPathSquishVertical: UIBezierPath {
    return UIBezierPath(ovalInRect: CGRect(x: 2.5, y: 20.0, width: 95.0, height: 90.0))
}

var ovalPathSquishHorizontal: UIBezierPath {
    return UIBezierPath(ovalInRect: CGRect(x: 5.0, y: 20.0, width: 90.0, height: 90.0))
}

func wobble() {
    let animationDuration: CFTimeInterval = 0.3
    // 1
    var wobbleAnimation1: CABasicAnimation = CABasicAnimation(keyPath: "path")
    wobbleAnimation1.fromValue = ovalPathLarge.CGPath
    wobbleAnimation1.toValue = ovalPathSquishVertical.CGPath
    wobbleAnimation1.beginTime = 0.0
    wobbleAnimation1.duration = animationDuration

    // 2
    var wobbleAnimation2: CABasicAnimation = CABasicAnimation(keyPath: "path")
    wobbleAnimation2.fromValue = ovalPathSquishVertical.CGPath
    wobbleAnimation2.toValue = ovalPathSquishHorizontal.CGPath
    wobbleAnimation2.beginTime = wobbleAnimation1.beginTime + wobbleAnimation1.duration
    wobbleAnimation2.duration = animationDuration

    // 3
    var wobbleAnimation3: CABasicAnimation = CABasicAnimation(keyPath: "path")
    wobbleAnimation3.fromValue = ovalPathSquishHorizontal.CGPath
    wobbleAnimation3.toValue = ovalPathSquishVertical.CGPath
    wobbleAnimation3.beginTime = wobbleAnimation2.beginTime + wobbleAnimation2.duration
    wobbleAnimation3.duration = animationDuration

    // 4
    var wobbleAnimation4: CABasicAnimation = CABasicAnimation(keyPath: "path")
    wobbleAnimation4.fromValue = ovalPathSquishVertical.CGPath
    wobbleAnimation4.toValue = ovalPathLarge.CGPath
    wobbleAnimation4.beginTime = wobbleAnimation3.beginTime + wobbleAnimation3.duration
    wobbleAnimation4.duration = animationDuration

    // 5
    var wobbleAnimationGroup: CAAnimationGroup = CAAnimationGroup()
    wobbleAnimationGroup.animations = [wobbleAnimation1, wobbleAnimation2, wobbleAnimation3,
        wobbleAnimation4]
    wobbleAnimationGroup.duration = wobbleAnimation4.beginTime + wobbleAnimation4.duration
    wobbleAnimationGroup.repeatCount = 2
    self.layer.addAnimation(wobbleAnimationGroup, forKey: nil)

}

then this to my viewDiLoad:
     NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: "x",
        userInfo: nil, repeats: false)

func x() {
    questionIcon.wobble()
}

questionIcon is an outlet to the image I want to animate, but it doesn't move! What is wrong with the code? thanks

A: It isn't at all clear what you are trying to do; your code as it stands is nonsense. You are making animation objects like this:
CABasicAnimation(keyPath: "path")

But a UIImageView does not have a path property so you are not animating anything. The whole notion that a UIImageView might have an animatable path property is just something you made up in your head. You don't get to do that...
What you are allowed to do with a UIImageView is prepare a sequence of images (which you can create in code) and hand them to the image view to be played in sequence (as its animationImages) like the frames of a cartoon. Perhaps that is the direction you should be taking here.


text:
Q: Make Asset Pipeline work with Chrome DevTools Autosave Chrome DevTools Autosave doesn't work with Rails Asset Pipeline. The culprit of the problem is in the assets URLs — I cannot decipher the actual file path by its URL. For example, /assets/application.css may refer to either  app/assets/stylesheets/application.css, lib/assets/stylesheets/application.css,
or vendor/assets/stylesheets/application.css.
I wonder, how do I change assets URL to one of the following:

*

*/app/assets/stylesheets/application.css (matches exactly actual file path, perfect solution)

*/assets/application.css?source_url=app/assets/stylesheets/application.css (introduces source_url query parameter)

I would appreciate any help writing Rails plugin for that.

Update: I filled an issue to sprockets.

A: I'll try to get the ball rolling, but I'd have to do a lot more to verify or provide a better answer, so I'll mark this answer community wiki.  That way others can answer below and or edit this post.
I've had to set up asset pipelining for Sinatra, and generally speaking, in the latest versions of Sprockets (which is used to provide the asset pipelining in Rails) the Sprockets::Asset class has methods to obtain the path and logical path.
I believe Rails uses the asset_path helper to generate the public facing url from the Sprockets class.  This in turn appears to use the AssetPaths#compute_public_path instance method.  A good first step would be to modify these parts of the code to add a source_url parameter based on your parsing of the source.pathname.  This is assuming that source is an instance of Sprockets::Asset in some form or another.

A: I'm not quite sure how you expect the source to come from but it's already provided by ActionView::Helpers::AssetTagHelper
http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html
image_tag("rails.png")
# => <img alt="Rails" src="http://assets.example.com/images/rails.png?1230601161" />

stylesheet_link_tag("application")
# => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />


text:
Q: how do i select a variable from the eclipse variables view I'm developsing a debugger plugin in eclipse; i'm trying to write unit tests to grep vars from the variables view and test thier values.
so far I was able to retrieve the variables view object as an IViewPart;
I've extracted the selection provider related to the variables view, by doing this:
ISelectionProvider selProvider = viewPart.getSite().getSelectionProvider();

now i would like to set a selection on the first element in the variables view
how do i get the elements list, or select any of the elements?
Thanks in advance,
Anat


text:
Q: pyspark sum group by month and date using start and end date I have a dataframe of contracts: a start period, end period, monthly price. I am trying to get each month's total revenue.
Current data frame:
id      start_period   end_period     montly_price
1       2019-01-01     2019-03-01     30
2       2019-01-01     2019-06-01     20
3       2019-07-01     2020-08-01     10
4       2019-07-01     2020-08-01     10

Expected output:
period          revenue_per_month_all_ids
2019-01         50
2019-02         50
2019-04         20
2019-05         20
2019-06         0
2019-07         20

A: Assuming you do not have contracts whose start_period and end_period have a different month (if this is the case, how do you want to proceed ? Could you edit your question or comment this post ?)

import pyspark.sql.functions as psf

df.withColumn("month",psf.month('start_period'))
  .groupBy("period")
  .agg(psf.sum("monthly_price").alias("revenue_per_month_all_ids"))


text:
Q: AltBeacon library won't detect iBeacon I am trying to detect an iBeacon with AltBeacon library but it won't work.
iBeacon layout is registered:
BeaconManager.getInstanceForApplication(applicationContext).beaconParsers.add(BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"))

Ranging code
val beaconManager: BeaconManager = BeaconManager.getInstanceForApplication(App.appContext)
beaconManager.addRangeNotifier { beacons, region ->
    Log.d("BeaconScanner", "Beacons detected: ${beacons.size}")
}

// Start ranging my beacon
val id = "test"
val uuid = Identifier.parse("30168DC2-8CA6-4283-8169-B309262C4561")
val major = Identifier.parse("12345")
val minor = Identifier.parse("54321")
val region = Region(id, uuid, major, minor)
Log.d("BeaconScanner", "Started ranging $region")
beaconManager.startRangingBeacons(region)

The beacon seems to be detected, but the library thinks the Regions does not match
Beacon packet detected for: id1: 30168dc2-8ca6-4283-8169-b309262c4561 id2: 12345 id3: 54321 with rssi -42
2022-01-24 16:31:43.578 14239-14276/com.mhcin.beacontest D/ScanHelper: beacon detected : id1: 30168dc2-8ca6-4283-8169-b309262c4561 id2: 12345 id3: 54321
2022-01-24 16:31:43.578 14239-14275/com.mhcin.beacontest D/ScanHelper: Beacon packet detected for: id1: 30168dc2-8ca6-4283-8169-b309262c4561 id2: 12345 id3: 54321 with rssi -42
2022-01-24 16:31:43.578 14239-14275/com.mhcin.beacontest D/ScanHelper: beacon detected : id1: 30168dc2-8ca6-4283-8169-b309262c4561 id2: 12345 id3: 54321
2022-01-24 16:31:43.579 14239-14275/com.mhcin.beacontest D/ScanHelper: looking for ranging region matches for this beacon
2022-01-24 16:31:43.579 14239-14275/com.mhcin.beacontest D/ScanHelper: This region (id1: 80ddda3d-66b7-4e35-bf6a-8a647f43126c id2: 12345 id3: 54321) does not match beacon: id1: 30168dc2-8ca6-4283-8169-b309262c4561 id2: 12345 id3: 54321
2022-01-24 16:31:43.579 14239-14276/com.mhcin.beacontest D/ScanHelper: looking for ranging region matches for this beacon
2022-01-24 16:31:43.580 14239-14276/com.mhcin.beacontest D/ScanHelper: This region (id1: 80ddda3d-66b7-4e35-bf6a-8a647f43126c id2: 12345 id3: 54321) does not match beacon: id1: 30168dc2-8ca6-4283-8169-b309262c4561 id2: 12345 id3: 54321
2022-01-24 16:31:43.597 14239-14239/com.mhcin.beacontest D/CycledLeScannerForLollipop: got record
2022-01-24 16:31:43.598 14239-14273/com.mhcin.beacontest D/BeaconParser: Processing pdu type FF: 1eff060001092002784495beaac2372a367ef2729772d9728b120dcf6284c200000000000000000000000000000000000000000000000000000000000000 with startIndex: 2, endIndex: 30
2022-01-24 16:31:43.599 14239-14273/com.mhcin.beacontest D/BeaconParser: This is not a matching Beacon advertisement. (Was expecting be ac.  The bytes I see are: 1eff060001092002784495beaac2372a367ef2729772d9728b120dcf6284c200000000000000000000000000000000000000000000000000000000000000
2022-01-24 16:31:43.599 14239-14273/com.mhcin.beacontest D/BeaconParser: Processing pdu type FF: 1eff060001092002784495beaac2372a367ef2729772d9728b120dcf6284c200000000000000000000000000000000000000000000000000000000000000 with startIndex: 2, endIndex: 30
2022-01-24 16:31:43.599 14239-14273/com.mhcin.beacontest D/BeaconParser: This is not a matching Beacon advertisement. (Was expecting 02 15.  The bytes I see are: 1eff060001092002784495beaac2372a367ef2729772d9728b120dcf6284c200000000000000000000000000000000000000000000000000000000000000
2022-01-24 16:31:43.607 14239-14239/com.mhcin.beacontest D/CycledLeScannerForLollipop: got record
2022-01-24 16:31:43.607 14239-14278/com.mhcin.beacontest D/BeaconParser: Ignoring pdu type 01

Looking at the logs, it seems to me like AltBeacon is looking for the wrong Region? It clearly says it finds my iBeacon, but then it's looking to match a region with a completely different UUID even though my code clearly defines the correct UUID.
Whole LogCat dump here: https://pastebin.com/VHCkd6Kx

A: The problem is caused by the way beacon scanning Regions are persisted in the Android Beacon Library.  The problem generally only applies to monitoring regions, but when using the job scheduler for scanning (beaconManager.setEnableScheduledScanJobs(true)) it applies to ranged regions as well.
The solution is to do one of three things:

*

*Any time you change the identifiers you are ranging or monitoring, also change the unique ID of the region.

*Any time you change the identifiers you are rating or monitoring, also change the unique ID of the region, add code first to explicitly call stopMonitoring or stopRanging on the old region definition.

*Uninstall and reinstall your app to clear out persistence.

This is admittedly awkward.  You can see a detailed description of the problem in the library's open source repo along with proposals on making it better:
https://github.com/AltBeacon/android-beacon-library/issues/1075
Any ideas on making this better are appreciated.  Please comment on the above issue if you have thoughts.


text:
Q: How to delete rows in merge statement for specific date where target doesnt match source I have a merge statement that runs every day as new data is dumped into my table every day, here is a sample of my code:
MERGE SQL_Backup as Target
USING Temp as Source
ON target.code = source.code
WHEN MATCHED THEN update SET
target.saledate = source.saledate,
target.branchcode = source.branchcode

WHEN NOT MATCHED BY TARGET
THEN insert (
code, saledate
)
values (
source.code, source.saledate
)

    when not matched by source
      then delete;

however, that deletes my entire table, I am only wanting it to delete rows that were added today, any previous rows shouldnt be touched.
Here is an image of what both the source and target table look like:
Source/Target Table
I have a column labeled 'saledate' which contains the date of the data dumped in, and I have a unique column labeled 'code' which i used for the merge to detect duplicates.
Was wondering if theres a when not matched by source for saledate = today then delete or something?

A: A MERGE statement allows to use only target's columns and columns in the comparison terms scope in the "WHEN NOT MATCHED BY SOURCE" clause.
For example if you want to filter by the dates in the target table then MERGE fits your case, but if you want to filter by the Dates of the Source table then this does not fit MERGE
Here is a full example using simple table
DROP TABLE IF EXISTS S
DROP TABLE IF EXISTS T
GO
CREATE TABLE S(
    id int,
    DT DATE
)
DROP TABLE IF EXISTS T
GO
CREATE TABLE T(
    id int,
    DT DATE
)

INSERT T(id, DT) values (1,'2000-01-01'),(2,'2000-01-01'),(3,'2019-01-01')
INSERT S(id, DT) values (3,'2000-01-01'),(4,'2000-01-01'),(5,'2019-01-01')
GO

SELECT * FROM T
SELECT * FROM S
GO

-- the following query will raise an error
MERGE T as Target USING S as Source
    ON Target.id = Source.id

    WHEN MATCHED THEN
        UPDATE SET Target.id = Source.id + 1000
    WHEN NOT MATCHED BY TARGET THEN
        insert (id, DT) values (Source.id, Source.DT)
    -- Only target columns and columns in the clause scope are allowed in the 'WHEN NOT MATCHED BY SOURCE' clause of a MERGE statement.
    -- Using the bellow wil raise an error:
     WHEN NOT MATCHED BY SOURCE AND Source.DT > '2005-01-01' THEN DELETE;
GO

-- the following query will work well
MERGE T as Target USING S as Source
    ON Target.id = Source.id

    WHEN MATCHED THEN
        UPDATE SET Target.id = Source.id + 1000
    WHEN NOT MATCHED BY TARGET THEN
        insert (id, DT) values (Source.id, Source.DT)
    -- The bellow will work OK, since I use condition on the TARGET
    WHEN NOT MATCHED BY SOURCE AND TARGET.DT > '2005-01-01' THEN DELETE;
GO

SELECT * FROM T
SELECT * FROM S
GO

A: You can set the AND <clause_search_condition> after WHEN NOT MATCHED BY SOURCE.
Specifies the valid search condition, and then specifies that the rows matching rows in target_table are deleted.
For example, delete the rows where source.saledate=today.
MERGE SQL_Backup as Target
USING Temp as Source
ON target.code = source.code
WHEN MATCHED THEN update SET
target.saledate = source.saledate,
target.branchcode = source.branchcode

WHEN NOT MATCHED BY TARGET
THEN insert (
code, saledate
)
values (
source.code, source.saledate
)

WHEN NOT MATCHED BY SOURCE AND  source.saledate = CONVERT(varchar(100), GETDATE(), 3)
THEN DELETE;

Your saledate format is "dd/mm/yy", so we need to convert the default dateformat.
Hope this helps.


text:
Q: Ignore certain file types when forcing lower case URL's with .htaccess I'm using this code to force URL's to be lowercase only:
RewriteEngine On
RewriteBase /

# If there are caps, set HASCAPS to true and skip next rule
RewriteRule [A-Z] - [E=HASCAPS:TRUE,S=1]

# Skip this entire section if no uppercase letters in requested URL
RewriteRule ![A-Z] - [S=28]

# Replace single occurance of CAP with cap, then process next Rule.
RewriteRule ^([^A]*)A(.*)$ $1a$2
RewriteRule ^([^B]*)B(.*)$ $1b$2
RewriteRule ^([^C]*)C(.*)$ $1c$2
RewriteRule ^([^D]*)D(.*)$ $1d$2
RewriteRule ^([^E]*)E(.*)$ $1e$2
RewriteRule ^([^F]*)F(.*)$ $1f$2
RewriteRule ^([^G]*)G(.*)$ $1g$2
RewriteRule ^([^H]*)H(.*)$ $1h$2
RewriteRule ^([^I]*)I(.*)$ $1i$2
RewriteRule ^([^J]*)J(.*)$ $1j$2
RewriteRule ^([^K]*)K(.*)$ $1k$2
RewriteRule ^([^L]*)L(.*)$ $1l$2
RewriteRule ^([^M]*)M(.*)$ $1m$2
RewriteRule ^([^N]*)N(.*)$ $1n$2
RewriteRule ^([^O]*)O(.*)$ $1o$2
RewriteRule ^([^P]*)P(.*)$ $1p$2
RewriteRule ^([^Q]*)Q(.*)$ $1q$2
RewriteRule ^([^R]*)R(.*)$ $1r$2
RewriteRule ^([^S]*)S(.*)$ $1s$2
RewriteRule ^([^T]*)T(.*)$ $1t$2
RewriteRule ^([^U]*)U(.*)$ $1u$2
RewriteRule ^([^V]*)V(.*)$ $1v$2
RewriteRule ^([^W]*)W(.*)$ $1w$2
RewriteRule ^([^X]*)X(.*)$ $1x$2
RewriteRule ^([^Y]*)Y(.*)$ $1y$2
RewriteRule ^([^Z]*)Z(.*)$ $1z$2

# If there are any uppercase letters, restart at very first RewriteRule in file.
RewriteRule [A-Z] - [N]

RewriteCond %{ENV:HASCAPS} TRUE
RewriteRule ^/?(.*) /$1 [R=301,L]

This works, although isn't ideal. It's also rewriting the URL's for .js files (for example jqueryblockUI.js) which is causing the scripts to not be found.
How can I exclude certain file types like .js and .css from this?

A:
How can I exclude certain file types like .js and .css from this?

Preceede the whole process with a another rule, that checks if the requested path ends with one of the file extensions you want to exclude – some expression like \.(js|css)$ – and then uses the skip flag to jump over the next X rules, same as you do with the check for whether there still are upper-case letters.
And if you have access to the central server configuration (since you tagged the question .htaccess, I presume you have not – but still, consider this a nice-to-know perhaps), you could use a RewriteMap directive – that offers, among other things, some (very) basic string functions, one of them being tolower, that could do all that case conversion in one go.
For performance reasons I'd perhaps recommend, that in lack of that possibility, you perhaps use some server-side scripting language, if available, that you just direct all requests (apart from the JS/CSS files, as above) to, and that then calls it's own version of a tolowercase function to get that job done in one go as well, and then issues the redirect header.


text:
Q: Why is -pthread necessary for usage of std::thread in GCC and Clang? Why does specifying -std=c++11 when compiling a program that directly or indirectly uses std::thread not imply -pthread? It seems strange that the implementation detail of std::thread using pthreads under the hood is exposed to the programmer; if it's a matter of giving the user a choice of posix-compatible threading libraries, why not just default to pthreads and have some --threading-model=<your_favorite_posix_threads_library> argument to override it?

A: The -pthread option is not universally required to use std::thread - it's an implementation quirk of whatever platform you're building on.
Compiling:
#include <thread>
#include <iostream>

int main()
{
    std::thread t{[]()
        {
            std::cout << "Hello World\n";
        }};
    t.join();
    return 0;
}

with
clang -std=c++11 ThreadTest.cpp -lc++

On MacOSX, builds and runs, and if we do:
otool -L a.out
a.out:
    /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.0.0)

We can see that we've needed to link nothing extra to make this work - nor has it happened behind the scenes.  It seems to be very much a platform implementation detail that pthreads is a separate library.
Having a choice of threading libraries with the pthread interface is legacy baggage on *NIX systems, many of which started off without thread support, then went through a phase of user-space threads before having full kernel support.   I guess it's still there because nobody likes making breaking changes.


text:
Q: How to type app.get('/events', (req, res) in express with TypeScript I would like to know what is the type annotation for (req, res) => when using app.get in express.
app.get('/events', (req, res) => {
        // SSE Setup
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
        });
        res.write('\n');

        sseEvents(req, res);
    });

A: You will need to have @types/express (npm i -D @types/express) and then you can use
import { Request, Response } from 'express';
app.get('/events', (req: Request, res: Response) => {
  // your code
});


text:
Q: Semantic segmentation with amazon AWS and S3 instance This is probably a easy question but I have been stuck now for a time.
I want to train an FCN an Amazon AWS. For this I want to use the procedure used in this example ( https://github.com/awslabs/amazon-sagemaker-examples/blob/master/introduction_to_amazon_algorithms/semantic_segmentation_pascalvoc/semantic_segmentation_pascalvoc.ipynb ) with my own datase.
In contrast to that procedure I have my train and annotation images (as .png) saved in one S3 bucket with four folders (Training, TrainingAnnotation, Validation, ValidationAnnotaion).The files in the folder for Training and Annotation have the same name.
I trained my model with followong code:
%%time
import sagemaker
from sagemaker import get_execution_role

role = get_execution_role()
print(role)

bucket = sess.default_bucket()
prefix = 'semantic-segmentation'
print(bucket)

from sagemaker.amazon.amazon_estimator import get_image_uri
training_image = get_image_uri(sess.boto_region_name, 'semantic-segmentation', repo_version="latest")
print (training_image)

s3_output_location = 's3://{}/{}/output'.format(bucket, prefix)
print(s3_output_location)

# Create the sagemaker estimator object.
ss_model = sagemaker.estimator.Estimator(training_image,
                                         role,
                                         train_instance_count = 1,
                                         train_instance_type = 'ml.p2.xlarge',
                                         train_volume_size = 50,
                                         train_max_run = 360000,
                                         output_path = s3_output_location,
                                         base_job_name = 'ss-notebook-demo',
                                         sagemaker_session = sess)
num_training_samples=5400
# Setup hyperparameters
ss_model.set_hyperparameters(backbone='resnet-50',
                             algorithm='fcn',
                             use_pretrained_model='True',
                             crop_size=248, .
                             num_classes=4,
                             epochs=10,
                             learning_rate=0.0001,
                             optimizer='rmsprop', 'adam', 'rmsprop', 'nag', 'adagrad'.
                             lr_scheduler='poly', 'cosine' and 'step'.
                             mini_batch_size=16,
                             validation_mini_batch_size=16,
                             early_stopping=True,
                             early_stopping_patience=2,
                             early_stopping_min_epochs=10,
                             num_training_samples=num_training_samples)
# Create full bucket names

bucket1 = 'imagelabel1'
train_channel = 'Training'
validation_channel = 'Validation'
train_annotation_channel = 'TrainingAnnotation'
validation_annotation_channel =  'ValidataionAnnotation'

s3_train_data = 's3://{}/{}'.format(bucket1, train_channel)
s3_validation_data = 's3://{}/{}'.format(bucket1, validation_channel)
s3_train_annotation = 's3://{}/{}'.format(bucket1, train_annotation_channel)
s3_validation_annotation  = 's3://{}/{}'.format(bucket1, validation_annotation_channel)

distribution = 'FullyReplicated'
# Create sagemaker s3_input objects
train_data = sagemaker.session.s3_input(s3_train_data, distribution=distribution,
                                        content_type='image/png', s3_data_type='S3Prefix')
validation_data = sagemaker.session.s3_input(s3_validation_data, distribution=distribution,
                                        content_type='image/png', s3_data_type='S3Prefix')
train_annotation = sagemaker.session.s3_input(s3_train_annotation, distribution=distribution,
                                        content_type='image/png', s3_data_type='S3Prefix')
validation_annotation = sagemaker.session.s3_input(s3_validation_annotation, distribution=distribution,
                                        content_type='image/png', s3_data_type='S3Prefix')

data_channels = {'train': train_data,
                 'validation': validation_data,
                 'train_annotation': train_annotation,
                 'validation_annotation':validation_annotation}
s3://imagelabel1/Training
ss_model.fit(inputs=data_channels, logs=True)

The Errror Message is:
ValueError: Error for Training job ss-notebook-demo-2019-07-15-06-42-25-784: Failed Reason: ClientError: train channel is empty.
Does someone know what is wrong in this Code?
Thank you
Simon

A: it looks like your folder hierarchy doesn't use the correct names. According to the doc (https://docs.aws.amazon.com/sagemaker/latest/dg/semantic-segmentation.html#semantic-segmentation-inputoutput), it should look like:
s3://bucket_name
    |
    |- train
                 |
                 | - 0000.jpg
                 | - coffee.jpg
    |- validation
                 |
                 | - 00a0.jpg
                 | - bananna.jpg
    |- train_annotation
                 |
                 | - 0000.png
                 | - coffee.png
    |- validation_annotation
                 |
                 | - 00a0.png
                 | - bananna.png
    |- label_map
                 | - train_label_map.json
                 | - validation_label_map.json

Fixing these prefixes should solve your problem:
train_channel = 'Training'
validation_channel = 'Validation'
train_annotation_channel = 'TrainingAnnotation'
validation_annotation_channel =  'ValidataionAnnotation'


text:
Q: Group by two columns in Rcharts nPlot I try to group by two variables in nPlot. I would like to get interactive Legend for both of this variables so I can filter on both variables.
My code in R for single group variables looks as follows:
    require(devtools)
    install_github('rCharts', 'ramnathv')
    library(rCharts)
    r1<- nPlot(mpg ~ wt, group = 'cyl', data = mtcars, type="scatterChart")
    r1$chart(tooltipContent = "#! function(key, x, y, e,graph){
    return 'carb: ' + e.point.carb
    } !#")
    r1$chart(size = '#! function(d){return d.disp} !#')
    r1

I try to use something like this for 2 columns bu t it's not working:
    r2<- nPlot(mpg ~ wt, group = c('cyl','gear'), data = mtcars, type="scatterChart")
    r2$chart(tooltipContent = "#! function(key, x, y, e,graph){
    return 'carb: ' + e.point.carb
    } !#")
    r2$chart(size = '#! function(d){return d.disp} !#')
    r2

I also try adding but it doesn't give me the posiibility to filter on both variables at one time:
    r2$addControls("group", value = "gear", values = names(mtcars))

Is there a way to make such plot. Thanks.


text:
Q: XML sequence with JAX-WS Is there any way to make default WSDL being generated by JAX-WS (returned via ?wsdl) to use XML choice instead of any and sequence?

A: I assume you mean the XML schema in the <types/> part of the WSDL. The generation of this schema is not governed by JAX-WS, but by the JAXB specification. This is the specification for the data binding in JAX-WS.
But to actually answer your question: Yes, you can do that with an appropriate @XMLElements annotation in the class that represents your datatype. For example, take a web service interface like this:
@WebService
public interface Chooser {

    String chooseOne(Choice myChoice);

}

Then the contents of your XSD depend on the structure of the Choice class. You can force the generation of a choice element through something like this:
public class Choice {

    @XmlElements(value = { @XmlElement(type = First.class),
            @XmlElement(type = Second.class) })
    private Object myChoice;

}

Classes First and Second are possible elements in the choice. The schema generated from this code looks like this:
<xs:complexType name="choice">
  <xs:sequence>
    <xs:choice minOccurs="0">
      <xs:element name="myChoice" type="tns:first"></xs:element>
      <xs:element name="myChoice" type="tns:second"></xs:element>
    </xs:choice>
  </xs:sequence>
</xs:complexType>

This still wraps the choice in a sequence, but as there is only one element in the sequence, this doesn't really matter.


text:
Q: Parsing DateTime from fixed length String with optional leading zero I want to parse some Strings to Joda DateTime objects like that:
DateTimeFormatter dtf = DateTimeFormat.forPattern("MMM dd yyyy h:mma");
DateTime dt = dtf.parseDateTime(dateStr);

dateStr can be in one of the following formats:
"Apr  5 2017  8:11PM"
"Oct 20 2017 10:29PM"

Parsing fails with the first String because the given pattern expects to have a leading zero for the day (expects "05" and not " 5").
Is there a pattern which could parse both of this date Strings?


text:
Q: Using getInitialProps with HOC which also contains getInitialProps I wrapped a page with a withAuth HOC. in the same page, i also tried to call getInitialProps. if i sign in, the getInitialProps function doesn't run (though it shows that my withAuth HOC is working).
is there anyway i can make getInitialProps for the Contact Page to work and also use the withAuth HOC (which also has a getInitialProps function)?
Contact
import Layout from "../components/Layout";
import { withAuth } from "../services/withAuth";

class Contact extends React.Component {
  static async getInitialProps(ctx) {
    console.log("@contact authenticated ", ctx);
    return {};
  }
  render() {
    return (
      <Layout>

hey there

        abc@gmail.com
      </Layout>
    );
  }
}

export default withAuth(Contact);

withAuth HOC
import { ME } from "../graphql/queries";
import redirect from "../lib/redirect";

export const withAuth = C => {
  class AuthComponent extends React.Component {
    static async getInitialProps(ctx) {
      const response = await ctx.apolloClient.query({ query: ME });
      console.log("@withAuth ", response);
      if (!response || !response.data || !response.data.me) {
        redirect(ctx, "/");
        return {
          me: null
        };
      }

      return {
        me: response.data.me
      };
    }

    render() {
      return <C {...this.props} />;
    }
  }

  return AuthComponent;
};

A: Try calling C.getInitialProps() inside the getInitialProps of your HOC:
export const withAuth = C => {
  class AuthComponent extends React.Component {
    static async getInitialProps(ctx) {
      const response = await ctx.apolloClient.query({ query: ME });

      console.log("@withAuth ", response);

      if (!response || !response.data || !response.data.me) {
        redirect(ctx, "/");
        return {
          me: null
        };
      }

      // Get component's props
      let componentProps = {}
      if (C.getInitialProps) {
        componentProps = await C.getInitialProps(ctx);
      }

      return {
        me: response.data.me,
        ...componentProps
      };
    }

    render() {
      return <C {...this.props} />;
    }
  }

  return AuthComponent;
};

I hope this helps.


text:
Q: UIBezierPath simple rectangle I just want to draw a simple rectangle to a view using the following function:
- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    if (self.drawTextBouble) {
        [[UIColor blueColor] setFill];
        UIBezierPath *aPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(40, 0, 230, 120) cornerRadius:12.0];
        [aPath fill];
    }
}

The code above fills the view with plain black background, outside the rectangle is not transparent. How can I fix this?
Edit:
The solution below is working, but this is working also:
[self setOpaque:NO];

A: You drawing code is OK. If you want the custom drawn view to have transparent background, you just need to set
self.backgroundColor = [UIColor clearColor];

in view's - (id)initWithFrame:(CGRect)frame
Edit: Just a little note regarding calling [super drawRect:rect]. UIView docs says:

If you subclass UIView directly, your implementation of this method does not need to call super. However, if you are subclassing a different view class, you should call super at some point in your implementation.


text:
Q: Let $A=\{6,10,30\},B=\{3,5\}$ and $P(x,y)=$ $x$ is divisible by $y$. Are these statements true? Let $A=\{6,10,30\},B=\{3,5\}$ and $P(x,y)=$ $x$ is divisible by $y$
State whether it is true or false for the below statements.
1.For any odd integer $x$ in $A$, for any $y$ in $B$, $P(x,y)$

This statement is true, because it is a vacuous truth statement. Since it is of the form $∀ \ odd\ x  \ \exists \ y$, and there are no odd $x$ in $A$.

2.For some y in B, for any odd integer x in A,P(x,y)
y odd

This statement is is true as it is also a vacuous truth statement. It is of the form, $\exists y\forall odd\ x$. The existence of y 3, 5 and there are no odd x in A.

3.For any odd integer x in A, for some even integer y in B,P(x,y)

I am not too sure about this one... This statement is true because there are no odd integers in A.

4.For some even integer y in B, for an integer x in A,P(x,y)

This statement is false, because there are no even integers in B, and we can't use for some.

Check my answer thanks! Also, is there a better way to state the justification more concisely and precisely? Generally, I feel I am plain confused about All and Some statements for empty sets.

A: Your arguments are perfect.
As you stated, $\forall x:Q(x)\to P(x,y)$ becomes automatically true if $Q(x)$ is never true, and $\exists x:Q(x)\land P(x,y)$ becomes automatically false if $Q(x)$ is never true.


text:
Q: How to make ImageView using java in android? protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView img=new ImageView(this);
img.setImageResource(R.drawable.img);
img.setScaleType(ImageView.ScaleType(CENTER_CROP));
setContentView(img) }

I want to set the size of image view in Java and I could not find the syntax working.

A: Try code(edit as per your view names):
@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout picLL = new LinearLayout(this);
    picLL.layout(0, 0, 100, 100);
    picLL.setLayoutParams(new LayoutParams(100, 100));
    picLL.setOrientation(LinearLayout.HORIZONTAL);
    ImageView myImage = new ImageView(this);
    myImage.setImageResource(R.drawable.ic_launcher);
    picLL.addView(myImage);
    setContentView(picLL);
}

And set height or width:
myImageView..getLayoutParams().height = your_size_value;
myImageView..getLayoutParams().width = your_size_value;

A:  <ImageView
    android:id="@+id/imageView1"
    android:layout_margin="20dp"
    android:src="@drawable/stop"
    android:layout_width="50dp"
    android:layout_height="50dp"/>

change width and height attribute with your values.

A: //Linear layout setting here
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.bull);
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(imageView);
setContentView(linearLayout);


text:
Q: I need to change the colour of my CoreUI tooltip and also the width of it .reactJS All the details are displaying correctly. I want to change the background colour and the width of the tooltip.
css file code for the tooltip

> .discountTooltip {
  $tooltip-max-width: 250px;
  $tooltip-bg:white
}

reactJS file code for the tooltip.Here please let me know whether I can change those using the CSS file or in another way
 >   <CTooltip className="discountTooltip"
                                content={
                                  <>
                                    <CTable align="right" className="mb-0 mt-3 border-1" hover responsive bordered>
                                      <CTableHead color="dark">
                                        <CTableRow className="bannerItemsHeader">
                                          <CTableHeaderCell className="text-start">
                                            All Rules
                                          </CTableHeaderCell>
                                        </CTableRow>
                                      </CTableHead>

                                      <CTableBody>
                                        {item?.data?.map((rule, index) => (
                                          <CTableRow v-for="item in tableItems" key={index}>
                                            {rule?.discountType === 'FLAT_RATE' ? (
                                              <CTableDataCell className="text-center p-0">
                                                <CRow className="m-0 p-0 ">
                                                  <CCol className="p-0"></CCol>
                                                  {`${rule.trxStartAmount}-${rule.trxEndAmount} Rs ${props.rewardType === 'Discount'
                                                    ? rule.discountValue
                                                    : rule.bonusValue
                                                    }.00`}
                                                </CRow>
                                              </CTableDataCell>
                                            ) : (
                                              <CTableDataCell className="text-center p-0">
                                                <CRow className="m-0 p-0 ">
                                                  <CCol className="p-0"></CCol>
                                                  {`${rule.trxStartAmount}-${rule.trxEndAmount}  ${props.rewardType === 'Discount'
                                                    ? rule.discountValue
                                                    : rule.bonusValue
                                                    }% Max Rs ${props.rewardType === 'Discount'
                                                      ? rule.maxDiscountValue
                                                      : rule.maxBonusValue
                                                    }.00`}
                                                </CRow>
                                              </CTableDataCell>
                                            )}
                                          </CTableRow>
                                        ))}
                                      </CTableBody>
                                    </CTable>
                                  </>
                                }
                                placement="bottom"
                              >
                                <CCol>{item.type} </CCol>
                                {/* {item.discountType}
                                 */}
                              </CTooltip>


text:
Q: Using style defined in merged dictionary from another merged dictionary Below you can see how I am trying to segregate styles by merging dictionaries (I'm skipping namespaces for the sake of cleanliness)
App.xaml:
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Style/Colors.xaml" />
            <ResourceDictionary Source="Style/HeaderStyle.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Colors.xaml:
<SolidColorBrush x:Key="DarkTextForeground" Color="#7471b9"/>

HeaderStyle.xaml:
<Style x:Key="HeaderTextBlockStyle" TargetType="TextBlock">
    <Setter Property="Foreground" Value="{StaticResource DarkTextForeground}"/>
    <Setter Property="FontWeight" Value="Black"/>
</Style>

During compilation I get a following error:

Cannot find a Resource with the Name/Key DarkTextForeground

To make It work we have to merge Colors.xaml inside HeaderStyle.xaml like this:
<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="Colors.xaml"/>
</ResourceDictionary.MergedDictionaries>

<Style x:Key="HeaderTextBlockStyle" TargetType="TextBlock">
    <Setter Property="Foreground" Value="{StaticResource DarkTextForeground}"/>
    <Setter Property="FontWeight" Value="Black"/>
</Style>

Can anyone explain to me, why I have to reference Colors.xaml in HeaderStyle.xaml? Can't I just reference styles defined in different merged dictionary?I assume that Colors.xaml is loaded before HeaderStyle.xaml so it should be visible for dictionaries defined later.

A: This is a response to my question from Erick Fleck at msdn forums:

In your first example each file is parsed independently and then added to the merged dictionary so they don't know anything about each other...similarly, the XAML in a merged dictionary cannot reference names in the 'parent' ResourceDictionary.  In other words, you should think of a MergedDictionaries as a one-way reference.

It's the way It works I guess...


text:
Q: A basic doubt on axiom of foundation of Zermelo-Fraenkel set theory I have read in a book that the "axiom of foundation prevents anomalies such as a
set being an element of itself".
Now, axiom of foundation says that there exist an element in every set which is disjoint with the set.
Now if $S$ be a set then according to the above axiom $S=\{S\}$ can't be a set. But, $S=\{\{1\},S\}$ satisfies axiom of foundation and contains $S$.
So, is the statement mentioned in the book correct ?

A: Consider $A=S\setminus\{1\}=\{S\}$, which exists by the various comprehension schemata. Then $S\cap A=\{S\}$.
Therefore $A$ is a counterexample to the axiom of foundations.
Understanding the axiom of foundation as stating "there are no anomalies such as ..." is a very informal. It is as informal as saying that the axiom of infinity states "there exists an infinite set". This is an informal notion which captures the intuition behinds the axiom, but it doesn't really tells us what is the content of the axiom.
The axiom of foundation states that $\in$ is a well-founded relation. From this assertion it follows that anomalies like $x\in y\in z\in w\in u\in x$ cannot occur. But in fact it tells us more. It tells us that we can use $\in$ for recursive definitions, what is commonly known as Epsilon induction/recursion.
So while saying that the axiom of foundation prevents anomalies such as X is not incorrect, it is not well-defined either. What is an anomaly? Why is X is an anomaly? These notions are informal, and so is the term "such as". It is better to state the axiom in its correct form "$\in$ is a well-founded relation".

A: If $S\in S$ then $\{S\}$ will violate the axiom of foundation.

A: You seem to think that you can find a set $S$ such that $S=\{\{1\},S\}$.
But can you really? Go on, write down this set explicitly. Truth is...you won't be able to.
Put it in another way: assume ab absurdo, that you can find such a set $S$. So $S \in S$.
Then the set $\{S\}$ violates the axiom of regularity since both $\{S\}$ and $S$ contain $S$, so  $\{S\} \cap S = \{S\}$ and thus non empty.


text:
Q: Evitar Desplegar menu desde icono en JFrame Buenas Tardes.
Como puedo evitar que se desplegué este menú cuando presione el icono de el frame?

Muchas Gracias.

A: Lo que buscas creo que es imposible, pero esto te puede servir, depende de lo que quieras hacer:
JFrame.setType(javax.swing.JFrame.Type.UTILITY);

Este comando oculta la barra superior (Incluidos el icono, el título, y los botones de maximizar y minimizar (NO el de cerrar)).