text:
Q: Using wildcards to download a file with Invoke-WebRequest I have an url in which there are 6 digits which are changing daily.
Sample website:
https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_160126.csv
This is the part which changes: 160126
I don't know the correct syntax but as a form of pseudo code:
$url = "https://www.ecb.europa.eu/paym/coll/assets
/html/dla/ea_MID/ea_csv_" + [0-9][0-9][0-9][0-9][0-9][0-9]+ ".csv"

How can I write this string?
To answer the comments, I use it to download that file to a folder, like this:
"https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_" + [0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9] +".csv"
$output = "C:\MyFolder\SomeSubFolder\ScriptDownload"
$start_time = Get-Date

Invoke-WebRequest -Uri $url -OutFile $output
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

A: You can parse the download page for your filenames by downloading the page or use get-ElementById etc.
I assume, this is the original download  page
This is your Download URL:
    $Url = "https://www.ecb.europa.eu/paym/coll/assets/html/list-MID.en.html"
$page = Invoke-WebRequest -Uri $Url
$a = ($page.ParsedHtml.getElementsByTagName('table') | ? {$_.classname -eq 'ecb-contentTable'}).textContent
$filename =  $a.Substring($a.IndexOf('ea_csv_'), 17)
$DLURL =  "https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/" + $filename

Gives:
$DLURL
https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_160126.csv

Complete that with your
$output = "C:\MyFolder\SomeSubFolder\ScriptDownload\" + $filename
Invoke-WebRequest -Uri $DLURL -OutFile $Output

and its done.

A: The 6 digits are the date encoded as YYMMDD, correct? If so, you can generate a URL for the current day with:
$currentDay = $(get-date).ToString("yyMMdd")
$url = "https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_$currentDay.csv"

A: What you are asking for cannot be done. However there are better, more reliable ways to get the same result you are looking for.
I'm with Martin. I also found the download page he did. The better way to do this is get the link. Now this is probably not the best way to get the information but it is a start in the right direction.
Note this is slow as hell. Mostly because of Invoke-WebRequest
$start_time = Get-Date
$output = "C:\MyFolder\SomeSubFolder\ScriptDownload"
# Browse to the page hosting the csv file.
$request = Invoke-WebRequest "https://www.ecb.europa.eu/paym/coll/assets/html/list-MID.en.html"
# Locate the uncompressed CSV file name from the page
$filename = $request.ParsedHtml.getElementsByTagName("a") | Where-Object{$_.nameProp -match "^ea_csv_\d{6}\.csv$"} | Select -ExpandProperty nameProp
$fileurl = "https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/$filename"

# Get the file the is hosted today.
Invoke-WebRequest -Uri $fileurl -OutFile "$output\$filename"
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

The way we find the right file name is with ^ea_csv_\d{6}\.csv$ which matches a name where it is exactly "ea_csv_[6 digits].csv".


text:
Q: App Crashes At Launch - "System services not available to Activities before onCreate()" I want to check whether an app is running with the code below. But, my app crashes on launch.
I am using ActivityManager to find the presence of the app. The isAppRunning method takes the name of an application and returns true if the ActivityManager thinks it is currently running.
package com.mavenmaverick.process;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MainActivity M = new MainActivity();
    M.isAppRunning("com.mcent.app");

}

public boolean isAppRunning (String aApplicationPackageName)
{
        ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
            if (activityManager == null)
            {
                    Toast.makeText(this, "Not Running", Toast.LENGTH_SHORT).show();
                    return false;
            }
            List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
            for(int idx = 0; idx < procInfos.size(); idx++)
                {
                    if(procInfos.get(idx).processName.equals(aApplicationPackageName))
                        {
                            Toast.makeText(this, "Running", Toast.LENGTH_SHORT).show();
                            return true;
                        }
                }
            return false;
}

LogCat

01-14 01:19:45.695: E/AndroidRuntime(3335): FATAL EXCEPTION: main
01-14 01:19:45.695: E/AndroidRuntime(3335): java.lang.RuntimeException: Unable to start activity       ComponentInfo{com.mavenmaverick.process/com.mavenmaverick.process.MainActivity}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.os.Looper.loop(Looper.java:137)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.app.ActivityThread.main(ActivityThread.java:5103)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at java.lang.reflect.Method.invokeNative(Native Method)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at java.lang.reflect.Method.invoke(Method.java:525)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at dalvik.system.NativeStart.main(Native Method)
01-14 01:19:45.695: E/AndroidRuntime(3335): Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.app.Activity.getSystemService(Activity.java:4492)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at com.mavenmaverick.process.MainActivity.isAppRunning(MainActivity.java:28)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at com.mavenmaverick.process.MainActivity.onCreate(MainActivity.java:22)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.app.Activity.performCreate(Activity.java:5133)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-14 01:19:45.695: E/AndroidRuntime(3335):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)

A: Step #1: Delete MainActivity M = new MainActivity();. Never manually create an instance of Activity (or Service or ContentProvider, for that matter).
Step #2: Change M.isAppRunning("com.mcent.app"); to isAppRunning("com.mcent.app");

redpajama_set_name: RedPajamaStackExchange


text:
Q: tar trying to open instead of create an archive I'm trying to run a command like this to back up my public directory:
tar -zcvf backups/2014-09-09-public_html.tar.gz public_html -C home/path

My understanding is that this is supposed to create and an archive with the compressed contents of my public directory. But I'm getting the following errors:
tar (child): backups/2014-09-09-public_html.tar.gz: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2

This has me confused because I want it to create the file, not open it. I've used similar commands in other projects without problems, so I'm not sure what the problem could be here. What could I be doing wrong?

A: When you create a file, you actually open it in write mode, even if it does not yet exist (read man 3 open to further understand how this works on *nix).
Are you sure you have write permissions for the destination where you're trying to compress? Can you touch(1) that location?

A: Well, I finally got it working by putting -C /home/path at the beginning and using the absolute path for the archive name instead of the relative path:
tar -C /home/path -zcvf /home/path/backups/2014-09-09-public_html.tar.gz public_html

I still don't understand why I need to specify the absolute path for the archive name since I've always used the relative path in other projects. I guess maybe it's a difference in how this server is set up or something?


text:
Q: Sound defaulting to HDMI I would like to know how to deafult my sound to always use headphones?
I plug my laptop via display port into an external monitor. Whenever I restart ubuntu (13.04) the sound is always defaulted to HDMI/DisplayPort.
Is there a way to override this?
My Sound options are
1) HDMI/Displayport (Built-in-Audio)
2) Headphones (Built-in-Audio)


text:
Q: How to send data to socket.io from react? I've never used Socket.IO before so this is very new for me.
I have a taxi app in react which will send a new order as an event through Socket.IO but I don't see any error or response.
Server Side it looks like this:
client.on('newOrder', function(data){
    socketController.newOrder(data, io, client);
});

newOrder: function(data, io, client) {
    order.create(data, io, client, function(response){});
}

Order.prototype.create = function (data, io, client, callback) {

    console.log("ORDER DATA = " + JSON.stringify(data));

    let luggage = 0;
    if (typeof data.luggage !== 'undefined')
        luggage = data.luggage;

    let insertData = {
        client_id: data.id_client,
        start_address: data.origin.name,
        start_lat: data.origin.latitude,
        start_lng: data.origin.longitude,
        end_address: data.destination.name,
        end_lat: data.destination.latitude,
        end_lng: data.destination.longitude,
        options: JSON.stringify(data.options),
        car_options: JSON.stringify(data.car_options),
        car_type: data.car_type,
        passengers: data.passengers,
        luggage: luggage,
        payment_method: data.payment_method,
        profile_id: data.profile,
        profile_type: data.profile_type
    };

    if (data.schedule_time != null && data.schedule_time.length > 0) {
        insertData.schedule_time = data.schedule_time
    }

    db.query("INSERT INTO orders SET ?", insertData,
        function (err, results, fields) {
            if (err) {
                console.log("Order.create [ERROR: " + err + "]");
                return callback({ error: true, message: err });
            }

            data.id_order = results.insertId;

            const timeInsert = {
                order_id: data.id_order,
                new: new Date().toISOString().slice(0, 19).replace('T', ' ')
            };

            db.query("INSERT INTO orders_timestamps SET ?", timeInsert, function (err, results, fields) { });

            client.emit("orderSaved", { "id_order": data.id_order });
            getOrder(data.id_order, function (order) {

                sendOrdersToDriver(data, order, io, function (data) {
                    console.log("Order.create [SUCCESS]");
                    return callback(data);
                });
            });

        }
    );

};

Client Side it looks like this
const data = {
    id_client: user.id,
    car_type: "executive",
    car_options: [],
    passengers: 1,
    luggage: 2,
    payment_method: "cash",
    options: [],
    origin: { name: pickUp, latitude: pickUpCoordinates.lat, longitude: pickUpCoordinates.lng },
    destination: { name: dropOff, latitude: dropOffCoordinates.lat, longitude: dropOffCoordinates.lng },
    schedule_time: new Date(),
    profile: "",
    profile_type: "owner"
}
socket.emit("newOrder", data, function (response) {
    console.log('emit response', response);
});

A: Edit 1:
Let me try to explain how does this callback stuff working,
// here we are at the client-side
// so here from client side i'm sending a data and a callback
// socket.emit('event-name', data, callback); signature
socket.emit('some-event', { a: true }, function(dataFromServer) {
    console.log(dataFromServer);
});

// here we are at server-side
socket.on('some-event', function(data, callback) {
    // we are getting the data first argument and callback second
    // let's say we are testing if data has a === true;
    if(data.a) { // same as data.a === true
       // here we are gonna send 'hi' to callback
       return callback('hi the data was valid for me');
    }
    // otherwise we are assuming that data wasn't valid
    return callback('your data is not okey mate!');
});

So from client-side if you send a data contains { a: true } as prop you should see that callback consoling 'hi the data was valid for me' this.
Otherwise if it doesn't contain a or a: false then you should see 'your data is not okey mate!' from your client's callback.
Consedering this senario; go for your code and check =)
First please check if you socket.connected === true on your frontend.
Second here you are sending data and a callback through your emit
socket.emit("newOrder", data, /*this is your callback*/function (response) {
    console.log('emit response', response);
});

And here on your server you are only getting data from client.
// needs to be like this
client.on('newOrder', function(data, callback) {
    socketController.newOrder(data, callback, io, client);
});
// same with
newOrder: function(data, callback, io, client) {
     // you probably dont need to send this empty callback cause actualy callback
     // coming after `data`, `callback`
    order.create(data, callback, io, client); //function(response){});
}

// same with
Order.prototype.create = function (data callback, io, client) {
...

  sendOrdersToDriver(data, order, io, function (data) {
    console.log("Order.create [SUCCESS]");
    // here you are calling it so it needs to work if
    // your `sendOrdersToDriver` function actually calls it's
    // own callback?
    return callback(data);
  });
}


text:
Q: How not to redirect HTML file to php I am very new to php just today itself I have started learning it, I am doing a simple program from of selecting a row from mysql's database based on user input on html through php file . and my concern is when I submit the form , it redirects to to the php and the output is displayed on the php, how can I display the result on the HTML page itself I mean the user shouldn't feel there is any transition from html to php any we get the output on the html page
HTML page :
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
    <form action="index.php" method="get">
    Enter Name : <input type="text" id="txt1" name="user">
    <input type="submit" name="enter">
    </form>
</body>

php page :
<?php
$dbhost = "localhost";
 $username = "root";
 $password = "";

 mysql_connect($dbhost,$username,$password);
 @mysql_select_db("trynew") or die(mysql_error());

if (isset($_GET["user"])) {
$user = $_GET['user'];

}
$query = "SELECT * FROM trynewtable where name = '$user' ";
$result = mysql_query($query);
if($result==FALSE)
{
die(mysql_error());
}
$row = mysql_fetch_array($result);
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];

mysql_close();

?>

A: On the user side theres no difference between html and php, php files are also html in the view of the browser. The only difference is that php files are interpreted by the server ,while html is just send. So you can put your html in your php and mix it all together:
index.php:
<body>
<div id="response">
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
//do your request
}else{
echo "please fill in the form";
}
?>
</div>
//your form etc

A: Simple answer You can merge the HTML and PHP files unless there is a need to separate them (if so use AJAX). Do a validation before any database interaction. Do not use mysql but mysqli_
<?php
$dbhost = "localhost";
 $username = "root";
 $password = "";
  $col1 = $col2=$col3=$col4="";
 mysql_connect($dbhost,$username,$password);
 @mysql_select_db("trynew") or die(mysql_error());

if (isset($_GET["user"])) {
    $user = $_GET['user'];

    $query = "SELECT * FROM trynewtable where name = '".mysql_real_escape_string($user)."' ";
    $result = mysql_query($query);
    if($result==FALSE) {
        die(mysql_error());
    }
    $row = mysql_fetch_array($result);
    $col1 = $row[0];
    $col2 = $row[1];
    $col3 = $row[2];
    $col4 = $row[3];
}
mysql_close();

?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
    <?php echo $col1." ".$col2." ".$col3." ".$col4;?>
    <form action="" method="get">
    Enter Name : <input type="text" id="txt1" name="user">
    <input type="submit" name="enter">
    </form>
</body>


text:
Q: Workflow Execution order I know that there is no particular order for the workflow execution, but is there any way I could write a formula to get it done like (Record creation time + add some seconds), or any workaround. Any help is appreciated. Thanks.

A: There is some ordering to workflow actions - as per this help topic:
https://help.salesforce.com/apex/HTViewHelpDoc?id=workflow_rules_considerations.htm&language=en
"The order in which individual actions and types of actions are executed is not guaranteed. However, field update actions are executed first, followed by other actions."
I have seen anecdotal evidence that workflow rules fire in the order that they were created - don't rely on this as Salesforce staff have said in the past that this isn't the case.
If you need ordering to the evaluation of the rules and/or actions that are fired, you'll need to write your business logic in an apex trigger rather than a workflow.  That way you'll have full control.

A: Yes, you can use time dependent workflow rule. Here are few examples. on how to use workflow rules with time dependency.


text:
Q: Добавить фильтр для условного обозначения столбцов power BI можно ли создать фильтр который будет менять это поля

Для того что бы можно было управлять различными разбивками, не создавая дополнительные графики


text:
Q: nginx reverse proxy - synology dsm issue I currently have nginx serving as a reverse proxy on my router with a single server block and multiple locations mapping to specific ports on my NAS. Everything seems to be working fine except for one item -- Synology DSM. Right now, the only way that I have WAN access to DSM in my setup is with the following configuration:
location / {
   proxy_pass http://127.0.0.1:5000;
}

I'd prefer to have something like this:
location /dsm {
   proxy_pass http://127.0.0.1:5000;
}

However, I can't seem to get this to work. I've tried location and proxy_pass with/without ending slashes and attempted different rewrite options but nothing has worked. I either get "page not found" errors or the page loads and I can view the source but nothing is displayed.
It should be noted that the DSM is CGI-based (loads as http://127.0.0.1:5000/webman/index.cgi) and it looks like there are absolute paths hardcoded in the css and js.

A: Asked 3 years ago, but I had this month (Oct 2018) the same problem. Yes, it is a mess with hard-coded paths. Simple PassProxy/ProxyPassReverse is not working. I am no computer expert, not at all. I found this configuration somewhere on internet, among many, many other propositions, and as a miracle it was the only one that worked ... (Debian 9, Apache2).  Slashes must be exactly in this way. You must call dsm as http://your.local.server.name/dsm/ or http://your.internet.name/dsm/.
 I hardly know what exactly every configuration line does, and I don't dare delete anything. Let the gurus figure out ...
On my machine, I edited /etc/apache2/sites-enabled/000-default.conf
but I suppose the script would work on any reverse-proxy server.
<VirtualHost *:80>
ServerName your.local.server.name
ServerAlias your.internet.name

<Location /dsm/>
ProxyPass http://your.synology.dsm:5000/
ProxyPassReverse /
ProxyHTMLEnable On
ProxyHTMLURLMap /       /dsm/
RequestHeader unset  Accept-Encoding

Order allow,deny
Allow from all

</Location>
</VirtualHost>


text:
Q: Tensorflow L2 loss definition I was wondering why tf.nn.l2_loss was set to compute half the L2 norm. Is there any special meaning to divide the L2 norm by 2?

A: It is just to simplify its derivatives (cancelling the 2 coefficients appearing from derivating the squared elements)


text:
Q: How to use MVVM ViewModel to change stuff in a View based on a ListView SelectionChanged event I want to make a UWP application with a ListBox navigation whose selected item determines the content of a frame. When the selection changes, the frame content should change. I found an example for how to this (Method 1 below), but it uses event handlers in the code behind. I want to learn MVVM with this project and thus want to use a MVVM solution to this problem. I'm new to MVVM and my current understanding is that in order to decouple the View from the ViewModel, ViewModels shouldn't reference anything particular to the View. Is this a correct understanding? The only way I can think of using the ViewModel to change the frame view is to basically move the event handler code to the ViewModel and pass in the Frame to the constructor (Method 2 below). But that violates my understanding of the ViewModel relationship to the View since the ViewModel is referencing particular instances of things in the View; furthermore it seems like pointless overhead and like it would give very little organization benefit.
How would you implement a MVVM solution to this problem? Or is this a case where using event handlers is better?
METHOD 1 - Event handler:
This code is based on an example Microsoft provides. (Here's the link to the relevant code: https://github.com/microsoft/Windows-universal-samples/tree/master/Samples/Playlists/cs)
public sealed partial class MainPage : Page
{
    List<Scenario> scenarios = new List<Scenario>
    {
        new Scenario() { Title = "Scenario 1", ClassType = typeof(Scenario1) },
        new Scenario() { Title = "Scenario 2", ClassType = typeof(Scenario2) }
    };

    public MainPage()
    {
        this.InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        ScenarioControl.ItemsSource = scenarios;
    }

    private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListBox scenarioListBox = sender as ListBox;
        Scenario s = scenarioListBox.SelectedItem as Scenario;
        if (s != null)
        {
            ScenarioFrame.Navigate(s.ClassType);
        }
    }
}

public class Scenario
{
    public string Title { get; set; }
    public Type ClassType { get; set; }

    public override string ToString()
    {
        return Title;
    }
}

<!-- MainPage.xaml -->
<Grid>
    <SplitView x:Name="Splitter" IsPaneOpen="True" DisplayMode="Inline">
        <SplitView.Pane>
            <RelativePanel>
                <ListBox x:Name="ScenarioControl" SelectionChanged="ScenarioControl_SelectionChanged"/>
            </RelativePanel>
        </SplitView.Pane>
        <RelativePanel>
            <Frame x:Name="ScenarioFrame" />
        </RelativePanel>
    </SplitView>
</Grid>

METHOD 2 - MVVM(?):
<!-- MainPage.xaml -->
<Grid>
    ...
    <ListBox x:Name="ScenarioControl" SelectionChanged="{x:Bind MyViewModel.SwitchScenario}"/>
    ...
</Grid>

// MainPage.xaml.cs
...
    public MainPage()
    {
        this.InitializeComponent();
        MyViewModel = new MyViewModel(ScenarioFrame);
    }
...
    MyViewModel MyViewModel { get; set; }
}

// MyViewModel.cs
public class MyViewModel
{
    public MyViewModel(Frame scenarioFrame)
    {
        ScenarioFrame = scenarioFrame;
    }

    public void SwitchScenario(object sender, SelectionChangedEventArgs e)
    {
        ListBox scenarioListBox = sender as ListBox;
        Scenario s = scenarioListBox.SelectedItem as Scenario;
        if (s != null)
        {
            ScenarioFrame.Navigate(s.ClassType);
        }
    }

    public Frame ScenarioFrame { get; set; }
}

A: You'll need PropertyChangedNotification when your model property changes- anything binding to the model property will then update automatically.
Also Bindings.Update() is your friend sometimes.
And if you're going to have a View and a ViewModel you'll need to set the DataContext of your View to the instance of the ViewModel or Model you are binding to.

A:
How would you implement a MVVM solution to this problem? Or is this a case where using event handlers is better?

For implementing MVVM navigation, you could refer Template 10 and Template Studio workflow.
In template 10, it bind Click event with navigation method.
<controls:PageHeader x:Name="pageHeader" RelativePanel.AlignLeftWithPanel="True"
                     RelativePanel.AlignRightWithPanel="True"
                     RelativePanel.AlignTopWithPanel="True" Text="Main Page">

    <!--  secondary commands  -->
    <controls:PageHeader.SecondaryCommands>
        <AppBarButton Click="{x:Bind ViewModel.GotoSettings}" Label="Settings" />
        <AppBarButton Click="{x:Bind ViewModel.GotoPrivacy}" Label="Privacy" />
        <AppBarButton Click="{x:Bind ViewModel.GotoAbout}" Label="About" />
    </controls:PageHeader.SecondaryCommands>

</controls:PageHeader>

ViewModel
 public void GotoDetailsPage() =>
     NavigationService.Navigate(typeof(Views.DetailPage), Value);

 public void GotoSettings() =>
     NavigationService.Navigate(typeof(Views.SettingsPage), 0);

In Template Studio, it navigates with NavHelper class.
<winui:NavigationViewItem x:Uid="Shell_Main" Icon="Document" helpers:NavHelper.NavigateTo="views:MainPage" />
<winui:NavigationViewItem x:Uid="Shell_Blank" Icon="Document" helpers:NavHelper.NavigateTo="views:BlankPage" />
<winui:NavigationViewItem x:Uid="Shell_MediaPlayer" Icon="Document" helpers:NavHelper.NavigateTo="views:MediaPlayerPage" />
<winui:NavigationViewItem x:Uid="Shell_WebView" Icon="Document" helpers:NavHelper.NavigateTo="views:WebViewPage" />

<ic:EventTriggerBehavior EventName="ItemInvoked">
                <ic:InvokeCommandAction Command="{x:Bind ViewModel.ItemInvokedCommand}" />
            </ic:EventTriggerBehavior>

ViewModel
private void OnItemInvoked(WinUI.NavigationViewItemInvokedEventArgs args)
{
    if (args.IsSettingsInvoked)
    {
        NavigationService.Navigate(typeof(SettingsPage));
        return;
    }

    var item = _navigationView.MenuItems
                    .OfType<WinUI.NavigationViewItem>()
                    .First(menuItem => (string)menuItem.Content == (string)args.InvokedItem);
    var pageType = item.GetValue(NavHelper.NavigateToProperty) as Type;
    NavigationService.Navigate(pageType);
}


text:
Q: Why some English words getting removed after using stop words or nltk corpus? I am working with pyspark dataframes and I need to perform data cleaning on one of the columns as shown below:
df.select('words').show(10, truncate = 100)

+----------------------------------------------------------------------------------------------------+
|                                                                                words|
+----------------------------------------------------------------------------------------------------+
|[you, are, hereby, ordered, to, cease, and, desist, all, furthe, r, emails, to, this, address, im...|
|[content, type, text, plain, charset, utf, 8, content, transfer, encoding, quoted, printable, x, ...|
|[you, are, hereby, ordered, to, cease, and, desist, all, furthe, r, emails, to, this, address, im...|
|[, original, message, return, path, bounce, 19853e, 6fb54, visyak, 3djuno, com, cysticacneonchin,...|
|[, forwarded, message, return, pat, h, bounce, 19853e, 6fb54, visyak, 3djuno, com, cysticacneonch...|
|[, original, message, from, 248, 623, 1653, mailto, lisa, lahlahsales, com, 20, sent, tuesday, fe...|
|[2018, horse, trailer, closeouts, free, delivery, cash, back, click, here, to, view, it, online, ...|
|[, original, message, from, paypal, us, mailto, scottkahndmd, nc, rr, com, sent, 27, february, 20...|
|[2col, 1, 2, 09, client, specific, styles, outlook, a, padding, 0, force, outlook, to, provide, a...|
|[you, are, hereby, ordered, to, cease, and, desist, all, furthe, r, emails, to, this, address, im...|
+----------------------------------------------------------------------------------------------------+
only showing top 10 rows

I perform the following steps for data cleaning:
remover = StopWordsRemover(inputCol='words', outputCol='words_clean') #remove stop-word
df = remover.transform(df)

df = df.withColumn("words_filtered", F.expr("filter(words_clean, x -> not(length(x) < 3))")).where(F.size(F.col("words_filtered")) > 0) #remove words with less than 3 characters

wnl = WordNetLemmatizer()
@F.udf('array<string>')
def remove_words(words):
    return [word for word in words if wnl.lemmatize(word) in nltk.corpus.words.words()] #removing words that are not in nltk corpus

df = df.withColumn('words_final', remove_words('words_filtered'))

I get the output as shown below:
df.select('words_final').show(10, truncate = 100)

+----------------------------------------------------------------------------------------------------+
|                                                                                words_final|
+----------------------------------------------------------------------------------------------------+
|[hereby, ordered, cease, desist, address, immediately, authorities, provider, continued, failure,...|
|[content, type, text, plain, content, transfer, printable, apparently, yahoo, tue, return, path, ...|
|[hereby, ordered, cease, desist, address, immediately, authorities, provider, continued, failure,...|
|[original, message, return, path, bounce, received, sender, bounce, tue, pst, results, received, ...|
|[message, return, pat, bounce, received, sender, bounce, tue, pst, results, received, ass, receiv...|
|                                                       [original, message, sent, ball, subject, get]|
|[horse, trailer, free, delivery, cash, back, click, view, horse, magazine, index, option, archive...|
|[original, message, sent, subject, notification, payment, number, hello, payment, amount, payment...|
|[client, specific, styles, outlook, padding, force, outlook, provide, view, browser, button, body...|
|[hereby, ordered, cease, desist, address, immediately, authorities, provider, continued, failure,...|
+----------------------------------------------------------------------------------------------------+
only showing top 10 rows

I see that stop words (are, the, in, etc) and many junk words such as scottkahndmd or incomplete words such as furthe are removed. But there are few words like emails, tuesday, february, encoding, quoted, online are also removed. There could be more such English words which might be getting ignored.
Any reason for this?

A: In your case, it looks like filtering happens in several places:

*

*the StopWordsRemover removes common words, like, he, she, myself, etc.  Usually these words may not be very useful in the text models, but that depends on the task that you're trying to solve

*another layer of filtering is your WordNetLemmatizer - it could be the main culprit of removal of email, encoding, etc.  Try to tune it, to be less  aggressive in removal of the words

P.S. if you're doing NLP on Spark, I would recommend to look to the Spark NLP package instead.  It could be more performant, have more functionality, etc.


text:
Q: How to convert the values in a Python Defaultdict to a Numpy array? I want multiple values to belong to the same key, so I used a Python defaultdict to walk around this.
However, since now the values in the defaultdict are nested lists, how do I make each element of the nested lists a row of a Numpy ndarray?
Let's say my defaultdict looks like this:
my_dict = defaultdict(list)

*** in some for loop ***
 my_dict[key].append(value) # key is a string and value is a Numpy array of shape (1,10)
*** end of the for loop ***

I guess the slowest way would be using a nested for loop like:
data = np.empty((0,10),np.uint8)
for i in my_dict:
    for j in my_dict[i]:
        data = np.append(data,j,axis=0)

is there a faster way to do this?

A: Instead of using defaultdict(list) use setdefault functionality, this will spare you from the nested list
my_dict = dict()
for key, value in values:
    my_dict[key] = np.append(my_dict.setdefault(key, value), value)

data = np.array(list(my_dict.values()))

A: You should have provided an example, but I think the following is as general as your code implies.
In [131]: from collections import defaultdict
In [132]: dd = defaultdict(list)
In [133]: dd[1].append(np.ones((1,5),int))
In [134]: dd[2].append(2*np.ones((1,5),int))
In [135]: dd[1].append(3*np.ones((1,5),int))

In [136]: dd
Out[136]:
defaultdict(list,
            {1: [array([[1, 1, 1, 1, 1]]), array([[3, 3, 3, 3, 3]])],
             2: [array([[2, 2, 2, 2, 2]])]})

Several suggested making array from:
In [137]: list(dd.values())
Out[137]:
[[array([[1, 1, 1, 1, 1]]), array([[3, 3, 3, 3, 3]])],
 [array([[2, 2, 2, 2, 2]])]]

But with the possibility that there is more than one array in each list, that won't work.
We can flatten the nested lies with something similar to your code, but with a faster list append:
In [140]: alist = []
     ...: for i in dd:
     ...:     for a in dd[i]:
     ...:         alist.append(a)
     ...:
In [141]: alist
Out[141]: [array([[1, 1, 1, 1, 1]]), array([[3, 3, 3, 3, 3]]), array([[2, 2, 2, 2, 2]])]

We can make a 2d array from this (provided the subarrays match in shape):
In [142]: np.vstack(alist)
Out[142]:
array([[1, 1, 1, 1, 1],
       [3, 3, 3, 3, 3],
       [2, 2, 2, 2, 2]])

or:
In [144]: np.array(alist).shape
Out[144]: (3, 1, 5)

As a general rule, repeated np.append is inefficient.  list append (or a list comprehension) is best when iteration is unavoidable.
Guy's
Trying to recreate the dict with @Guy's suggestion:
In [147]: my_dict = dict()
     ...: key,value=(1,np.ones((1,5),int)); my_dict[key]= np.append(my_dict.setdefault(key, value), value)

I would prefer to use np.hstack here (np.append is misused too often).
In [148]: key,value=(2,2*np.ones((1,5),int)); my_dict[key]= np.append(my_dict.setdefault(key, value), value)
In [149]: key,value=(1,3*np.ones((1,5),int)); my_dict[key]= np.append(my_dict.setdefault(key, value), value)

In [150]: my_dict
Out[150]:
{1: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3]),
 2: array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2])}

This has duplicated values for some of the additions.  And making an array from list(my_dict.values()) is no easier.
We could collect the dict values as arrays, but it's not a simple as with lists.  Array doesn't have a simple "empty", and doesn't have an inplace "append".
In [157]: dd = defaultdict(lambda: np.zeros([0,5],int))
In [158]: dd[1]=np.vstack((dd[1],(np.ones((1,5),int))))
In [159]: dd[2]=np.vstack((dd[2],(2*np.ones((1,5),int))))
In [160]: dd[3]=np.vstack((dd[3],(3*np.ones((1,5),int))))

In [161]: dd
Out[161]:
defaultdict(<function __main__.<lambda>()>,
            {1: array([[1, 1, 1, 1, 1]]),
             2: array([[2, 2, 2, 2, 2]]),
             3: array([[3, 3, 3, 3, 3]])})

In [162]: np.vstack(list(dd.values()))
Out[162]:
array([[1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3]])

This avoids an iteration after the dict is constructed, but the dict construction is more complex and slower.  So I don't think it helps.


text:
Q: Celery retry only the fail request in the loop and continue with the other I'm kinda new to celery as a whole and having the problem with retry case on a for loop:
i have the following task:
@app.task(bind=True, autoretry_for=(CustomException,), retry_kwargs={'max_retries': 10,'countdown': 30})
def call_to_apis(self):
   api_list = [api1, api2, api3, api4, api5,...]
   for api in api_list:
       try:
           response = requests.get(api)
           if response.status_code == 500:
              raise CustomException
       except CustomException:
           continue

From my understanding celery will retry on my CustomException get raised.
In the case of retry, will it only retry for the the failed api or will it just run the whole process of every api in the api_list again? If so is there anyway for it to only retry the failed api ?
Expected result: only retry the failed api
EDIT:
i have split it into 2 different tasks and 1 request function as follow:
@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(300.0, call_to_apis.s())
    print("setup_periodic_tasks")

def call_api(api):
    response = requests.get(api)
    if response.status_code == 500:
        raise CustomException
    elif response.status_code == 404:
        raise CustomWrongLinkException

@app.task(default_retry_delay=30, max_retries=10)
def send_fail_api(api):
    try:
        call_api(api)
    except NonceTooLowException:
        try:
            send_fail_api.retry()
        except MaxRetriesExceededError:
            print("reached max retry number")
            pass
    except Exception:
        pass

@app.task()
def call_to_apis():
   api_list = [api1, api2, api3, api4, api5,...]
   for api in api_list:
       try:
          call_api(api)
       except CustomException:
          send_fail_api.delay(api)
       except CustomWrongLinkException:
          print("wrong link")
       except Exception:
          pass

it worked and the other apis get to complete, with failed api it supposed to call to another task and retry for 10 time each delay 30 seconds.
But i'm getting more than expected retries about 24 times(expected to only retry 10 times) and it also printed out reached max retry number at 10th retry but it still retry until 24 retries
What am i doing wrong ?

A: The whole task will be retried in case of a known exception (specified in autoretry_for decorator argument), see the documentation. Celery can't know by any means the state of the task when exception is raised, that's what you have to handle. I would suggest splitting the task into individual tasks (one per API) and call them separately, presumably creating some workflow.


text:
Q: JIT debugging PHP in Aptana Studio Linux Mint 15, Aptana Studio 3.4.1, Chromium 28.0.1500.71
Sorry, this is a little lengthy to explain. Please let me know if something's not clear.
The title is my goal. I have a local server set up with Apache2. I don't know if it matters, but I have dnsmasq set up to redirect, for example, site.dev/index.html to /home/wastvedt/Projects/site/www/index.html (described here).
I've followed the tutorials I can find. XDebug is running, I have the helper installed in Chromium, and the debugger, interpreter, and web server set up in Aptana.
I'm working on a WordPress site and want to break on one of the functions in my theme's functions.php file. I created a breakpoint in the function in Aptana, turned on the XDebug helper in Chromium, and updated a post, which calls the function in question. Aptana recognizes what I'm doing and prompts me with the option of breaking on the first line. Regardless of what I select, I see "XDebug JIT Session [Remote Launch]" in the Debug view. The prompt appears three times, but nothing else happens in Aptana.
I think the problem might have something to do with linking files in the editor to files in Apache. When I try this JIT debugging thing with "localhost" (located at /home/wastvedt/apache2/www/index.php), Aptana brings up /home/wastvedt/Projects/site/www/index.php. This isn't right, but maybe the real problem is somewhere else. To be honest I'm a little lost now.
Any thoughts? I'd provide some sort of dump or output, but I'm not sure which or what.
Thanks for reading,
Trygve

A: In order to properly setup XDebug with Aptana I setup the below options by going to the Window menu -> Preferences -> Aptana Studio -> Editors -> PHP -> Debug:
Allow multiple debug sessions: Always
Break on first line when an unknown remote sessions (JIT): Never
Then click on XDebug in Installed Debuggers -> Configure:
Use Multisession: OFF
Accept remote session (JIT): any
That pretty much made it work for me.


text:
Q: Align horizontally with % in CSS I've made a sort of diagram with temperature values and a schedule for it. Now I want to align the time-tags perfectly with the middle of my gaps between the "blocks". The first one works with position:absolute and left:(%-px/2), but the second and third example are off. How does one align these boxes?
The Fiddle is HERE.

body {
  background-color: #DDD;
}

a {
  cursor: pointer;
}

.block {
  display: block;
  height: 100%;
  color: #FFF;
  font-size: .75em;
  float: left;
  position: relative;
  opacity: 1;
  transition: opacity, 0.4s ease; /* hover effect transition */
  border-radius: 5px;
}

.block:nth-child(n+2) {
  margin-left: 0.5%;
}

.block:hover {
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 3px 10px 0 rgba(0, 0, 0, 0.19);
}

.block.cool,
.legend li:nth-of-type(1):before {
  background-color: #41A6F0;
}

.block.hot,
.legend li:nth-of-type(2):before {
  background-color: #E27A3F;
}

.paused.cool {
  background-color: #ccc;
}

.paused.hot {
  background-color: #bbb;
}

.barchart {
  display: grid;
  margin: 0;
  grid-template-columns:
    [viewport-start] minmax(0.57em, 1fr) [container-start] minmax(20em, 35em) [container-end] minmax(0.75em, 1fr) [viewport-end];
  grid-auto-rows: 30px;
}

row {
  padding: 5px;
  grid-column: container;
  grid-row: span 4;
  line-height: 120px;
  text-align: center;
  width: 0%;
  animation: expand 1.2s ease forwards;
  /* see animation "expand" below */
}

timerow {
  grid-column: container;
  grid-row: span 1;
  line-height: 14px;
  text-align: center;
  visibility: hidden;
  animation: 1.3s blendin; /* see animation "blendin" below */
  animation-fill-mode: forwards;
  margin-top: -15px;
  position: relative;
}

timerow a {
  position: absolute;
  height: 25px;
  width: 44px;
  font-size: 0.8em;
  color: #919191;
  background: #fff;
}

/*
timerow a:last-child {
  float: right;
  margin-right: -12px;
}

timerow a:first-child {
  margin-left: -17px;
}
*/
tag {
  grid-column: container;
  padding-top: 8px;
  font-size: 0.8em;
  color: #919191;
}

/* Big-Screen Design */
@media screen and (min-width: 768px) {
  .barchart {
    margin-left: -4.5em;
    grid-template-columns:
      [viewport-start] minmax(0.5em, 1fr) [axis-start] minmax(2em, 8em) [container-start] minmax(36em, 3fr) [container-end] minmax(0.5em, 1fr) [viewport-end];
  }

  tag {
    grid-column: axis-start/container-start;
    grid-row: span 4;
    line-height: 120px;
    padding: 0;
    text-align: center;
  }

}

/* intro animation */
@keyframes expand {
  from {
    width: 0%;
  }

  to {
    width: calc(100% - 12px);
  }
}

@keyframes blendin {
  99% {
    visibility: hidden;
  }

  100% {
    visibility: visible;
  }
}

@media screen and (min-width: 768px) {
  @keyframes expand {
    from {
      width: 0%;
    }

    to {
      width: calc(100% - 13px);
    }
  }
}

row:nth-child(4) {
  animation-delay: .1s;
}

row:nth-child(6) {
  animation-delay: .2s;
}

  <tag>Workday</tag>

  <row>
    19deg
    21deg
    22deg
  </row>

  <timerow>
  07:30
  22:30
  </timerow>

  <tag>Weekend</tag>
  <row>
    16deg
    21deg
    18deg
  </row>

  <timerow>
  00:00
00:00
  </timerow>

timerow a {
  position: absolute;
  height: 25px;
  width: 44px;
  font-size: 0.8em;
  color: #919191;
  background: #fff;
}

this one get's positioned too far right,
  22:30

while this one works perfectly, where the ":" is centered in the gap:
  07:30

Even though I added the % numbers and factored in the 0.5% gap and subtracted the 22px for half the width of the box.

A: You also have the padding that you need to account for since position:absolute consider the padding-box to do the calculation. Add margin to timerow equal to the padding applied to row and you calculation will be correct.
You can also simplify the -22px with a translation. Also consider box-sizing:border-box; to your row element instead of decreasing the width in the animation.

body {
  background-color: #DDD;
}

a {
  cursor: pointer;
}

.block {
  display: block;
  height: 100%;
  color: #FFF;
  font-size: .75em;
  float: left;
  position: relative;
  opacity: 1;
  transition: opacity, 0.4s ease; /* hover effect transition */
  border-radius: 5px;
}

.block:nth-child(n+2) {
  margin-left: 0.5%;
}

.block:hover {
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 3px 10px 0 rgba(0, 0, 0, 0.19);
}

.block.cool,
.legend li:nth-of-type(1):before {
  background-color: #41A6F0;
}

.block.hot,
.legend li:nth-of-type(2):before {
  background-color: #E27A3F;
}

.paused.cool {
  background-color: #ccc;
}

.paused.hot {
  background-color: #bbb;
}

.barchart {
  display: grid;
  margin: 0;
  grid-template-columns:
    [viewport-start] minmax(0.57em, 1fr) [container-start] minmax(20em, 35em) [container-end] minmax(0.75em, 1fr) [viewport-end];
  grid-auto-rows: 30px;
}

row {
  padding: 5px;
  box-sizing:border-box;
  grid-column: container;
  grid-row: span 4;
  line-height: 120px;
  text-align: center;
  width: 0%;
  animation: expand 1.2s ease forwards;
  /* see animation "expand" below */
}

timerow {
  grid-column: container;
  grid-row: span 1;
  line-height: 14px;
  margin:0 5px;
  text-align: center;
  visibility: hidden;
  animation: 1.3s blendin; /* see animation "blendin" below */
  animation-fill-mode: forwards;
  margin-top: -15px;
  position: relative;
}

timerow a {
  position: absolute;
  height: 25px;
  width: 44px;
  font-size: 0.8em;
  color: #919191;
  background: #fff;
  transform:translateX(-50%);
}

tag {
  grid-column: container;
  padding-top: 8px;
  font-size: 0.8em;
  color: #919191;
}

/* Big-Screen Design */
@media screen and (min-width: 768px) {
  .barchart {
    margin-left: -4.5em;
    grid-template-columns:
      [viewport-start] minmax(0.5em, 1fr) [axis-start] minmax(2em, 8em) [container-start] minmax(36em, 3fr) [container-end] minmax(0.5em, 1fr) [viewport-end];
  }

  tag {
    grid-column: axis-start/container-start;
    grid-row: span 4;
    line-height: 120px;
    padding: 0;
    text-align: center;
  }

}

/* intro animation */
@keyframes expand {
  from {
    width: 0%;
  }

  to {
    width: 100%;
  }
}

@keyframes blendin {
  99% {
    visibility: hidden;
  }

  100% {
    visibility: visible;
  }
}

row:nth-child(4) {
  animation-delay: .1s;
}

row:nth-child(6) {
  animation-delay: .2s;
}

  <tag>Workday</tag>

  <row>
    19deg
    21deg
    22deg
  </row>

  <timerow>
  07:30
  22:30
  </timerow>

  <tag>Weekend</tag>
  <row>
    16deg
    21deg
    18deg
  </row>

  <timerow>
  00:00
00:00
  </timerow>


text:
Q: How to understand disk activity view charts of the Windows 7 resource monitor? The disk activity monitor charts show blue line, green line with the green shaded area below and sometimes also the orange line. Of course, the higher the lines the more the activity and horizontal axis is clearly the time but what is exactly plotted there? I have looked into disk activity monitor help but did not find the legend of these charts there.
I mean, Resource Monitor, Disk tab, charts on the right.

A: According to Microsoft TechNet:

Disk displays the total current I/O in green, and displays the highest active time percentage in blue.

Notice that this corresponds to the Disk Activity list on the left (might need to expand it), which shows "XX KB/sec Disk I/O" and "XX% Highest Active Time". So, I interpret this as green being both reads and writes, and blue also being reads and writes, but showing the current value of the green line divided by the maximum value of the green line, as a percentage.
Admittedly my source is for Windows Server 2008, not Windows 7.
The orange line shows I/O for a specific task, enabled by checking a box in the "Processes with Disk Activity" list on the left (might need to expand it also).

A: UPDATE:
Many thanks to RoG below for more clarification on this answer:
Green is data being WRITTEN TO and READ FROM the drive.
Blue shows a statistical quantifier of the amount of data that has been written to and from from the drive, as explained by RoG below:

"...Blue...showing the current value of the green line divided by the maximum
  value of the green line, as a percentage."

Orange shows the impact of a specific task, as chosen by checking a box to highlight the task on the left of the window.


text:
Q: Retaining tabular structure after extracting data using OCR Pytesseract I am using OCR Pytesseract to extract data from an image which has tabular data. I am extracting it to a textfile and I wish to store it in an excel sheet. I Couldn't directly store it into an excel sheet. But the problem I am encountering is that after saving data to text file, I am losing the tabular kind of structure. I tried converting to a dataframe and referred to a few SO questions as well, but none seem to help. My aim is that every cell of the excel sheet should have single value which would be extracted from Tesseract.
Code to save to excel and converting to dataframe is:
text = pytesseract.image_to_string(PIL.Image.open("jpg path"), config = config)
#print(text)
file = open("file.txt","a+", encoding  = "utf-8")
file.write("text :{0}".format(text))
file.close()
list_of_lists = []

with open("fileone.txt", 'r', encoding = "utf-8") as f:
    for line in f:
        inner_list = [line.strip() for line in line.split("  ")]
        list_of_lists.append(inner_list)

df = pd.DataFrame(list_of_lists)
print(df)


text:
Q: How to use Nuget with more than one solution I have  a number of solutions which share the same projects in different folders, for example,
Common folder
 - common 1
 - common 2
Contracts folder
 - contracts for project A
 - contracts for Project B
Application 1 folder (in this folder I have my solution file)
 - Solution A
 - nuget creates packages folder there
Application 2 folder
 - Solution B
 - nuget creates packages folder there
packages folder( I need this folder at top level, so all projects can reference it)

With this structure Nuget creates two packages folder inside of Application 1 and Application 2
But all of this projects and solutions related to each other, so logically it's better to have only one packages folder.
Is it possible to set in nuget only one folder and use that folder for all solutions?
Or should I structure my solutions and projects another way?

A: You can do this by adding  nuget.config files to each solution with following contents
<settings>
<repositoryPath>..\Packages</repositoryPath>
</settings>

Make sure that they all point to the same folder.
When you make this file, you have to restart Visual Studio to make it use this setting ( or at least close and open the solution).
But more practical would be to create just one nuget.config that all solutions make use of.  Just make sure it resides on a folder higher then any solution file you wish to include. When restoring, the nuget manager searches for this file, starting from next to the solution file and if not found, start looking higher up the folder structure.

A: Sharing a repository between 2 solutions isn't really possible, as if you update a package in solution A the projects in solution b won't be updated unless they're also in solution A (and may have their package automatically deleted because solution A doesn't use them anymore). Basically meaning having 2 solution files is redundant or you're going to break the other solution with no way of knowing.
How are the solutions related to each other? Maybe there's another way to solve the problem if we have a bit more information.


text:
Q: How to add aggregions for KNN search in elasticsearch? I want to use aggregations over the search result of the knn_search api in elasticsearch (because I need facet search on the user interface), but I cannot pass the agg parameter as in the search api. Any suggestions?

A: Tldr;
As per the documentation of this endpoint GET /<index>/_knn_search.
You just can not give the parameter agg.
In 8.4
Although in the latest version of elasticsearch, you can use the knn search in the standard search queries.


text:
Q: Xcode 5 Unsupported Configuration: maximum size is smaller than its content rectangle size I am getting 2 warnings with a Table View on my mac osx application. They are both "Unsupported Configuration: maximum size is smaller than its content rectangle size (May result in unexpected runtime behavior)." I have tried "reset to suggested constraints" in the editor, but that doesn't do anything. Does anyone have any suggestions?

A: The only thing I know of that has a "maximum size" is NSWindow. Did you look at the geometry inspector for the window in the XIB file?


text:
Q: How to best setup a recruitment model I was just wondering what would be the best setup for a recruitment model in django?
A user can be recruited by just one user, but the user itself could have recruited many other users.
Is it as simple as:
class Recruiter(models.Model):
    recruiter = models.ForeignKey(settings.AUTH_USER_MODEL)

class Recruited(models.Model):
    recruited = models.ForeignKey(settings.AUTH_USER_MODEL)

class UserProfile(AbstractUser):

    recruited_by = models.ForeignKey(Recruiter, blank=True)
    recruited = models.ManyToManyField(Recruited, blank=True)

    objects = UserManager()

Or is it a better way of doing this?

A: What are you trying for?
I would do that:
class UserProfile(AbstractUser):

    recruited_by = models.ForeignKey("self", blank=True, related_name="recruited")

    objects = UserManager()

Are Recruiter and Recruited classes necessaries?

A: I would do it this way:
class Recruiter(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)

class Recruited(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    recruited_by = models.ForeignKey(Recruiter)

Since every Recruiter is a User and every Recruited is a User, but one Recruited is recruited by one Recruiter and one Recruiter can have recruited 0 to many Recruiteds. In this schema, there is implicit backward relation from Recruiter instance accessed like:
 recruiter_instance.recruited_set

Just see the docs:
https://docs.djangoproject.com/en/1.4/ref/models/fields/#django.db.models.ForeignKey
https://docs.djangoproject.com/en/1.4/topics/db/queries/#backwards-related-objects
https://docs.djangoproject.com/en/1.4/ref/models/fields/#onetoonefield
If you are using different Django version, you can use version switch - it's on every Django docs page in the bottom right corner.


text:
Q: Testing welcome paragraph to equal to "welcome" instead of empty string I am using jest, jsdom and testing-libray/dom to test this page (index.html). i expect paragraph to be  "welcome" but i am getting empty string ("") because a page (index.html) is loading before javascript.
I would like to ask if there are other ways to do it. thanks.
this is how my code looks like.
index.html

index.test.js
const { getByTestId } = require("@testing-library/dom");
const { JSDOM } = require("jsdom");
require("@testing-library/jest-dom/extend-expect");
const path = require("path");
const fs = require("fs");
let dom;
let container;

const html = fs.readFileSync(path.join(__dirname, "./index.html"));

describe("index", () => {
  beforeEach(() => {
    dom = new JSDOM(html, { runScripts: "dangerously" });
    container = dom.window.document.body;
  });

  it("should display welcome text", () => {
    const pEl = getByTestId(container, "paragraph");

    expect(pEl.textContent).toEqual("welcome");
  });
});

screenshoot
enter image description here
thanks


text:
Q: PHP: year when a date occurs the next time I need a function that returns the year when a given date (day + month) occurs the first time from now on.
function year($day, $month) {
  // ...
  return $year;
}

$day and $year are two-digit numbers
E.g. the given date is '12/25' it should return '2016' (or '16'), but if the date is '02/25' it should return '2017' (or '17').
[Today is August 30, 2016]
Leap years may be disregarded and input doesn't have to be validated.
EDIT:
My attempt
year($day, $month) {

  $today_day = date('d');
  $today_month = date('m');

  $year = date('y');

  if($month > $today_month) {
    return $year;
  } else if ($month < $today_month) {
    return $year + 1;
  } else {
    if($day >= $today_day) {
      return $year;
    } else {
      return $year + 1;
    }
  }

}

A: Just compare the date you are checking against today. If it is today or earlier increment the year of the date. Otherwise do not. Then return that year.
DateTime() functionality makes this easy to do.
function year($day, $month) {
  $date  = new DateTime("{$month}/{$day}"); // defaults to current year
  $today = new DateTime();
  if ($date <= $today) {
      $today->modify('+1 year');
  }

  return $today->format('Y');
}

echo year(6, 6); // 2017
echo year(12, 12); // 2016

Demo

A: I appreciate your effort! It was pretty good, but can certainly use some fine tuning. We could reduce the no. of unnecessary if statements.
The function accepts two parameters: month and date. Please be sure we follow the order while calling the function.
In the function, $date is the input date concatenated with the current year.
E.g: year(12,25) refers to the year where month is December (12) and day is 25.
year(12,25) would make $date as 2015-12-25.
 function year($month, $day)
 {
     $date= date('Y').'-'.$month.'-'.$day;
     if (strtotime($date) > time()) {
         return date('y');
     }
     return (date('y')+1);
 }

 echo year(12,25);   // 16

 echo year(2,25);    // 17

Now, all we need to do is check the timestamp of $date with the current timestamp- time().
strtotime($date) > time() input date timestamp is more than current timestamp. Which implies this date is yet to come in this year. So, we return the current year date('Y').
If the above if is not executed, it's obvious that this date has passed. Hence we return the next year  date('Y') + 1.


text:
Q: Will my AWS storage be wiped after a reboot? I'm hosting a website on a simple Ubuntu 14.04 AWS instance. It works pretty good, but I'm running out of space, so I need to expand the storage space. For this I first want to get comfortable with a pretty basic thing: rebooting/stopping/starting. On any normal linux box I would simply do sudo reboot, but on this page I read a line saying:

When you stop an instance, the data on any instance store volumes is erased.

As far as I understand, this has something to do with wether you use EBS or not. The only thing the instance details say about this is the following:
EBS-optimized: False
Root device type: ebs

But so far I'm kinda confused. Why would the data on the instance be erased? Isn't it a regular linux installation which persists after a reboot? All tips are welcome!

A: For on-demand/reserved instances:
No. Stop a instance will not delete the EBS volume.
AWS will delete the EBS when you terminate the EC2 instance.
Instance Store is a different type of storage:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html

A: As you have mentioned that your Root Device is of type ebs, so your data will not be wiped after a reboot but will be after termination because by default all ebs volumes got deleted after the termination of instance to which it was attached., But you can also configure not to delete on termination.
Data on ephemeral storage is not persistant.


text:
Q: Openrowset function failure I'm executing this openrowset function:
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0;Database=C:\Users\JCPABALAN\Desktop\Data Migration\ListOfDiscards.xlsx;HDR=YES',
    'SELECT * FROM [Sheet1$]')

But it gave me the following error

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "The Microsoft Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet1$' is not a local object, check your network connection or contact the server administrator.".
  Msg 7350, Level 16, State 2, Line 1
  Cannot get the column information from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

I have already set the Ad Hoc Distributed Queries into 1 and I Installed Microsoft ACE and also executed this line of code:
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

But it still won't work.

A: You Error message has two parts :

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "The Microsoft Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet1$' is not a local object, check your network connection or contact the server administrator.".

And

Msg 7350, Level 16, State 2, Line 1
  Cannot get the column information from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

That the second part is because of error of first part, So your main error is at first part, that tells us:

The Microsoft Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet1$' is not a local object, check your network connection or contact the server administrator.

Some common causes and solutions are these:

*

*Path not exists : File or Path C:\Users\JCPABALAN\Desktop\Data Migration\ListOfDiscards.xlsx is not exist;

Note : SQL Server C:\ is referring to the \\Server\C$, So if you are using SSMS and you register a Server and are connecting to it, your path is not exist.

*

*File permission is denied : File or Path C:\Users\JCPABALAN\Desktop\Data Migration\ListOfDiscards.xlsx have security level that you can access them from SQL Server service account, You can grant access to SQL Server service account.

*Sheet Name is invalid : Worksheet Sheet1 is not a valid sheet name in your workbook sheets, You maybe change its name.


text:
Q: Why do clouds have well-defined boundaries? Why do cumulus clouds have well defined boundaries? In other words, what are the physical mechanisms that hold a cloud together, as an entity separate from other clouds, that prevent it from spreading, etc.
Naively, one could expect the atmospheric vapour to spread homogeneously or (in presence of nonlinearities inherent in hydrodynamics) form periodic structures or even vortices - these are indeed observed (see, e.g., horizontal convective rolls), but does not seem to explain the cumulus clouds. Dust clouds in outer space, held together by gravity seem closer phenomenologically, but physically gravity seems as a less plausible explanation than fluid/gas dynamics

A: Cumulus clouds are opaque (optically thick). The interior of a large cloud is very dark (as you've experienced if you've flown through one in an airliner in the daytime during ascent or descent). When you view a cloud from outside, the white scattered light you see comes from the outer layer of the cloud where sunlight can reach.
Starting from the outside, as the droplet density increases heading into the cloud, the scattered intensity becomes greater and greater, until so much light has been scattered out that the remaining inward-bound light is significantly attenuated. Around this point, the scattered intensity reaches a maximum and then quickly dies out. Even if the droplet density continues to increase toward the center of the cloud, this does not contribute to the cloud's brightness.
(This is also why sunlit cumulus clouds are very bright -- they scatter nearly all of the incident sunlight, similar to an ordinary bright-white diffusely reflecting object, like a sheet of paper.)
When viewing a cloud from outside, you see mainly the "skin" at the depth of maximum scattering. Thus, you see a nearly uniform brightness on any line of sight that intersects this skin, despite potentially large variations in depth and density under the skin. As your line of sight starts to miss the skin, the brightness you see decreases along with the droplet density; if this occurs over a distance that is small compared to the size of the cloud, it will appear as a sharp boundary.

A: I just want to expand on Anders's otherwise great answer, because I think based on the text of the question this paragraph is more what you're asking for:

There are doubtless other forces keeping cumulus clouds sharp, like the upper boundary often corresponding to the top of an upwelling convective flow into drier air and hence having a strong vapour gradient, and the cloud base being set by temperature, pressure and the dew point.

What the layperson needs to understand about a cloud, is that it is not like a rock with a defined set of grains/crystals in a fixed configuration. It is more like a river or a waterfall. Stuff is coming in one end and going out the other.
At the bottom you have moist air coming upwards, where the water inside is fully vaporized and so is transparent. But the pressure is dropping and so is the temperature, and at a particular virtual boundary which is the flat bottom of the cloud, this vaporized water condenses into little droplets. Those droplets are visible now.
All of the little droplets that you are seeing in the cloud are drifting, and on average they are drifting upwards.
Partly this is driven by outside factors, different masses of air moving across the landscape collide and one of them shifts upwards while the other one burrows underneath. But it is also self-sustaining. As a consequence of condensing, droplets release heat which warms the air which expands it. The warm air rises and drags the droplet with it upwards. Because the flows involved are way slower than the speed of sound, the air behaves approximately as an incompressible fluid. That just means that if there is this sudden updraft from the condensation warming the air, then air gets sucked in from the bottom to prevent a vacuum. (Incompressible also means not expandable, the vacuum can be interpreted as "stretching out the air" and at lower velocities air doesn't like to stretch.)
Eventually the droplet leaves the moist air that it is in. If it leaves out of the sides of the cloud, or the bottom, it may re-evaporate. On the other hand if it leaves out of the top of the cloud, which usually requires some pretty considerable convective wind transport, then it may get to the upper atmosphere where it can spontaneously freeze into "diamond dust", tiny little flecks of supercooled ice. These are cirrus clouds, and they look a lot more fuzzy and flowy. A cumulus cloud that does this with those strong convective currents is a cumulonimbus cloud, a rain cloud. They have a characteristic anvil-like shape from the diamond dust top spreading out while the bottom is so firm and solid. (And the rain comes of course from the super-cooled ice crystals coming back down into the cloud, growing into big snowflakes, falling out of the cloud, and melting into raindrops.)
If you've been out on a foggy day then you have walked around in a cloud before, they do not have extremely sharp boundaries when you are up close in person. But, these very common cumulus clouds have this distinctive flat bottom and puffy top because those represent properties of the surrounding air where the droplets are appearing and disappearing. The bottom is flat because the dominant temperature and pressure gradient is vertical, the top is poofy with a sharp-looking boundary because you are looking at this boundary where this moist air mass from below collides with a dry air mass which it is pushing, roiling, bubbling into. The droplets at the one boundary are either turned away or evaporated into the dry air, the droplets at the other boundary are formed and are pulling more moist air up after them.

A: Clouds are fuzzier than they look.
Clouds get their white colour from Mie scattering of light from water droplets of size comparable to the wavelength of light. But for smaller droplets Rayleigh scattering is the best approximation. The formula for the intensity of that radiation seen by an observer at distance $R$, scattering angle $\theta$, wavelength $\lambda$ from a particle of refractive index $n$ with diameter $d$ is
$$
I=I_0 \left(\frac{1+\cos^2\theta}{2R^2}\right)\left(\frac{2\pi}{\lambda}\right)^4\left(\frac{n^2-1}{n^2+2}\right)^2\left(\frac{d}{2}\right)^6
$$
Note the last term: the scattering intensity increases with the sixth power of the diameter. That means that as the vapour density increases in the air and droplets start forming, even a completely smooth gradient of droplet sizes will look like it has a sharp edge where the scattering goes from minuscule to dominant.
Once droplets are $\sim 10$% of the light wavelength the full Mie theory is needed, but the effect is roughly the same (and less wavelength dependent).
There are doubtless other forces keeping cumulus clouds sharp, like the upper boundary often corresponding to the top of an upwelling convective flow into drier air and hence having a strong vapour gradient, and the cloud base being set by temperature, pressure and the dew point.

A: Convection in meteorology is often assumed to be more or less adiabatic, and convection is what creates cumulus clouds. You can imagine clouds as bubbles rising inside a water tank, they also have a quite well defined boundary. Warm humid air rises up, cools (reduction of pressure) and condensation begins.
https://en.wikipedia.org/wiki/Cloud#Adiabatic_cooling
https://en.wikipedia.org/wiki/Lapse_rate#Dry_adiabatic_lapse_rate
Furthermore the wind in the upper atmosphere is less turbulent than wind close to the ground. The clouds are advected by the general motion of the wind. So the warm humid air bubble which rose up stays together. With strong shear winds clouds some times get thorn apart.
To add to the question, there are cumulus clouds that look fuzzy as well. For example the Pileus cloud phenomenon.
https://en.wikipedia.org/wiki/Pileus_(meteorology)#/media/File:Sarychev_peak_eruption.jpg
Edit: To add to your question about periodic structures. There are periodic clouds. They are created by gravity waves in the upper atmosphere.
https://www.antarctica.gov.au/site/assets/files/51703/07-clouds_chris-wilson.1600x900.webp


text:
Q: Java 17 gradle 7.3.3 Intellij Cannot cast org.gradle.api.file.Directory to java.io.File I am migrating project from Java 8 to newer version.
I am not using module info.
springBootVersion=2.5.7
springCloudVersion=2020.0.5

I have an error in Intellij during build:
Cannot cast object 'property(org.gradle.api.file.Directory, undefined)' with class 'org.gradle.api.internal.file.DefaultFilePropertyFactory$DefaultDirectoryVar' to class 'java.io.File'
* Exception is:
com.intellij.openapi.externalSystem.model.ExternalSystemException: Cannot cast object 'property(org.gradle.api.file.Directory, undefined)' with class 'org.gradle.api.internal.file.DefaultFilePropertyFactory$DefaultDirectoryVar' to class 'java.io.File'

This issue occurs while using gradle-7.3.3,
when changed to gradle-7.4 issue changes to:
Cannot query the value of this property because it has no value available.

On gradle 7.3 the issue is:
class org.gradle.api.internal.file.DefaultFilePropertyFactory$DefaultDirectoryVar cannot be cast to class java.io.File (org.gradle.api.internal.file.DefaultFilePropertyFactory$DefaultDirectoryVar is in unnamed module of loader org.gradle.internal.classloader.VisitableURLClassLoader @6a4f787b; java.io.File is in module java.base of loader 'bootstrap')
class org.gradle.api.internal.file.DefaultFilePropertyFactory$DefaultDirectoryVar cannot be cast to class java.io.File (org.gradle.api.internal.file.DefaultFilePropertyFactory$DefaultDirectoryVar is in unnamed module of loader org.gradle.internal.classloader.VisitableURLClassLoader @6a4f787b; java.io.File is in module java.base of loader 'bootstrap')

I think the issue comes from this gradle block (idea part) that worked fine before:
afterEvaluate {
    contracts {
        baseClassForTests = "(...).contract.ContractBaseSpec"
        basePackageForTests = '(...).contract.tests'
        //targetFramework = TestFramework.SPOCK some other error here
        testMode = 'EXPLICIT'
        baseClassMappings {
            baseClassMapping('.*event.*', '(...).contract.EventContractBaseSpec')
        }
    }

    idea {
        module {
            testSourceDirs += project.contracts.generatedTestSourcesDir
            generatedSourceDirs += project.contracts.generatedTestSourcesDir
        }
    }
}

After commenting it - build is ok.
Intellij 2022.1 EAP,
the same in 2021.3.2.
Java version setting in IntelliJ's Project setting does not make difference, I tried both: java 11 and java 17.
The same with build tools - gradle JVM java version setting.
As of https://docs.gradle.org/current/userguide/compatibility.html
Java 17 is compatible from gradle 7.3.
Running from terminal and from jenkins i see other issue:
sdk use java 17.0.2-open

Using java version 17.0.2-open in this shell.

 ./gradlew --version

------------------------------------------------------------
Gradle 7.3
------------------------------------------------------------

 ./gradlew clean build

Issue:
 > BUG! exception in phase 'semantic analysis' in source unit '(.some-path-here...)/contract/ClientBuilder.groovy' Unsupported class file major version 61

Stacktrace: https://pastebin.pl/view/1449e795
in gradle:
jacoco {
    toolVersion = "0.8.7"
}

as for this issue updating groovy from 3.0.3 to 3.0.9 fixes it and shows another issue.
Still why IntelliJ shows different issue?


text:
Q: Swift 1.2 segmentation fault on compile of Release scheme I've just upgraded to Swift 1.2 and when I attempt to compile the iOS application using the Release scheme I receive a "segmentation fault: 11".
0  swift                    0x00000001105a9a08 llvm::sys::PrintStackTrace(__sFILE*) + 40
1  swift                    0x00000001105a9ee4 SignalHandler(int) + 452
2  libsystem_platform.dylib 0x00007fff9a724f1a _sigtramp + 26
3  libsystem_platform.dylib 0x00007fff4fd6f6b0 _sigtramp + 3043272624
4  swift                    0x00000001100e837a (anonymous namespace)::DCE::markControllingTerminatorsLive(swift::SILBasicBlock*) + 346
5  swift                    0x00000001100e8109 (anonymous namespace)::DCE::markValueLive(swift::ValueBase*) + 201
6  swift                    0x00000001100e791f (anonymous namespace)::DCE::run() + 1983
7  swift                    0x000000011008f55e swift::SILPassManager::runFunctionPasses(llvm::ArrayRef<swift::SILFunctionTransform*>) + 1310
8  swift                    0x000000011008ffe9 swift::SILPassManager::runOneIteration() + 633
9  swift                    0x000000011008ea56 swift::runSILOptimizationPasses(swift::SILModule&) + 790
10 swift                    0x000000010fe92ee7 frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 4695
11 swift                    0x000000010fe91ae6 main + 1814
12 libdyld.dylib            0x00007fff995665c9 start + 1

The application compiles and runs perfectly when I use the Dev/Debug scheme.
I have narrowed the compiler issue down to a single file and a couple lines of code.
let directPhoneType = PhoneNumber.Codes.Contacts["D"]
phoneTypes = phoneTypes.filter { $0 != directPhoneType }

I've tried changing the filtering code around (using "element in", etc), but each attempt causes the segmentation fault still. There is other filtering logic throughout our application that compiles fine.
If I remove the filtering code or change it to a loop that manually filters the phone types, the Application runs fine in the Release scheme.
I've tried setting the optimization level to "Fastest, Unchecked" or "Fastest", the segmentation fault still occurs. If I set the optimization level to "None"; the project builds.
This code worked fine before Swift 1.2 in both schemes.
Anyone have any insight into what is going on here?
UPDATE: It looks like Xcode 6.3.1 has fixed my seg fault issues.

A: Ran into the same problem, without having code similar to yours. Turning off whole module optimization (which is off by default) solved the issue for me, meaning I'm still able to archive with fastest optimization settings.

A: Unfortunately we have these sorts of issues all the time. The fault is not with you and they are frustratingly difficult to track down. Usually somewhat arbitrary code changes eventually solve things.
Various superstitions we have developed include: reducing use of unowned where possible, reducing use of weak where possible, being cautious of the ?? operator, being cautious of "too much" stuff in one line (like max(min(x,y),z)), switching let to var, etc.
In your code I might try switching your let to a var, or try removing the filter and doing an old school
var resultList = [MyType]()
for type in phoneTypes {
     if type != directPhoneType {
         resultList.append(type)
     }
}

or change PhoneNumber.Codes.Contacts["D"] to access that differently.
Good luck! Happy hunting.

A: I had this problem when switching to Swift 1.2 and not just for release scheme. While migrating, I had changed a recommended "as!" to "as?" thinking that it was what I wanted. That seems to have caused the problem; I went back and changed to "as!" and it worked.


text:
Q: Getting access to $(this) in jQuery's .on() data object? I am using .on() to add listeners a few items in my DOM - one input range field, and a number of blocks with the class .colorBlock. These event listeners only need to be active intermittently, and I would like to turn them .off() when they are not in use. Doing this means using a named function instead of an anonymous one.
So fair enough, except that I need to pass data into the callback functions. I know I can use the second (third?) argument field to pass in an object to the event, which is readable in the callback, but doing so seems to be scoping this to the event, instead of to the DOM node that .on() was listened on. See below for example:
$('#brushSize').on('touchend', { size: $(this).val() }, utils.setBrushSize);
$('.colorBlock').on('touchstart', { color: $(this).data('color') }, utils.setColor);

In my callback functions, I added an alert for e.data.color and e.data.size, and both call out undefined.
To make matters worse, this is a phone gap app, so I am limited in my options to trace what is getting passed around, so some of what I am assuming could be wrong about what is going on.
Any suggestions?
Thanks.

A: Let's break down this line:
$('#brushSize').on('touchend', { size: $(this).val() }, utils.setBrushSize);

It's exactly the same (other than the variables) as this:
var sizeValue = $(this).val();
$('#brushSize').on('touchend', { size: sizeValue }, utils.setBrushSize);

E.g., you're calling $(this).val(), and then passing the result of calling it in as part of your data object. So unless this is already what you want to get the value from at that point, it's not going to work.
If you want to get some information from the element when the event happens, just put that code in your event handler. For example, looking at this line:
$('.colorBlock').on('touchstart', { color: $(this).data('color') }, utils.setColor);

It looks to me like you're trying to get the color from the .colorBlock element that was touched. If so:
$('.colorBlock').on('touchstart', function() {
    utils.setColor($(this).data('color'));
});

Or if you're going to reuse it:
utils.setColorFromEventElement = function() {
    utils.setColor($(this).data('color'));
};

and
$('.colorBlock').on('touchstart', utils.setColorFromEventElement);

Side note:
There's also a possible second problem with that line. You're using utils.setBrushSize as the event handler. Note that within the call to setBrushSize, this will refer to the DOM element on which you hooked the event, not utils. Now, given the name utils, maybe that doesn't matter, but I thought I'd mention it.
More: Mythical methods, You must remember this

A: The value you're sending in the arguments object is always going to be the number it was when you called the .on() statement. That function's not going to be dynamically re-called every time the event fires.
Personally I think it's really ugly to have the util class go looking for some DOM element and get its value, when as you alluded, what you really want to do is have your util function run in the same scope as the .on() statement.
Your first instinct was probably correct. You don't want an anonymous function, because you want to be able to call off(). Ideally you want a named function that runs in the same scope as the thing that calls the on() statement. So what you want to do is bind the util function to your current scope:
$('#brushSize').on('touchend', utils.setBrushSize.bind(this));

Then in utils.setBrushSize, $(this) is whatever function you called .on() from.
edit Just a warning on this though: when you call off(), you want to call it like this:
$('#brushSize').off('touchend', utils.setBrushSize);

Not on a new scope-bound version of setBrushSize. JQuery should recognize it as equal to the original function you bound and turn it off.
re-edit I'm realizing now that your val() is in $('#brushSize') as that's the "this" you're trying to call... not the function holding the on statement. In that case you can do it this way:
$('#brushSize').on('touchend', utils.setBrushSize.bind($(this)));

A: So the solution for this particular problem ended up requiring that I strip this bit of code out of Phone Gap and rebuild it in a browser. I was then able to console.log the event that was being sent to the callbacks, and examine them to understand the event object better.
The solutions was to use event.target. This allowed to get the event.target.dataset.color for the .colorBlock listener, and event.target.value from the brushSize range listener.
So for future me, I would be good to have a solid working version of my app in the browser with the phone gap stuff stripped out, to do better testing for problems like this.


text:
Q: Initializing Python class object with external data Suppose a "person" class contains name, age and phone number.
When creating a person object, I would like to set phone number by looking up an external phone book rather than explicitly passing a phone number.
Option 1: Store phone book as a class variable
class person():

    phonebook = {}

    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.phone = self.phonebook[self.name]

person.phonebook = {'dan':1234}
dan = person('dan', 30)

Option 2: Create a class object without phone number then have a separate function to load it.
class person():

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def loadphone(self, phone):
        self.phone = phone

phonebook = {'dan':1234}
dan = person('dan',30)
dan.loadphone(phonebook['dan'])

Both solutions do not seem optimal. Option 1, every person carries a phone book (unnecessarily). Option 2 requires 2-step initialization.
Is there a better way to create a person object without 1) explicitly passing a phone number or phone book during initialization, 2) storing phone book as a class variable, and 3) requiring a multi-step initialization?

A: As discussed in this post, defining a variable outside of any methods in the class, while still being defined in a class makes it a static variable, such as the one you have:
class person():

    phonebook = {}

This means that there is a single phonebook which all instances of the class refer to
person.phonebook{'dave':1234, 'joey':5678}

dave = person('dave', 30)
joey = person('joey', 23)

There is still only the one universal phonebook that all instances refer to. The one thing to change in that code is that you should not define it as self.phonebook['dave'] so it should look like
class person():

    phonebook = {}

    def __init__(name, age):
        self.name = name
        self.age = age
        self.number = phonebook[name]

A: Are you wanting to optionally define a phone number for a Person? You could do something like below:
class Person():
    def __init__(self, name, age, phone=None):
        self.name = name
        self.age = age
        self.phone = phone

dan = Person('dan',30, phone=1234)
stan = Person('stan', 60)

A: Firstly, as for me, it's too wide question and very depend on task. In one case you can access to PhoneBook, in another - it's bad idea (e.g. PhoneBook load data from server and creating 1000 of Person will produce 1000 requests).
Secondary, their is next approach:
class BasicPerson():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def ToString(self):
        return('some code')

class PersonWithPhone():
    def __init__(self, basicPerson, phone):
        self.basicPerson = basicPerson
        self.phone = phone

    def ToString(self):
        return('another code ' + self.basicPerson.ToString())

person = PersonWithPhone(BasicPerson('', ''), '11111')

It's just example and may seems useless, but in many situations you can extract some core actions (ToString, for example) and than wrote small decorators that expand each other.


text:
Q: GXT Grid with multiple CheckBoxCell with listener I'm using GXT 3.0 and have a Grid with multiple checkboxes each row. These checkboxes reflect certain properties of my row data and checkin/unchecking does not implies selecting/unselecting the particular row. How can I add a listener to each checkbox and perform some action upon clicking it?

A: I override the handlesSelection() method to capture the check/uncheck event
CheckBoxCell checkCol = new CheckBoxCell() {
    @Override
    public boolean handlesSelection() {
        //TODO:
        return true;
    }
};

A: Add some CheckBoxSelectionModel for each checkbox
IdentityValueProvider<Stock> identity = new IdentityValueProvider<Stock>();
SpecialRowClickCheckBoxSelectionModel<Stock> sm =
   new SpecialRowClickCheckBoxSelectionModel<Stock>(identity);

public class SpecialRowClickCheckBoxSelectionModel<M>
     extends CheckBoxSelectionModel<M> {

  public SpecialRowClickCheckBoxSelectionModel(
         IdentityValueProvider<M> identity) {
    super(identity);
  }

  @Override
  protected void handleRowClick(RowClickEvent event) {
       M model = listStore.get(event.getRowIndex());
       //TODO
  }
}


text:
Q: MongoDB uses COLLSCAN when returning just _id I want to return all IDs from a MongoDB collection and I used the code below:
db.coll.find({}, { _id: 1})

But MongoDB scans the whole collection instead of reading the information from the default index { _id: 1 }.
From the log:
{ find: "collection", filter: {}, projection: { _id: 1 } }
planSummary: COLLSCAN cursorid:30463374118 keysExamined:0
docsExamined:544783 numYields:4286 nreturned:544782 reslen:16777238
locks:{ Global: { acquireCount: { r: 8574 } }, Database: {
acquireCount: { r: 4287 } }, Collection: { acquireCount: { r: 4287 } }
} protocol:op_query 7024ms

Any idea how to fix this, please?

A: You would need to add a filter that can use this index like so in order to change that query plan - not all operations remove the FETCH stage, e.g. $exists does not appear to work:
db.coll.find({ _id: { $ne: 0 }, { _id: 1 }) // works for ObjectIds

One part of the explanation for this is in the documentation:

A covered query is a query that can be satisfied entirely using an
  index and does not have to examine any documents. An index covers a
  query when both of the following apply:

*

*all the fields in the query are part of an index,

*and all the fields returned in the results are in the same index.

I seem to remember seeing a JIRA request to support that without the filter but cannot remember which ticket that was...

A: I have found a solution, which works if one knows the type of the _id field. In case of string _id:
db.coll.find({ _id: { $regex: ".*" }, { _id: 1 })

In case of integer _id:
db.coll.find({ _id: { $gte: 0 }, { _id: 1 })


text:
Q: Extract one year from a period of time involving two years in R I need to extract a year corresponding to a time period and put it into a new column in a data frame. The tricky part is that the years I need to extract are not calendar years. My 'standardized' years start the 1st of July of a given calendar year and end up the 30th of June of the subsequent calendar year. So, if an event occurred anytime within this time period, the standardized year is the first calendar year in this time period involving two calendar years. For example, if events occurred the 1st of July 2019, the 25th of December 2019, and the 30th of June 2020, the 'standardized' year for all these three events is 2019 (i.e. the first year within the time period between 1st of Jul 2019 and 30th June 2020). How can I extract such standardized years in R and assigned it to a new column in the data frame?
My data file is very large, but as a simplified example, here are some events happening in specific dates
dat <- as.Date(c("2-Feb-18", "24-May-10", "30-Dec-19","1-Jul-20"),"%d-%b-%y")
dat <- as.data.frame(dat)
names(dat)[1] <- "events"
dat
      events
1 2018-02-02
2 2010-05-24
3 2019-12-30
4 2020-07-01

In this case the column I want to create 'standardized_year' should look like this
      events standardized_year
1 2018-02-02              2017
2 2010-05-24              2009
3 2019-12-30              2019
4 2020-07-01              2020

In the first row, the standardized year is 2017 because 2-Feb-18 is within 1st of Jul 2017 and 30th Jun 2018, so the first year is extracted within the 'standardized' year. The same criteria for all other values.
Is there a way to do this automatically in R for a large amount of  events in a dataframe?
Any help would be much appreciated. Thanks

A: You could extract the actual year from first four substrings, then compare if it is smaller than all dates of the standardized year starting in the actual year. The standardized year we get from sequences with ISOdate.
standardized_year <- sapply(dat$events, function(x) {
  x <- as.POSIXct(x)
  y <- as.numeric(substr(x, 1, 4))
  ifelse(all(x < seq(ISOdate(y, 7, 1, 0), ISOdate(y + 1, 6, 30, 0), "day")), y - 1, y)
})
dat <- cbind(dat, standardized_year)
dat
#       events standardized_year
# 1 2018-02-02              2017
# 2 2010-05-24              2009
# 3 2019-12-30              2019
# 4 2020-07-01              2020

A: I guess you can do something likes  this:
library(dplyr)
library(lubridate)

events <- events %>%
     mutate(events = dmy(events),
           standardized_year = ifelse(month(events)>=7, year(events), year(events)-1))


text:
Q: Can't change role name when I create a role using discord.js I'm using the following code:
message.guild.roles.create({
    data: {
        name: "test",
        color: 'BLUE'
    },
    reason: 'Bid created',
});

to create a new role with discord.js v13, but the role name doesn't change to "test", it remains at "new role".

A: Discord.js v13 no longer needs a data object for RoleManager#create (changelog) :
message.guild.roles.create({
    name: "test",
    color: 'BLUE',
    reason: 'Bid created'
});


text:
Q: Zookeeper backed shared map (small KeyValue storage) I have bunch of Hadoop MapReduce applications (jobs) that need to share some 'living' small key-value storage. Actually it is about string ID being generated based on some string criteria during the progress of the job.
So it looks like shared Map<String,String> which can be modified and values are shared among MapReduce job components (mappers in my case but it does not matter).
Approach I see as visible is Apache ZooKeeper. I already have this service available on my Hadoop cluster. What I need in this case is reliable ZooKeeper-powered KeyValue storage. Currently I see it as one of declared applications but I don't see good implementation. Any suggestion? I see I need ephemeral node in this case (as MapReduce job has limited life time).
What I have found as best option currently is Curator framework which contains SharedValue class which looks like what I need. But I don't see any example of using it either in recipes or examples. Any example?
Any other good implementation approach or ready out-of-the-box solution for this problem?
Thank you in advance.


text:
Q: How to have a circular inner shadow for canvas shape? In my canvas, I have a circle shape that moves with cursor.
I am trying to give this a little inner shadow, but it does not work.
Here is the code and demo : JSFIDDLE
function writeMessage(canvas, message, x, y) {
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);

    var pattern = context.createPattern(imageResized, 'no-repeat'); //Use imageResized, not imageObj.
    context.fillStyle = pattern;
    context.fill();

    context.font = '28pt Calibri';
    context.fillStyle = 'white';
    //context.fillText(message, x, y);
    context.beginPath();
    context.arc(x, y, 50, 0, 2 * Math.PI);
    context.stroke();

    context.beginPath();
    context.lineWidth = 5;
    context.shadowColor = 'black';
    context.strokeStyle = "rgba(0,0,0,1)";
    context.shadowBlur = 15;
    context.shadowOffsetX = 0;
    context.shadowOffsetY = 0;
    context.arc(x, y, 50, 0, 2 * Math.PI, false);
    context.stroke();
    context.restore();

}

I notice this settings would work if I add context.clip(); but then it would make the whole canvas crash.
Any idea to have an inner shadow for this circle ?

A: Try drawing the arc that is to supply the shadow before the arc that supplies the frame. Save the context state before the beginPath and restore it after the stoke of the shadow arc.  You will need to make the shadow arc radius smaller than the frame arc so that the outer edge of the shadow is covered by the stroke of the frameing arc.  The outside shadow that is outside of the shadow arc is still drawn, but covered over by the framing arc.
Example:
context.save();
context.beginPath();
context.lineWidth = 6;
context.shadowColor = 'black';
context.strokeStyle = "rgba(0,0,0,1)";
context.shadowBlur = 15;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.arc(x, y, 47, 0, 2 * Math.PI, false);
context.stroke();
context.restore();

context.save();
context.beginPath();
context.lineWidth = 6;
context.arc(x, y, 50, 0, 2 * Math.PI);
context.stroke();
context.restore();

You will need to adjust the size, color, and line width of the arcs to get the effect you want.

A:
If doing .clip within an busy handler like mousemove is crashing your browser, you can pre-build your circle with inner shadow once at the beginning of your app and then reuse that pre-built circle with little impact on performance.
Here's how to create an in-memory canvas containing your circle with inner shadow. Yes, it uses .clip, but it only uses it once at the beginning of the app.
var PI2=Math.PI*2;
var cut=document.createElement('canvas');
var cutCtx=cut.getContext('2d');
cut.width=100;
cut.height=100;
cutCtx.arc(50,50,50,0,Math.PI*2);
cutCtx.closePath();
cutCtx.clip();
cutCtx.shadowColor='black'
cutCtx.shadowBlur=15;
for(var i=0;i<15;i++){
    cutCtx.stroke();
}

Then it's not very expensive to draw that pre-built circle inside the mousemove event.
Here's example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();

var PI2=Math.PI*2;
var cut=document.createElement('canvas');
var cutCtx=cut.getContext('2d');
cut.width=100;
cut.height=100;
cutCtx.arc(50,50,50,0,Math.PI*2);
cutCtx.closePath();
cutCtx.clip();
cutCtx.shadowColor='black'
cutCtx.shadowBlur=15;
for(var i=0;i<15;i++){
  cutCtx.stroke();
}

ctx.fillStyle='white';
ctx.fillRect(0,0,cw,ch);

$("#canvas").mousemove(function(e){handleMouseMove(e);});

function applyCut(mx,my){
  // hide the background image by whiteing-out the canvas
  ctx.fillRect(0,0,cw,ch);

  // use compositing to "erase" a circle under the mouse
  ctx.globalCompositeOperation='destination-out';
  ctx.beginPath();
  ctx.arc(mx,my,50,0,PI2);
  ctx.closePath();
  ctx.fill();

  // draw the pre-built circle shadow under the mouse
  ctx.globalCompositeOperation='source-over';
  // Hint: the in-memory canvas can be an image source for
  // your on-screen canvas
  ctx.drawImage(cut,mx-50,my-50);
}

function handleMouseMove(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);

  applyCut(mouseX,mouseY);

}
body{ background-color: ivory; }
#wrapper{position:relative;}
#bk,#canvas{position:absolute;}
#canvas{border:1px solid red;}

Move the mouse to reveal the image underneath

  <canvas id="canvas" width=512 height=512></canvas>

A: I've just created Inset.js for this exact situation!
Inset.js
Only requires setting ctx.shadowInset = true;
For example: http://codepen.io/patlillis/pen/RpEoKE
var ctx = canvas.getContext("2d");
var w = canvas.width = window.innerWidth;
var h = canvas.height = window.innerHeight;

// Set up circle styles.
ctx.shadowInset = true;
ctx.shadowBlur = 15;
ctx.shadowColor = 'black';
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.fillStyle = 'red';

// Set up mouse listener.
document.addEventListener('mousemove', function(e) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.arc(e.clientX, e.clientY, 30, 0, 2 * Math.PI);
    ctx.fill();
});


text:
Q: Problem with my program about finding factors This was a continuation to my older question
The program was working fine without the
while True:
    main()
    if input("Try Again? (Yes/No)").strip().upper() == 'No':
        break
but when i added it, the problem rose
I was trying to make the program start by asking the user a number
and it shows a factor then i loop it and ask the user if he wants another number and it repeats if the user wants to repeat it
def main():

 def print_factors(x):
    print("The factors of",x,"are:")
    for i in range(1, x + 1):
    if x % i == 0:
        print(i)

try:
    num = int(input("Enter a number: "))
    print_factors(num)
except ValueError:
    print("Sorry, I didn't understand that.");

while True:
    main()
    if input("Try Again? (Yes/No)").strip().upper() == 'No':
    break

line 12, in <module>
    print_factors(num)
NameError: name 'print_factors' is not defined

when the program is ran this was the end result

A: You defined print_factors inside of main(), meaning it's not a function available to the global scope
Give main() a body, and unindent print_factors() and it should resolve your issues