text:
Q: Convert object to byte[] I am trying to convert a retrieved registry value from object to byte[]. It is stored as REG_BINARY. I tried using BinaryFormatter with MemoryStream. However, it adds overhead information that I do not want. I observed this when I then converted the byte array to a string by performing the function Convert.ToBase64String(..). I am performing these functions because I am testing the storing and retrieval of an encrypted key in the registry.

A: If it's a REG_BINARY then it should already be a byte array when you retrieve it... can't you just cast it to byte[]?
Alternatively, if you haven't already verified that it's REG_BINARY in the code, you may want to use:
byte[] binaryData = value as byte[];
if (binaryData == null)
{
    // Handle case where value wasn't found, or wasn't binary data
}
else
{
    // Use binaryData here
}

A: Try this.  If it already is a REG_BINARY, all you need to do is cast it:
static byte[] GetFoo()
{

  var obj = Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\Software", "foo", null);
  //TODO: Write a better exception for when it isn't found
  if (obj == null) throw new Exception();

  var bytearray = obj as byte[];
  //TODO: Write a better exception for when its found but not a REG_BINARY
  if (bytearray == null) throw new Exception();

  return bytearray;
}

A: If you converted it using Convert.ToBase64String, you should be able to get it out similarly.
string regValueAsString = (string)regValueAsObj;
byte[] buf = Convert.FromBase64String(regValueAsString);


text:
Q: Its possible to the same event overlap in MySQL? I was wondering if its possible to the same event on MySQL overlap its execution:
eg:
I have this event scheduled to execute every 2 seconds:
BEGIN
 DELETE FROM RouteDatabase3.route_fast WHERE TIMESTAMPDIFF(minute, updated_at, now()) > 5;
END

What happens if this event takes 10 seconds? MySQL server will execute the same event overlaping the last one?
Its possible to lock the event execution, so MySQL will execute only one at time?

A: I was able to find a solution using the GET_LOCK and RELEASE_LOCK functions from MySQL,
BEGIN
 IF GET_LOCK('lock', 5) THEN
  DELETE FROM RouteDatabase3.route_fast WHERE TIMESTAMPDIFF(minute, updated_at, now()) > 5;
  SELECT RELEASE_LOCK('lock');
  END IF;
END

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dapper: mapping hierarchy and single different property I really love Dapper's simplicity and possibilities. I would like to use Dapper to solve common challenges I face on a day-to-day basis. These are described below.
Here is my simple model.
public class OrderItem {
    public long Id { get; set; }
    public Item Item { get; set; }
    public Vendor Vendor { get; set; }
    public Money PurchasePrice { get; set; }
    public Money SellingPrice { get; set; }
}

public class Item
{
    public long Id { get; set; }
    public string Title { get; set; }
    public Category Category { get; set; }
}

public class Category
{
    public long Id { get; set; }
    public string Title { get; set; }
    public long? CategoryId { get; set; }
}

public class Vendor
{
    public long Id { get; set; }
    public string Title { get; set; }
    public Money Balance { get; set; }
    public string SyncValue { get; set; }
}

public struct Money
{
    public string Currency { get; set; }
    public double Amount { get; set; }
}

Two challenges have been stumping me.
Question 1:
Should I always create a DTO with mapping logic between DTO-Entity in cases when I have a single property difference or simple enum/struct mapping?
For example: There is my Vendor entity, that has Balance property as a struct (otherwise it could be Enum). I haven't found anything better than that solution:
public async Task<Vendor> Load(long id) {
    const string query = @"
        select * from [dbo].[Vendor] where [Id] = @id
    ";

    var row = (await this._db.QueryAsync<LoadVendorRow>(query, new {id})).FirstOrDefault();
    if (row == null) {
        return null;
    }

    return row.Map();
}

In this method I have 2 overhead code:
1. I have to create LoadVendorRow as DTO object;
2. I have to write my own mapping between LoadVendorRow and Vendor:
public static class VendorMapper {
    public static Vendor Map(this LoadVendorRow row) {
        return new Vendor {
            Id = row.Id,
            Title = row.Title,
            Balance = new Money() {Amount = row.Balance, Currency = "RUR"},
            SyncValue = row.SyncValue
        };
    }
}

Perhaps you might suggest that I have to store amount & currency together and retrieve it like _db.QueryAsync<Vendor, Money, Vendor>(...)- Perhaps, you are right. In that case, what should I do if I need to store/retrive Enum (OrderStatus property)?
var order = new Order
{
    Id = row.Id,
    ExternalOrderId = row.ExternalOrderId,
    CustomerFullName = row.CustomerFullName,
    CustomerAddress = row.CustomerAddress,
    CustomerPhone = row.CustomerPhone,
    Note = row.Note,
    CreatedAtUtc = row.CreatedAtUtc,
    DeliveryPrice = row.DeliveryPrice.ToMoney(),
    OrderStatus = EnumExtensions.ParseEnum<OrderStatus>(row.OrderStatus)
};

Could I make this work without my own implementations and save time?
Question 2:
What should I do if I'd like to restore data to entities which are slightly more complex than simple single level DTO? OrderItem is beautiful example. This is the technique I am using to retrieve it right now:
public async Task<IList<OrderItem>> Load(long orderId) {
    const string query = @"
            select [oi].*,
                   [i].*,
                   [v].*,
                   [c].*
              from [dbo].[OrderItem] [oi]
              join [dbo].[Item] [i]
                on [oi].[ItemId] = [i].[Id]
              join [dbo].[Category] [c]
                on [i].[CategoryId] = [c].[Id]
              join [dbo].[Vendor] [v]
                on [oi].[VendorId] = [v].[Id]
             where [oi].[OrderId] = @orderId
    ";

    var rows = (await this._db.QueryAsync<LoadOrderItemRow, LoadItemRow, LoadVendorRow, LoadCategoryRow, OrderItem>(query, this.Map, new { orderId }));

    return rows.ToList();
}

As you can see, my question 1 problem forces me write custom mappers and DTO for every entity in the hierarchy. That's my mapper:
private OrderItem Map(LoadOrderItemRow row, LoadItemRow item, LoadVendorRow vendor, LoadCategoryRow category) {
    return new OrderItem {
        Id = row.Id,
        Item = item.Map(category),
        Vendor = vendor.Map(),
        PurchasePrice = row.PurchasePrice.ToMoney(),
        SellingPrice = row.SellingPrice.ToMoney()
    };
}

There are lots of mappers that I'd like to eliminate to prevent unnecessary work.

A:
Is there a clean way to retrive & map Order
  entity with relative properties like Vendor, Item, Category etc)

You are not showing your Order entity but I'll take your OrderItem as an example and show you that you don't need a mapping tool for the specific problem (as quoted). You can retrieve the OrderItems along with the Item and Vendor info of each by doing the following:
var sql = @"
select oi.*, i.*, v.*
from OrderItem
    inner join Item i on i.Id = oi.ItemId
    left join Vendor v on v.Id = oi.VendorId
    left join Category c on c.Id = i.CategoryId";
var items = connection.Query<OrderItem, Item, Vendor, Category, OrderItem>(sql,
    (oi,i,v,c)=>
    {
      oi.Item=i;oi.Item.Category=c;oi.Vendor=v;
      oi.Vendor.Balance = new Money { Amount = v.Amount, Currency = v.Currency};
      return oi;
    });

NOTE: The use of left join and adjust it accordingly based on your table structure.

A: I'm not sure I understand your question a 100%. And the fact that no one has attempted to answer it yet, leads me to believe that I'm not alone when I say it might be a little confusing.
You mention that you love Dapper's functionality, but I don't see you using it in your examples. Is it that you want to develop an alternative to Dapper? Or that you don't know how to use Dapper in your code?
In any case, here's a link to Dapper's code base for your review:
https://github.com/StackExchange/dapper-dot-net
Hoping that you'd be able to clarify your questions, I'm looking forward to your reply.


text:
Q: How to convert type String to type File in Flutter I am running a project with flutter-web
This time is first time doing project with flutter-web. and now i just knew that flutter web doesn't supports Dart:io
So i am trying to use dart.html and... it is quite different compare to dart:io
uploadImage(ReservationPvd reservationPvd) async {
    final XFile? photo = await ImagePicker().pickImage(source: ImageSource.gallery);
    File image = File(photo!.path);
    MultipartFile imageFile = await MultipartFile.fromFile(photo.path);
    reservationPvd.updateInfo('image', image);
    reservationPvd.updateInfo('imageFile', imageFile);
  }

this following code is the code that i've used in my other project with flutter.
and I need to save this File to Type File and MultipartFile
File image = File(photo!.path);

and this following code gives an error message, and it says
The argument type 'String' can't be assigned to the parameter type 'List<Object>'

i have googled for a 3 days but i really can't solve this problem...
does anyone knows how to upload fine ways to upload in flutter-web?

A: I suspect your File class may be imported from the wrong dependency. It should use File from dart:io like so:
import 'dart:io';

And it's likely you're currently using dart:html:
import 'dart:html';

Auto import suggests dart:html over dart:io for me as well, so this is the most likely cause I think.

A: to get around dart io not supported in web
after you pick the image instead of File(file.path) you say file.readAsBytes(); the you store the output of file.readAsBytes() in a Uint8List variable. when you want to display the images you use MemoryImage() provided in flutter

A: I have flutter-web project and it use MultipartFile.fromBytes not MultipartFile.fromFile. Because in flutter-web you can't get File from path.
Try this:
uploadImage(ReservationPvd reservationPvd) async {
    final XFile? photo = await ImagePicker().pickImage(source: ImageSource.gallery);

    MultipartFile imageFile = MultipartFile.fromBytes(await photo!.readAsBytes());

    reservationPvd.updateInfo('image', image);
    reservationPvd.updateInfo('imageFile', imageFile);
  }


text:
Q: Is this correct way to write factory and adapter pattern I am trying to use adapter and factory pattern which i am trying to learn but not sure about correct way of using them in real scenario.
Below is one console application for writing log in three difference part.
Thanks in advance.
This is console application
class Program
{
    static void Main(string[] args)
    {
        LogWriterFactory _LogWriterFactory = new LogWriterFactory();

        var data = _LogWriterFactory.SaveData(SaveOption.Database, "Something");
        var email= _LogWriterFactory.SaveData(SaveOption.Email, "Something");
        var text = _LogWriterFactory.SaveData(SaveOption.Text, "Something");

        Console.WriteLine("{0}", data);
        Console.WriteLine("{0}", email);
        Console.WriteLine("{0}", text);
        Console.ReadKey();
    }
}

This is Class Library
public enum SaveOption
{
    Database = 1,
    Email = 2,
    Text = 3
}

public class LogWriterFactory
{
    public string SaveData(SaveOption option, string Log = "")
    {
        LogWriterAdp _LogWriterAdp = new LogWriterAdp();
        string output;
        switch (option)
        {
            case SaveOption.Database:
                IConnector _SendEmailConnector= new SendEmailConnector();
                output = _LogWriterAdp.Write(_SendEmailConnector, Log);
                break;
            case SaveOption.Email:
                IConnector _WriteInDBConnector = new WriteInDBConnector();
                output = _LogWriterAdp.Write(_WriteInDBConnector , Log);
                break;
            case SaveOption.Text:
                IConnector _WriteInTextConnector= new WriteInTextConnector();
                output = _LogWriterAdp.Write(_WriteInTextConnector, Log);
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
        return output;
    }
}

public class LogWriterAdp
{
    public string Write(IConnector Connector, string Log)
    {
        return Connector.Save(Log);
    }
}

public interface IConnector
{
    string Save(string Log);
}

public class SendEmailConnector : IConnector
{
    public string Save(string Log)
    {
        SendEmail _SendEmail = new SendEmail();
        return _SendEmail.Send(Log);
    }
}

public class WriteInDBConnector : IConnector
{
    public string Save(string Log)
    {
        WriteInDB _WriteInDB = new WriteInDB();
        return _WriteInDB.Save(Log);
    }
}

public class WriteInTextConnector : IConnector
{
    public string Save(string Log)
    {
        WriteInText _WriteInText = new WriteInText();
        return _WriteInText.Write(Log);
    }
}

public class SendEmail
{
    public string Send(string Log)
    {
        return "Data From DatabaseHelper " + Log;
    }
}

public class WriteInText
{
    public string Write(string Log)
    {
        return "Data From WebSiteScanner " + Log;
    }
}

public class WriteInDB
{
    public string Save(string Log)
    {
        return "Data From XmlFileLoader " + Log;
    }
}

I am trying to use adapter and factory pattern which i am trying to learn but not sure about correct way of using them in real scenario.


text:
Q: straight-line solutions of dynamical system Given the dynamical system
$\dot x = f(x,y)$ and $\dot y = g(x,y)$
where f and g are homogeneous of degree n (i.e. $G(\alpha x,\alpha y)=\alpha^n G(x,y))$
show that straight line solutions of the form $y(t)=mx(t)$ exist for the system if and only if
$mf(1,m) = g(1,m)$
Starting with a simple example
$\dot x = 2x+y$ and $\dot y = x+y$
Both functions are homogeneous of degree 1 since
$f(\alpha x, \alpha y) = 2\alpha x + \alpha y = \alpha (2x+y) = \alpha f(x,y) $
and
$g(\alpha x, \alpha y) = \alpha x + \alpha y = \alpha (x+y) = \alpha g(x,y) $
If you want straight line solutions, then:
$mf(1,m) = g(1,m)$
$m(2+m) = 1+m$
$m=0.618, -1.618$
Phase portrait of the system showing nullclines and the two straight line solutions y = 0.618x and y=-1.618x
I see how the solutions are generated but how can I go about expressing this more formally for any function that is homogeneous of degree n

A: There are solutions satisfying $y(t)=mx(t)$ if and only if
$$
g(x,mx)=mf(x,mx)
$$
for all $x$. This is because solutions of that form exists if and only if the vector field along the corresponding line has the same direction. Being homogeneous of degree $n$ gives you the equation
$$
g(1,m)=mf(1,m)
$$
after canceling out $x^n$.

A: If a line through the origin
$$t\mapsto p(t)(a,b)$$
is a solution of the given system then
$$\eqalign{\dot x(t)=a\dot p(t)&=f\bigl(p(t)(a,b)\bigr)=p^n(t)F(a,b)\cr
\dot y(t)=b\dot p(t)&=g\bigl(p(t)(a,b)\bigr)=p^n(t)G(a,b)\cr}$$
for all $t$, hence
$$bF(a,b)-aG(a,b)=0\ .$$


text:
Q: Android Studio Error when Creating a Project with a Google Maps Activity When I create a new project in Android Studio with a Google Maps Activity I get the following error when I do the initial build of the project:

Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
      is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
      Suggestion: add 'tools:replace="android:appComponentFactory"' to  element at AndroidManifest.xml:12:5-41:19 to override.

When I add:
tools:replace="android:appComponentFactory
to my AndroidManifest.xml file I get the error below:

Manifest merger failed with multiple errors, see logs

I've found several potential solutions on StackOverflow but none work.
I've tried several potential solutions that I've found on StackOverflow including:

*

*migrating to AndroidX

*Adding the following lines to my
manifest
tools:replace="android:appComponentFactory
android:appComponentFactory="whateverString"

*

*Removing implementation com.android.support:appcompat-v7:28.0.0-rc01
Main Activity code
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

Android Manifest:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/.
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

A: Migrating to androidX should do the trick, add these two flags to your gradle.properties file. Refactor by going to Refactor > Migrate to AndroidX in android studio menu bar
android.useAndroidX=true
android.enableJetifier=true

A: The answer should be tied to AndroidX and making sure you have all support libraries migrated to AndroidX.  This would include design libraries.  I had the same issue and once I migrated them over it worked.  Check out all possible libraries here https://developer.android.com/jetpack/androidx/migrate

A: All you need to do is to update your android studio and you are good to go. I created a new project and it ran fine.


text:
Q: NotAllowedError create_login_url Update3
In desperation I have created a new google appengine app which is identical to the original, even in name, but with a slightly longer ID. The new app has -232619 added to the ID, the original app has the briefer ID. The NEW app works as expected, but the original app produces the NotAllowedError still.
So, in my judgement, the problem is in google's system somehow, but I have not been able to get any human at google to give me a solution that will enable me to keep the original ID of the app. It seems that a human administrator would have to delete my original app named Participoll but somehow let me replace it. Replacing it would be complicated because the app creation system would also have to remove the name Participoll long enough so that I could claim the app name/ID again.
So I have the same app in 2 gae places, both have the EXACT same project name, but slightly different project IDs. The app with the stupid ID works, but no one can help me make the one with the desired ID work. How can this be fixed? I cannot delete the app with the desired ID because I will lose the desired name.
Can someone at google help here, please?
Update3
Update2
Chrome produces different results Safari from Firefox.
participoll.appspot.com produces ApplicationError: 2 on Chrome, and Error: Server Error (500) on both Safari and Firefox.
participoll.appspot.com/admin produces You are an administrator. on Chrome, and You are not logged in. on both Safari and Firefox.
So, it looks like all 3 may be thinking I am an administrator, which I am. But none of the 3 have asked me to login, and I don't know how to force a logout or login request except in Chrome which is attached to google app engine, of course.
Does this give anyone any more ideas what can be going on?
Update2
Update1
More recently, using the "revised" simple app I am getting a different and more descriptive error message, which I show below. The new error refers to create_logout_url instead of create_login_url and the 500 error has disappeared.
Since the original 500 error appeared -- not disappeared as I incorrectly typed, I temporarily commented out the login requests and assigned login_url = 'login_url' and logout_url = 'logout_url'; maybe this made the 500 error disappear. That was encouraging because the 500 error was so un-informative. So, maybe that change temporarily got around some other problem. But now I am getting this new error. (But see below, because Safari browser still has the 500 error.)
    ApplicationError: 2
Traceback (most recent call last):
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
    rv = self.handle_exception(request, response, e)
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
    rv = self.router.dispatch(request, response)
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__
    return handler.dispatch()
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "/base/data/home/apps/s~participoll/1.418713147155852221/main.py", line 33, in get
    logout_url = users.create_logout_url('/')
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/1/google/appengine/api/users.py", line 299, in create_logout_url
    raise e
ApplicationError: ApplicationError: 2

Traceback (most recent call last):
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 273, in Handle
    result = handler(dict(self._environ), self._StartResponse)
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1519, in __call__
    response = self._internal_error(e)
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
    rv = self.handle_exception(request, response, e)
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
    rv = self.router.dispatch(request, response)
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__
    return handler.dispatch()
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "/base/data/home/apps/s~participoll/1.418713147155852221/main.py", line 33, in get
    logout_url = users.create_logout_url('/')
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/a19f7fde5f64c33c/python27/python27_lib/versions/1/google/appengine/api/users.py", line 299, in create_logout_url
    raise e
ApplicationError: ApplicationError: 2

When I ask for more information from Chrome regarding its "Not Secure" notification, it tells me that 1 cookie is being use.
Wait My comments above refer to using Chrome. I just tried Safari and there I am getting the 500 error only.
Update1
Update0
The server error exception is 500 (I did not say that originally).
Even after changing the app's guts to include only a Google-supplied sample code, the same server error exception occurs: 500.
This app was never migrated from the master/slave datastore to the HRD datastore (because this developer was not informed of a need to do so).
I suspect that the app has been frozen out of appengine because the migration was not done, but the kind Answerer disagrees (see comments to the Answer).
The revised app.yaml:
application: participoll
version: 1
runtime: python27
threadsafe: yes
api_version: 1

handlers:
- url: .*
  script: main.app

The revised main.py:
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Sample Google App Engine application that demonstrates using the Users API

For more information about App Engine, see README.md under /appengine.
"""

# [START all]

from google.appengine.api import users
import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        # [START user_details]
        user = users.get_current_user()
        if user:
            nickname = user.nickname()
            logout_url = users.create_logout_url('/')
            greeting = 'Welcome, {}! (sign out)'.format(
                nickname, logout_url)
        else:
            login_url = users.create_login_url('/')
            greeting = 'Sign in'.format(login_url)
        # [END user_details]
        self.response.write(
            '{}'.format(greeting))

class AdminPage(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            if users.is_current_user_admin():
                self.response.write('You are an administrator.')
            else:
                self.response.write('You are not an administrator.')
        else:
            self.response.write('You are not logged in.')

app = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/admin', AdminPage)
], debug=True)

# [END all]

My goal is to salvage the name ParticiPoll for this app, whether the datastore is preserved or not preserved. How can I proceed? For example, is there some information at the developers' Google Cloud Platform, that I might use for confirming the datastore status or edit to avoid the server error?
update0 above
My app works in the local server but not in the public server. This suggests to me there is some problem with my app.yaml, but I have had no luck identifying the problem.
app.yaml:
application: participoll
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /static
  static_dir: static

- url: /favicon.ico
  static_files: static/images/favicon.ico
  upload: static/images/favicon.ico

- url: /.*
  script: main.app

libraries:
- name: jinja2
  version: "2.6"
- name: markupsafe
  version: latest

builtins:
- remote_api: on

main.py
import webapp2
from views import MainHandler, TablePage, AddPerson, AddQuestion, Image
import os

app = webapp2.WSGIApplication([
        ('/', MainHandler),
        ('/table', TablePage),
        ('/add_person', AddPerson),
        ('/add_question', AddQuestion),
    ('/img', Image),
        ],
        debug=True)

views.py (excerpt) (notice users.create_login_url(self.request.uri))
class MainHandler(BaseHandler):

    def get(self):
        ID_id = self.request.get("ID", None)
        if ID_id == '':
            ID_id = None
        user = users.get_current_user()
        if ID_id is None: #no ID has been set by the user
            path = os.path.join(TEMPLATE_DIR, 'splash.html')
            if user: #offer user or nonuser options back at choose_name.html
                url = users.create_logout_url(self.request.uri)
                url_linktext = 'Signout'
                url_linktextmore = ' if you wish. You will be returned to this page after you signout.'
            else:
                url = users.create_login_url(self.request.uri)
                url_linktext = 'Signin'
                url_linktextmore = ' if you will be creating a page. You will be returned to this page after you signin.'
            template_values = {
                'url': url,
                'url_linktext': url_linktext,
                'url_linktextmore': url_linktextmore,
                }
            self.response.out.write(template.render(path, template_values))

Can I get help detecting and repairing this exception?

A: It looks like the dev server doesnt actually use the Google Accounts system https://cloud.google.com/appengine/docs/standard/python/users/#Python_Google_accounts_and_the_development_server
A few questions on stack overflow seem to indicate that getting the NotAllowedError means you may need to do some extra configuring from within the app engine dashboard to enable it
https://stackoverflow.com/a/19676826/4458510
NotAllowedError when trying to access AppStats
Create_login_url error after migrating to HRD (Google App Engine)
https://groups.google.com/forum/#!topic/google-appengine/xH__FhRXOCM


text:
Q: pyshark can not capture the packet on windows 7 (python) I want to capture the packet using pyshark.
but I could not capture the packet on windows 7.
this is my python code

import pyshark
def NetCap():
    print 'capturing...'
    livecapture = pyshark.LiveCapture(interface="eth0", output_file='./test.pcapng')
    livecapture.sniff(packet_count=10)
    print 'end of capture.'
    print livecapture

if __name__ == "__main__":
    NetCap()

this is result

capturing...
end of capture.
<LiveCapture (0 packets)>

Livecapture is 0 packets.
I don't know what is the matter.
please help me.

A: open cmd and type:
tshark -D

this will give you a list like:
C:\WINDOWS\system32>tshark -D
1. \Device\NPF_{BF2D596D-AEB8-4AF3-88A2-FF31441BB262} (VMware Network Adapter VMnet8)
2. \Device\NPF_{7AB58B39-455D-4A40-AA3A-678491E70B27} (Local Area Connection* 4)
3. \Device\NPF_{7FEC3EE6-0676-4E81-8B13-FBD5716BF2BF} (Wi-Fi)
4. \Device\NPF_{10D9C98D-BF03-4CE5-A58C-5A726BC6066A} (Ethernet)
5. \Device\NPF_{45AD9B2A-DB01-4EDE-A922-C2DD6D868568} (VMware Network Adapter VMnet1)
6. \\.\USBPcap1 (USBPcap1)

now you can use any of the interface as required by this:
import pyshark
livecapture = pyshark.LiveCapture(interface='\\Device\\NPF_{7FEC3EE6-0676-4E81-8B13-FBD5716BF2BF}', output_file='./test.pcapng')

A: windows doesnot have any interface named eth0. they use the full name as Ethernet adapter Ethernet. please use str() command and try solving it.


text:
Q: Visual Studio: how do I have the debugger stop when a member variable is modified? I have program that has a variable that should never change. However, somehow, it is being changed. Is there a way to have the debugger stop when that particular member variable is modified?

A: You can set conditional breakpooint at places where the variable is used.
In Visual Studio set breakpoint by pressing F9 when your cursor at the line where you want to set breakpoint.
Next, right click on the breakpoint and select Condition.
Type your condition like
n != 5

Good luck.
Here's a link from MSDN.

A: Set a data breakpoint to stop execution whenever some variable changes.
Break on the initialization of your variable, or someplace where your variable is visible - you need to be able get its address in memory. Then, from the menus choose Debug -> New Breakpoint -> New Data Breakpoint. Enter "&var" (with var replaced by the name of your variable.)
This will break into the debugger on the exact line of code that is modifying your variable.
More documentation here:
http://msdn.microsoft.com/en-us/library/350dyxd0.aspx

A: If it is being modified through an assignment or other direct update, the data breakpoint will work.  However, if it is being modified via some other means - for example a buffer overwrite - I'm not sure if it will tell you exactly when it occurs.  Just something to keep in mind.


text:
Q: What is a good way to balance the pros and cons from using Redux? Of course Redux provides us a very excellent solution for managing the states.
However, it's hard to handle async dispatches and a global state may not be needed for many components in the project.
Is it possible to have a solution can fulfill the basic usage of redux and also handle async problems?

A: You should definitely check Redux-Saga or Redux-Service first.
There are many tutorials and real examples with using Redux-Saga so I'll not talk a lot about it.
Redux-Service is written by one of my colleagues and has been applied to our production environment for a long time. The solution behind is that by combining the idea of Redux-Saga, Redux-Thunk and the generator in JavaScript, Redux-Service offers an experimental way to handle (highly mutable || remote) data source && async logic in Redux.
If you are experienced with backend development framework like Express, you will be familiar with the concept of middlewares. And here you go. The ideas of Express middleware and Redux-Service are pretty similar.
Check more from the document and try to do some mini project with it should be more helpful than words.

A: Please take a look at Redux-Tunk, in case you has not done it yet.
Given it's nice feature of returning the value of the inner function as the result of dispatch invocation and combining this feature with Promises makes it super easy to orchestrate asynchronous state updates.
They have pretty clear explanation of the concept under Compostion section of their doc.


text:
Q: Migrating from NET4.8 to NET5/Core, is Full Framework required? Using the NET Upgrade Assistant, it informed me that it couldn't perform the migration since the code was not in .NET Full Framework. For code to operate in the new NET world, is that a requirement or is that a assistant issue? Can I just create a new project and manually move everything to it?
The error is

[09:22:29 ERR] Support for Web Forms is limited to .NET Full Framework. To learn more please read: aka.ms/migrate-web-forms [09:22:29 ERR] Project C:\Projects\IC\VS2022\SentryServices_NET5_Dev\WWW\www.csproj uses feature(s) that are not supported.

A: Well, web forms is so old, it's no longer supported in .NET Core or .NET 5.
You can read the link the error message gave you, to find out what you can do about that.
You will have to rewrite considerable parts of your app. While it is possible to just copy over source code files, that only works if the code written would work under .NET 5. If it wouldn't, like web forms, then there is no real migration path other than rewrite it.


text:
Q: JS/jQuery Change Image on Hover of  I have some HTML shown below, which is generated dynamically in an ASP Classic form.
There can be any amount of groups/tables (Size/Color) with any amount of rows/options.
Each group/table has an img tag, and each row/option has a hidden field with its corresponding image URL.
On the hover of each row, I need to change the src attribute of the image of that group to that row's image URL, using JS or jQuery (something that works in ASP classic).
The HTML can be changed if needed for it to work.
Thank you.

            Color<input id="colorSortOrder" type="hidden" value="1" />

            <input id="radioRed" type="radio" name="Color" value="R-" />

                Red
            <input type="hidden" value="Image1.jpg" />

            <input id="radioOrange" type="radio" name="Color" value="O-" />

                Orange
            <input type="hidden" value="Image2.jpg" />

            <input id="radioBlue" type="radio" name="Color" value="B-" />

                Blue
            <input type="hidden" value="Image3.jpg" />

            Size<input id="sizeSortOrder" type="hidden" value="2" />

            <input id="radioLarge" type="radio" name="Color" value="LA-" />

                Large
            <input type="hidden" value="Image4.jpg" />

            <input id="radioMedium" type="radio" name="Color" value="ME-" />

                Medium
            <input type="hidden" value="Image5.jpg" />

            <input id="radioSmall" type="radio" name="Color" value="SM-" />

                Small
            <input type="hidden" value="Image6.jpg" />

...which looks something like:

A: I would change the HTML just a little bit to reduce the JavaScript parsing needed by adding data attributes for the image src like this
http://jsfiddle.net/muDJ9/
and with the use of JavaScript replace you can edit out extensions for the alt tags
EDIT: This also runs the fastest I just ran tests on the others submitted using the console.time() profiler
FINAL: http://jsfiddle.net/FV9cw/

A: $("input[type='radio']").hover(function(){
var src = $(this).parent().find("input[type='hidden']").val();
$(this).parent().parent().parent().find("img").attr("src",src);
});

Line 1 detects hover.
Line 2 go up to td and looks for the hidden input inside td and takes the value
Line 3 go up three times td > tr > table and looks for img and sets his attribute src with the image.

A: You can do it as under
Live Demo
$('label[for]').closest('tr').mouseenter(function(){
    $(this).siblings().find('img').hide();
    $(this).find('img').attr('src', $(this).find('input[type=hidden]').attr('value')).show();
});


text:
Q: I have a memory leak and can't find it This is my code. I am programing an app and using firebase to load a random users photo, but after i realod a couple of times this fragment, it crashes due to memory leak. I have been looking for it for ages. please help :)
how my app works:

*

*Create a user

*user takes a photo

*random other users (or the same users) photo appers

*the user rates a picture and then a new one comes up

public class RatingFragment extends Fragment {
private TabLayout tabLayout;
private ImageView imageView;
private DatabaseReference databaseReference;
private FirebaseDatabase firebaseDatabase;
private DataSnapshot childSnapshot;
private User user, newUser;
private RatingBar ratingBar;
private Random random = new Random(System.currentTimeMillis());

public RatingFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View view;
    view = inflater.inflate(R.layout.fragment_rating, container, false);

    tabLayout = view.findViewById(R.id.tabLayoutRating);
    tabLayout.setTabTextColors(ColorStateList.valueOf(Color.WHITE));
    tabLayout.setSelectedTabIndicatorColor(Color.WHITE);

    firebaseDatabase = FirebaseDatabase.getInstance();
    databaseReference = firebaseDatabase.getReference().child("users");

    imageView = view.findViewById(R.id.ivRandomPhoto);

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int userCount = (int) dataSnapshot.getChildrenCount();
            int rand = random.nextInt(userCount);
            Iterator itr = dataSnapshot.getChildren().iterator();

            for (int i = 0; i < rand; i++) {
                itr.next();
            }
            childSnapshot = (DataSnapshot) itr.next();
            user = childSnapshot.getValue(User.class);
            imageView.setImageURI(Uri.parse(user.getNewPhoto()));
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    ratingBar = view.findViewById(R.id.ratingBar);

    ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
        @Override
        public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
            newUser = new User (user.getUserId(),user.getUsername(),user.getPhotos(),user.getAverageRating(),user.getPoints()+1,user.getNewPhoto());
            databaseReference.child(user.getUserId()).setValue(newUser);
            ratingBar.setRating(0);
        }
    });

    TabLayout.Tab tab = tabLayout.getTabAt(1);
    tab.select();

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            switch (tab.getPosition()) {
                case 0:
                    CropFragment cropFragment = new CropFragment();
                    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.main_framelayout, cropFragment);
                    fragmentTransaction.commit();
                    break;
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    return view;
   }
 }

A: You are adding ValueEventListener in onCreateView but, as far as I can see, you're not removing it anytime. Apart from this, I'm not able to see any other source of memory leak.


text:
Q: A new(?) partial order on the set of continuous maps Let $X,Y$ be topological spaces. Define a partial order on $\hom(Y,X)$ as follows: $f \leq g$ if $f^{-1}(U) \subseteq g^{-1}(U)$ for all open subsets $U \subseteq X$. Equivalently, $f(y)$ is a specialization of $g(y)$ for all $y \in Y$. In particular this endows $\mathsf{Top}$ with the structure of a $2$-category. I have several questions:
1) Is this partial order well-known and studied somewhere in the literature?
2) What are some properties of this partial order? What about the case that $X,Y$ are sober?
3) What are interesting and nontrivial examples of maps $f,g$ with $f \leq g$, but $f \neq g$? I am mostly interested in scheme morphisms.
EDIT: I would like to add:
4) If $X,Y$ are actually ringed spaces, then we can define $f \leq g$ if $f^{-1}(U) \subseteq g^{-1}(U)$ for all $U \subseteq X$ and $f^\# = \mathrm{res} \circ g^\#$. What about this $2$-categorical structure on the category of ringed spaces, is this already known?

A: The short answer is yes: for locales (hence sober spaces), anyway. The 2-category (or rather, $\textbf{Poset}$-enriched category) $\mathfrak{Loc}$ has hom-sets with precisely this ordering. Some of its properties are mentioned in passing in [Johnstone, Sketches of an elephant, Chapter C1], but to some extent the 2-dimensional properties of $\mathfrak{Loc}$ are subsumed by the 2-dimensional properties of the 2-category $\mathfrak{BTop}_{/ \textbf{Set}}$ of Grothendieck toposes and geometric morphisms. Indeed:
Theorem. The pseudofunctor $\textbf{Sh}(-) : \mathfrak{Loc} \to \mathfrak{BTop}_{/ \textbf{Set}}$ is 2-full embedding, in the sense that the induced functors on hom-categories $\mathfrak{Loc}(X, Y) \to \mathfrak{BTop}_{/ \textbf{Set}}(\textbf{Sh}(X), \textbf{Sh}(Y))$ is (half of) an equivalence of categories.
Here is a non-trivial property of the hom-poset $\mathfrak{Loc}(X, Y)$:
Proposition. $\mathfrak{Loc}(X, Y)$ has joins for directed subsets, i.e. $\mathfrak{Loc}(X, Y)$ is dcpo and moreover $\mathfrak{Loc}(X, Y)$ is an accessible category.
The last one generalises to $\mathfrak{BTop}_{/ \textbf{Set}}$: for any two Grothendieck toposes $\mathcal{E}$ and $\mathcal{F}$, the category of geometric morphisms $\mathcal{E} \to \mathcal{F}$ forms an accessible category.


text:
Q: what's the meaning of "fit the scale" what's the meaning of "fit the scale"
eg
Colorful blocks on an ethnographical map, did not only demonstrate how dif  erent ethnic groups "stand with respect to one another," but they also made a powerful statement about their discontents, or people who did not fit the scale

A: I've only heard that phrase in passing a few times, but from context it appears to mean "social outliers".  Meaning, people who are culturally different from any other group that is included in the study and have no real cultural connection with the group as a whole.
This would fit pretty well with how I remember the phrase being used, and it makes sense in terms of the phrase itself.
To explain the phrase: We create scales to measure weight or, more generally, to measure things.  But, in creating a scale we assume several things about what we are measuring.  For example, we may assume that the object we are weighing is going to be a heavy cube of some metal.  So we build a scale with a plate for us to put the metal cube on, and that works fine for heavy cubes.  But what about a metal ball?  It would roll right off!  Or perhaps a helium balloon?  That's just going to go up!  Both of those objects "do not fit the scale."  They are outside of our understanding of how to weigh things.
Hence, that's what the sentence is saying about some cultures.  They exist outside of the other culture's expectations and assumptions.  Thus the other cultures have no framework or understanding to view them through.  They're like balloons on our scale, they don't fit our expectations, and thus we can't measure them properly.


text:
Q: CakePHP friendly seo url I want to make my url seo friendly. www.example.com/posts/view/1 change for www.example.pl/:slug-:id. Everything works fine, but probably I'm doing something wrong with routing, because when after clicking the urls in paginator, the url is correct, it looks like www.example.pl/:slug-:id , but it appears an error
"The requested address 'www.example.pl/:slug-:id' was not found on this server."
I don't know what's wrong. Here's my code:
Router::connect(
    '/:slug-:id',
    array(
        'controller' => 'posts',
        'action' => 'view'
    ),
    array(
        'pass' => array('slug' , 'id'),
        'id' => '[0-9]+'
    )
);

in paginator view:
echo $this->Html->link($ad['Post']['title'], array(
    'controller' => 'posts',
    'action' => 'view',
    'slug' => Inflector::slug($post['Post']['title'],'-'),
    'id'=>$post['Post']['id'])
);

I solved the problem.

A: Its too simple i'll give you an example from my project ..
in your routes.php
Router::connect(
    '/:slug-:id',
    array('controller'=>'posts','action'=>'view'),
    array('pass'=>array('slug','id'),'slug'=>'[a-zA-Z0-9 -]+','id'=>'[0-9]+')
);

your link in views should be like .
$this->Html->link(__('link desu'),array('controller'=>'posts','action'=>'view','id'=>$post['Post']['id'],'slug'=>$post['Post']['slug']));

and your PostsController.php
public function view($slug,$id){
    $this->Post->id = $id;
    // ....
}

Quick tip : try to create an array in your PostModel to avoid creating it every time in your view .
example :
Post.php
class Post extends AppModel{
    // ....
        public function afterFind($results,$primary = false){
        foreach ($results as $key => $value) {
            if(isset($value[$this->alias]['id'])){
                $results[$key][$this->alias]['url'] = array(
                                 'controller'=>'posts',
                                 'action'=>'view',
                                 'id'=>$results[$key][$this->alias]['id'],
                                 'slug'=>$results[$key][$this->alias]['slug']
                            );
            }
            // ....
        }
        return $results;
    }
}

}
so you can call it in your view simply like that
$this->Html->link(__('link desu'),$post['Post']['url']);

A: It's probably a problem with the regex on the route. Your slug contain hyphens - which you also use to separate between the slug and the id. i.e.:
example.com/my-slug-has-hyphens-1

The regex is not smart enough to know that the "last" hyphen separates the slug from the id.
To test if this is the problem, try using a route like this '/:slug__:id', just to see if it works.

A: I solved the problem. In the posts controller my view function was wrong. Here's right correct:
function view($id = null, $slug = null) {
$this->Post->id = $this->params['post'];
$this->set('post', $this->Post->read());

A: Pass is order sensitive
In the question the route is as follows:
Router::connect(
    '/:slug-:id',
    array(
        'controller' => 'posts',
        'action' => 'view'
    ),
    array(
        'pass' => array('slug' , 'id'), # <-
        'id' => '[0-9]+'
    )
);

That means the post function will recieve:
public function view($slug, $id)

As indicated by the edited question, the code is expecting the id to be the first parameter. The easiest solution is simply to specify the passed parameters in the order that they are expected:
...
        'pass' => array('id', 'slug'), # <-

A: Router::connect(
    '/:slug/:id',
    array(
        'controller' => 'posts',
        'action' => 'view'
    ),
    array(
        'pass' => array('slug' , 'id'),
        'id' => '[0-9]+'
    )
);

the above code will create correct link as www.example.com/posts/view/title/1
echo $this->Html->link($post['Post']['title'], array('controller' => 'posts', 'action' => 'view', Inflector::slug($post['Post']['title'],'-'),$post['Post']['id']));


text:
Q: How to show a dynamic location in ASP MVC using Google Maps I am developing an ASP MVC web application.
I am trying to show a location in a Google Maps frame according to a given address by the user (In a input field).
I wrote a Javascript function in order to show the location using the ASP Helpers Maps but it doesn't work.
This is what I've tried :

 ADDRESS :

       <form method="post">
        <input type="text" name="address" placeholder="Your Address" required="" style="margin-top:0px; width:506px;" value="@Request["address"]">
         <input type="submit" value="Map It!" />
       </form>

A: You shouldn't use these helpers, and follow the documentation
It's as easy as an API call : Just use
https://maps.googleapis.com/maps/api/geocode/json?address=YOUR_TEXTBOX_ADRESS&key=YOUR_API_KEY

To get the API_KEY, just follow the steps here
And replace YOUR_TEXTBOX_ADRESS by the adress entered by user


text:
Q: How to solve equations where the power of $x$ is a function of $x$? I have been trying to find a solution for equations of the type $x^{px-c} = a$. I know how to use Lambert W. function to find solutions for $x^x = a$, but the function of $x$ at the exponent is making things much difficult for me. I do not how to proceed in this scenario. Should I try series expansion or some approximation method?
Any help will be greatly appreciated.

A: I do not think that explicit solutions could be obtained for the zero's of
$$f(x)=x^{p\,x-c} - a$$
and you will, more than likely, use numerical methods.
In the case where $c=0$, there is a solution, still expressed in terms of Lambert function. It would be
$$x=\frac{\log (a)}{p\, W\left(\frac{\log (a)}{p}\right)}$$ obtained writing
$x^x=a^{\frac1p}$.
For $c\neq 0$, consider instead the function
$$g(x)=(px-c)\log(x)-\log(a)$$
$$g'(x)=-\frac{c}{x}+p \log (x)+p$$
$$g''(x)=\frac{c+p x}{x^2}$$ The first derivative cancels at
$$x_*=\frac{c}{p\,W\left(\frac{e c}{p}\right)}$$ At this point
$$g''(x_*)=\frac{p^2}{c} W\left(\frac{e c}{p}\right) \left(1+W\left(\frac{e
   c}{p}\right)\right)$$ Considering the value of $g(x_*)$ and the above would give you indications about the existence of the roots, their number and where they are located.


text:
Q: Storing bash script argument with multiple values I would like to be able to parse an input to a bash shell script that looks like the following.
myscript.sh --casename obstacle1 --output en --variables v P pResidualTT

The best I have so far fails because the last argument has multiple values. The first arguments should only ever have 1 value, but the third could have anything greater than 1. Is there a way to specify that everything after the third argument up to the next set of "--" should be grabbed? I'm going to assume that a user is not constrained to give the arguments in the order that I have shown.
casename=notset
variables=notset
output_format=notset
while [[ $# -gt 1 ]]
do
    key="$1"
    case $key in
        --casename)
        casename=$2
        shift
        ;;
        --output)
        output_format=$2
        shift
        ;;
        --variables)
        variables="$2"
        shift
        ;;
        *)
        echo configure option \'$1\' not understood!
        echo use ./configure --help to see correct usage!
        exit -1
        break
        ;;

    esac
    shift
done

echo $casename
echo $output_format
echo $variables

A: One conventional practice (if you're going to do this) is to shift multiple arguments off. That is:
variables=( )
case $key in
  --variables)
    while (( "$#" >= 2 )) && ! [[ $2 = --* ]]; do
      variables+=( "$2" )
      shift
    done
    ;;
esac

That said, it's more common to build your calling convention so a caller would pass one -V or --variable argument per following variable -- that is, something like:
myscript --casename obstacle1 --output en -V=v -V=p -V=pResidualTT

...in which case you only need:
case $key in
  -V=*|--variable=*) variables+=( "${1#*=}" );;
  -V|--variable)   variables+=( "$2" ); shift;;
esac


text:
Q: MySQL Multiple Left Joins I am trying to create a news page for a website I am working on. I decided that I want to use correct MySQL queries (meaning COUNT(id) and joins instead of more than one query or num_rows.) I'm using a PDO wrapper, that should function fine, and this still fails when run directly through the MySQL CLI application.
Basically, I have 3 tables. One holds the news, one holds the comments and one holds the users. My aim here is to create a page which displays all (will paginate later) the news posts titles, bodies, authors and dates. This worked fine when I used a second query to get the username, but then I decided I'd rather use a JOIN.
So what's the problem? Well, I need two joins. One is to get the author's username and the other to get the number of comments. When I simply go for the author's username, all works as expected. All the rows (there are 2) in the news table are displayed. However, when I added this second LEFT JOIN for the comments row, I end up only receiving one row from news (remember, there are 2,) and COUNT(comments.id) gives me 2 (it should display 1, as I have a comment for each post.)
What am I doing wrong? Why is it only displaying one news post, and saying that it has two comments, when there are two news posts, each with one comment?
SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id

Also, just to be sure about one other thing, my left join to comments is the correct way to get all posts regardless of whether they have comments or not, correct? Or would that be a right join? Oh, one last thing... if I switch comments.news_id = news.id to news.id = comments.news_id, I get 0 results.

A: To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"
SELECT news.id, users.username, news.title, news.date,
       news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

A: You're missing a GROUP BY clause:
SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.


text:
Q: Host root domain on CloudControl I want to host a root domain like "example.com". The Alias addon allows you to host sub domains like "www.example.com".
But how to host the root domain "example.com" on cloudcontrol? Because I want to create a redirect from example.com to www.example.com.
I have already setup an alias from www.example.com to my cloudControl app successfully. But I was not able to setup an alias from example.com to my cloudControl app.
I'm not sure, whether I have understood everything with the Alias addon.
Best regards,
Christian

A: Since you can't add a CNAME to a root romain you can't link it directly to cloudControl.
The ugly way would be to manually create A-records to the (currently 3) cloudControl-loadbalancer-IPs, but cloudControl changes these (adds/removes loadbalancers) sometimes so you shouldn't do this.
For my apps I usually use the "URL"-record-type many DNS-Providers provide. In the background they use A-records to a seperate webserver that returns a redirect to the www-version.

A: You can also use a service like DNS Made Easy. They provide a custom type called ANAME, that's basically a CNAME without the CNAME limitations. They take care of updating the IP addresses in the background when necessary.
http://www.dnsmadeeasy.com/technology/aname-records/


text:
Q: Using Same If Else Statement Multiple Times I'm doing this...
<?php $term = ucfirst($_GET['term']);?>

And doing this multiple times on the page:
<?php if (empty($term)) echo 'X'; else echo $term; ?>

Is there a better way to go about this?

A: You can specify the placeholder value when you first assign the value:
<?php  $term = ucfirst($_GET['term'])  or  $term = "X";  ?>

(Works because the OR has lower precedence than the assignment.)
Then just print that variable henceforth:
<?= $term ?>

It will contain either the input value, or your X.

A: ternary operator :
$term = (empty(ucfirst($_GET['term']))) ? echo 'X' : $_GET['term'];

A: Declare a function
function doTerm()
{
    $term = ucfirst($_GET['term']);
    if (empty($term)) echo 'X'; else echo $term;
}

so you can call it like
doTerm();

whenever you need it to test and echo.

A: <?php
$term = isset($_GET['term']) ? ucfirst($_GET['term']) : 'X';
echo $term;

//...
?>

If you don't need it anywhere else than you could make it even shorter :-)
    echo (isset($_GET['term']) ? ucfirst($_GET['term']) : 'X');

A: Ternary syntax can work easily here:
Using short hand tags:
<?=empty($term) ? 'X' : $term ?>

or long hand:
<?php echo empty($term) ? 'X' : $term ?>

A: you can use Conditional Operator like
echo ($term!=null)? 'x' : $term;


text:
Q: Javascript click gets always the first item from multiple items with similar class I am a beginner in JavaScript.
I have five (05) html divs like this:

                                    Items

Item 1

Item 2

Item 3

Item 4

And a css to rotate the fa-chevron-right like this:
.down{
    -ms-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -webkit-transform: rotate(180deg);
    transform: rotate(180deg);
}

Handled by below JavaScript:
var mainparentelements = document.querySelectorAll('.ddmenu');
for (let i = 0; i < mainparentelements.length; i++) {
    mainparentelements[i].onclick = function() {
    var toberotated = document.querySelector('.fa-chevron-right');
    toberotated.classList.add("down");
    };
}

Now the problem is: no matter which main item I click, its always the fist fa-chevron-right which gets rotated (of course). How can I bind the rotation action and class to each individual rather to just one? What I am missing here? Feeling clueless. Any reading or directions or solution will be greatly appreciated. Looking for kind help using css and pure vanilla Javascript only.

A: Reference the parent element you're iterating over inside the loop instead of using querySelector, and you can get from the clicked parent element to the .fa descendant:
mainparentelements[i].onclick = function () {
  var toberotated = mainparentelements[i].querySelector('.fa-chevron-right');
  toberotated.classList.add("down");
};

You can also make the code a lot more concise by invoking the iterator instead:
for (const parent of document.querySelectorAll('.ddmenu')) {
  parent.onclick = () => {
    parent.querySelector('.fa-chevron-right').classList.add("down");
  };
}


text:
Q: vueX with vuei18n. this.dispatch is not able to access vuei18n I am relatively new to Vue and I've been reading the documentation and forums for quite a while for a solution to this one but haven't found it yet.
I am using the Vue Webpack template: here
I'm trying to create an app where I have an API endpoint to get the currency and country for the user as well as the user language from the browser.
I am using this.$store.dispatch('setlanguage') on initialisation of the Vue Component to set the state of the language, and save it to a cookie. The problem here though is that I am unable to alter the vuei18n as my app says it does not exist. The reason I am using vuei18n instead of vueXi18n is because the latter does not have the numberFormat options and this is needed in order to set correctly the currency symbols.
So to get things started:
Project structure:
main.js
App.Vue
 store
   getters.js
   index.js
   mutation-types.js
   mutations.js
 router
   index.js
 lang
   locales
     en.js
     fr.js
     de.js
   lang.js
 components
   LocaleSwitcher.vue
 pages
   Footer.vue
   Home.vue

main.js
import Vue from 'vue'
import VueResource from 'vue-resource'
import Cookies from 'js-cookie'
import App from './App.vue'
import i18n from './lang/lang'
import store from './store'
import router from './router'

Vue.use(VueResource)
Vue.config.productionTip = false

Vue.config.language = Cookies.get('lang')
Vue.config.country = Cookies.get('country')
Vue.config.currency = Cookies.get('cur')

export const localeStrings = {
  en: 'English',
  de: 'Deutsch',
  fr: 'Français',
  it: 'Italiano',
  nl: 'Nederlands',
  sv: 'Svenska',
  es: 'Español',
  ja: '日本語'
}

export const app = new Vue({
  el: '#app',
  router,
  store,
  i18n: i18n,
  render: h => h(App),
  created () {
    this.$store.dispatch('setLang', Vue.config.language)
    this.$store.dispatch('setCountry', Vue.config.country)
  }
})

lang.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

let i18n = new VueI18n({
  locale: 'en',
  messages: {},
  fallbackLocale: 'en',
  numberFormats: {}
})

export default {i18n}

App.vue
template>

    <app-header></app-header>

      <router-view></router-view>

    <app-footer></app-footer>

</template>

Footer.vue
<template>

{{copyright}}

    <local-switcher></local-switcher>

</template>

LocaleSwitcher.vue
<template>

    <select v-model="activeLocale" @change="changeLang">
      <option v-for="(lang, id) in locales" :key="id" v-bind:value="id">{{lang}}</option>
    </select>

</template>

router/index.js
import Vue from 'vue'
import Router from 'vue-router'

import p404 from '../pages/error/404.vue'
import Home from '../pages/Home.vue'

Vue.use(Router)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '*',
    name: '404',
    component: p404
  }
]

let router = new Router({
  mode: 'history',
  routes
})

// I still have to figure out how to use this to set www.mypage.com/mylanguage/home
// use beforeEach route guard to set the language
router.beforeEach((to, from, next) => {
  // use the language from the routing param or default language
  let language = to.params.lang
  console.log(language)
  console.log('router end')
  if (!language) {
    language = 'en'
  }
  // set the current language for vuex-i18n. note that translation data
  // for the language might need to be loaded first
  // Vue.i18n.set(language)
  next()
})

export default router

store/getters.js
export const getters = {
  getLanguage: state => {
    return state.language
  },
  getCountry: state => {
    return state.country
  },
  getCurrency: state => {
    return state.currency
  }
}

store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import { state, mutations, actions } from './mutations'
import { getters } from './getters'

Vue.use(Vuex)

// const mapState = Vuex.mapState
const store = new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})

export default store

store/mutation-types.js
export const SET_LANG = 'SET_LANG'
export const SET_COUNTRY = 'SET_COUNTRY'
export const SET_CURRENCY = 'SET_CURRENCY'

store/mutations.js
import Vue from 'vue'
import Cookies from 'js-cookie'
import * as types from './mutation-types'
import {app, supportedLocale, supportedCurrencies} from '../main'
import CountryCurrency from '../data/country_currency.json'
import locale2 from 'locale2'

export const state = {
  language: Cookies.get(settings.languageCookie),
  country: Cookies.get(settings.countryCookie),
  currency: Cookies.get(settings.currencyCookie),
  loading: false
}

export const mutations = {
  [types.SET_LANG] (state, payload) {
    Cookies.set('lang', payload)
    state.language = payload
  },
  [types.SET_COUNTRY] (state, payload) {
    Cookies.set('country', payload)
    state.country = payload
  },
  [types.SET_CURRENCY] (state, payload) {
    Cookies.set('currency', payload)
    state.currency = payload
  }
}

export const actions = {
  async setLang ({commit}, language) {
    console.log(app)
    console.log(Vue)
    var vueMessages = app.$i18n.messages

  var userLocale = 'en'
  var browserLocale = locale2.split('-', 1)[0]
  // testing browser language
  if (locale === undefined) {
    // get browser language
    userLocale = browserLocale
  } else if (browserLocale !== locale) {
    console.log('browser language changed')
    userLocale = browserLocale
  } else {
    userLocale = locale
  }
  // check for supported languages
  if (!supportedLocale.includes(userLocale)) {
    userLocale = 'en'
  }
    if (language in vueMessages) {
      console.log('already in messages')
      commit(types.SET_LANG, language)
    } else if (!supportedLocale.includes(language)) {
      console.log('not supported so commiting default en')
      commit(types.SET_LANG, 'en')
    } else {
      try {
        // you can use fetch or import which ever you want.
        // Just make sure your webpack support import syntax
        // const res = await axios.get(`./src/lang/${payload}.json`)
        const res = await import(`../lang/locales/${language}.json`)
        app.$i18n.locale = language
        app.$i18n.setLocaleMessage(language, res)
        var addNumberFormats = {
          currency: {
            style: 'currency', currencyDisplay: 'symbol', currency: `${app.$i18n.currency}`
          }
        }
        app.$i18n.mergeNumberFormat(language, addNumberFormats)
        Cookies.set('lang', language)
        commit(types.SET_LANG, language)
      } catch (e) {
        console.log(e)
      }
    }
  },
setCountry ({commit}, countryCode) {
    var userCountry = 'NA'
    if (countryCode === undefined || countryCode === 'NA') {
      Vue.http.get('https://www.myapi.com/api/v2/geo/country-code', {
        timeout: 100
      }).then(response => {
        state.country = response.data.code
        Cookies.set('country', response.data.code)
      }, response => {
        // error callback
        state.country = userCountry
        Cookies.set('country', userCountry)
      })
    } else {
      console.log(countryCode)
      state.country = countryCode
      Cookies.set('country', countryCode)
    }
  },
  setCurrency ({commit}, countryCode) {
    var userCurrency = 'USD'
    console.log('user country ' + countryCode)
    console.log('user currency ' + CountryCurrency[countryCode])
    console.log('currency supported: ' + supportedCurrencies.includes(CountryCurrency[countryCode]))

    if (CountryCurrency[countryCode] && supportedCurrencies.includes(CountryCurrency[countryCode])) {
      userCurrency = CountryCurrency[countryCode]
    }

    Cookies.set('currency', userCurrency)
    app.$i18n.currency = userCurrency

    try {
      var addNumberFormats = {
        currency: {
          style: 'currency', currencyDisplay: 'symbol', currency: `${app.$i18n.currency}`
        }
      }
      if (!app.$i18n.numberFormats[app.$i18n.locale]) {
        console.log('merge currency')
        app.$i18n.setNumberFormat(app.$i18n.locale, addNumberFormats)
      }
    } catch (error) {
      console.log(error)
    }
  }
}

The problem is that once loaded, I cannot access the app vue i18n. Am I accessing it incorrectly or is there another way to add language and currency settings to this? I hope I have provided enough info Thanks!

A: Could this answer be relevant in your case? https://stackoverflow.com/a/45460729/2964531
If you need to access or mutate properties of i18n, you can import it directly from store/mutations.js


text:
Q: How do I center an icon in an Edit Text? I have an icon and a hint in an edit text and  i tried to center the contents of the edit text horizontally, but that seems to only work for the hint and not for the icon. The icon is closer to the bottom of the edit text.
this is my code
<EditText
            android:id="@+id/password_edittext"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:backgroundTint="@color/white"
            android:background="@drawable/edittext_background"
            android:inputType="textPassword"
            android:gravity="center_vertical"
            android:drawableStart="@drawable/ic_lock"
            />

A: I've had no luck using the drawableStart property, an alternative is to use SpannableString and ImageSpan to set your hint by code.
SpannableString string = new SpannableString(" Password");
string.setSpan(new ImageSpan(this, R.mipmap.ic_launcher), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

EditText password_edittext = findViewById(R.id.password_edittext);
password_edittext.setHint(string);

XML:
<EditText
        android:id="@+id/password_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/white"
        android:drawablePadding="10dp"
        android:gravity="center_horizontal"
        android:inputType="textPassword" />

A: Try to remove gravity property, I think it will work for you, because you set the height of edit text to wrap content which will automatically make them vertically center.


text:
Q: GitLab specific merge request I have i18n branch on GitLab. Where i have already made few commits with pushes.
The problem:
Client wants me to make merge request to master branch but only with some specific files (

select the smallest possible set of changes

).
How is it possible ?
As i see it gathers all commits to merge request...so what should i do here ? i thought about creating third branch and commit there this small set of changes..but that's ridiculous...

A: You could try and apply a solution similar to "How do you merge selective files with git-merge?":

*

*use git merge --no-ff --no-commit -s ours i18n

*merge only the files you need:
git checkout i18n -- file1 file2 file3...

A: Sounds like your client just wants you to squash your commits on your i18n branch before you create you merge request. You do this using interactive rebase in git on your i18n branch.
git rebase -i HEAD~4

This will let you interact with the last 5 commits, change the number to get the commits you want.
In the interactive rebase, keep the first commit of your changes as a 'pick' and change the rest to 'squash'
When you save it will give you the opportunity to change the commit message of the squashed commits.
For more information see: https://thoughtbot.com/blog/git-interactive-rebase-squash-amend-rewriting-history


text:
Q: Logistic regression: Non-convergence issue I'm trying to perform a simple binary logistic regression over the  MNIST dataset using Python. The problem I'm experiencing is that when I try to optimize the $\vec{\theta}$ model parameters using scipy.optimize.minimize function (Newton-CG method) it throws the following warning:
  Warning: Desired error not necessarily achieveddue to precision loss

and the optimization is very poor, and I don't know why.
The dataset is as below:

*

*60000 28x28 training images of handwritten numbers (read as a $(m, n)$ matrix ${X}$, where $m$ is the number of images and $n$ is the number of pixels)

*60000 training labels (read as a $(m, 1)$ vector $\vec{y}$, where $m$ is the number of images)

*10000 28x28 test images of handwritten numbers (read as a $(p, n)$ matrix ${X_t}$, where $p$ is the number of (test) images and $n$ is the number of pixels)

*10000 test labels (read as a $(n, 1)$ vector $\vec{y_t}$, where $p$ is the number of (test) images)

I perform a preprocessing over this data which consists in the following steps:

*

*Standardization over each feature:
$$z_j = \frac{\vec{x_j} - \mu_j}{\sigma_j}$$
Here $x_j$ is the j-th feature vector (the j-th column of ${X}$),       $\mu_j$ is the mean value of $\vec{x_j}$ and $\sigma_j$ is the standard deviation of $\vec{x_j}$.

*Select only binary digits (0,1)

*Add an intercept term (a first columns filled with ones)
With the data ready to be used in a training algorithm  I've coded it as a class:
class LogisticRegression(object):
""" Logistic regression class

Implementation of common methods used in logistic regression problems

.. data:: data

   Dataset (train and test) as a Data class

.. data cost

   Logistic cost

.. data:: jac

   Jacobian of the cost function (logistic)

"""
def __init__(self, data):
    """ Constructor

    :param data: Input data
    :type data: Data class

    """
    self.data = data
    self.cost = None
    self.jac = None
    self.theta = None
    self.init_params()

def sigmoid(self, x):
    """ Compute the sigmoid function

    Compute the sigmoid function:

    .. math::

        \\sigma(x) = \\frac{1}{1 + e^x)}

    .. note::

        This version of sigmoid tries to avoid overflows in the computation
        of :math:`e^{-x}` by using an alternative formulation when x is
        negative, to get 0:

        .. math::

            \\sigma(x) = \\frac{e^{x}}{1 + e^{x})}

        This is equivalent to the definition of sigmoid, but we won't
        get :math:`e^{-x}` to overflow when x is very negative.

        Since both the x and y arguments to np.where are evaluated by Python,
        we may still get overflow warnings for large x elements; therefore
        we ignore warnings during this computation.

    :param x: Input
    :type x: Scalar or numpy ndarray
    :returns: Sigmoid function result
    :rtype: Scalar or numpy ndarray

    """
    with np.errstate(over='ignore', invalid='ignore'):
        return np.where(x >= 0,
                        1 / (1 + np.exp(-x)),
                        np.exp(x) / (1 + np.exp(x)))

def hypothesis(self, theta, x):
    """Makes classification predictions for the data in x using theta.

    :param theta: Logistic regression parameters (n, 1)
    :param x: Feature matrix (m, n
    :type theta: Numpy ndarray
    :type x: Numpy ndarray
    :returns: Logistic regression prediction (:math:`\\hat{y}`) with shape (m, 1), a
              number in the range (0.0, 1.0) for each sample. The number is the
              probability that the sample is classified as 1.

    :rtype: Numpy ndarray with shape (n, 1)
    """
    z = x.dot(theta)
    return self.sigmoid(z)

def log_cost(self, theta, x, y, inplace=True):
    """ Logistic cost function (cross-entropy error function)

    Compute the cross-entropy error function for a logistic regression
    problem:

    .. math::

        J(\\theta) = -\\frac{1}{m}\\sum_i^m\\left(y_i log(h_{\\theta}(x_i)) + (1-y_i)\
            log(1-h_{\\theta}(x_i))\\right)

    where

    .. math::

        h_{\\theta}(x_i) = sigmoid(\\theta^tx)

    .. note::

        Calls to hypothesis may produce probabilities that are
        0.0 and 1.0, due to the exponent in sigmoid and the large numbers
        involved. np.log on 0.0 overflows, so we clip the input of np.log to
        values very close to 0 instead.

    :param theta: Parameters vector
    :param x: Feature matrix (m, n)
    :param y: Labels vector (m, 1)
    :param inplace: If True assigns the result to the interal parameter cost
    :type theta: Numpy ndarray (shape (n, 1))
    :type x: Numpy ndarray (m, n)
    :type y: Numpy ndarray (m, 1)
    :type inplace: Boolean
    :returns: Cost
    :rtype: Scalar
    """
    m, n = x.shape
    theta = theta.reshape(n, 1)
    eps = np.finfo(np.float32).eps
    yhat_prob = np.clip(self.hypothesis(theta, x),
                        a_min=eps,
                        a_max=1.0-eps)
    loss = np.mean(np.where(y == 1,
                            -np.log(yhat_prob),
                            -np.log(1 - yhat_prob)))
    if inplace:
        self.cost = loss.flat[0]
    return loss.flat[0]

def log_cost_jac(self, theta, x, y, inplace=True):
    """ Logistic cost function Jacobian computation

    Computes the Jacobian of the logistic cost function:

        .. math::

            \\Delta(J(\\theta)) = \\sum_i(x^i(h_{\\theta}(x^i) -y^i)

    :param theta: Parameters vector 1D
    :param x: Feature matrix (m, n)
    :param y: Labels vector (m, 1)
    :param inplace: If True assigns the result to the interal parameter cost
    :type theta: Numpy ndarray (shape (n, 1))
    :type x: Numpy ndarray (m, n)
    :type y: Numpy ndarray (m, 1)
    :type inplace: Boolean
    :returns: Logistic cost function Jacobian
    :rtype: Numpy ndarray (n,) where n is the number of parameters (theta) (scipy minimize needs this
            shape)

    """
    m, n = x.shape
    theta = theta.reshape(n, 1)
    eps = np.finfo(np.float32).eps
    yhat_prob = np.clip(self.hypothesis(theta, x),
                        a_min=eps,
                        a_max=1.0-eps)
    yh = np.where(y.reshape(len(y), 1) == 1, yhat_prob - 1, yhat_prob)
    dtheta = np.dot(yh.T, x).T / float(m)
    if inplace:
        self.jac = dtheta
    return dtheta.flatten()

def log_cost_opt(self, method='Newton-CG', jac=True):
    """ Optimization of the logistic cost function over the theta parameters.

    """
    if jac:
        result = optimize.minimize(fun=self.log_cost,
                                   x0=self.theta.flatten(),
                                   method=method,
                                   args=(self.data.trainX[:20, :], self.data.trainY[:20], True),
                                   jac=self.log_cost_jac)
    else:
        result = optimize.minimize(fun=self.log_cost,
                                   x0=self.theta.flatten(),
                                   method=method,
                                   args=(self.data.trainX[:20, :], self.data.trainY[:20], True))
    return result

def init_params(self):
    """ Init parameter vector
    """
    m, n = self.data.trainX.shape
    self.theta = np.random.rand(n, 1)

The cost function is
$$J(\theta) = -\frac{1}{m}\sum_i^m\left(\vec{y_i} log(h_{\theta}(\vec{x_i})) + (1-\vec{y_i})
        log(1-h_{\theta}(\vec{x_i}))\right)$$
being $$h_{\theta}(\vec{x_i}) =  \frac{e^{\vec{w}^t \vec{x_i}}}{1+e^{\vec{w}^t \vec{x_i}}}$$
and the Jacobian and Hessian are:
$$\Delta(J(\vec{\theta})) = \sum_i(\vec{x_i}(h_{\theta}(\vec{x_i}) -\vec{yi}) = X(\vec{h} - \vec{y}) $$
$$ Hess(J(\vec{\theta})) = X^tSX$$
where $S = diag(\vec{h_i}(1-\vec{h_i})$.
So, I run the optimization but the function is throwing the error I've commented above. It is supposed to converge because the Hessian is positive definite but, if I compute the Hessian for the initial parameters (random) the Hessian is not positive definite. By the other side, if I try to optimize the parameters using Powell method it also gives a poor result but don't throw any error/warning.
Could you please help me with this issue please?
Thanks in advance,


text:
Q: I Gave My Site Access to My Gmail's Google Contacts... Now What? I'm trying to use the Google Contacts API to pull a list of contacts from Gmail.  I figured out how to give my site access to my Gmail account's contacts.  I'm not sure what the next step is.
What do I do next to allow my site to download a list of contacts?
Thanks in advance,
John
EDIT: Not sure if it's relevant to my question, but I am using PHP.  I've read up on how Google Contacts API delivers its results in XML format, but I'm not sure how to pull it using PHP.

A: To get a complete list of all contacts, do the following GET
GET https://www.google.com/m8/feeds/contacts/myname%40gmail.com/full

(replacing myname%40gmail.com with the relevant gmail address.)
See here for more details


text:
Q: regex does not remove non digits from string I have the following string "item number:237728"
I'm applying replace
str.replace(/[^0-9]/g,'');

but the string does not change, non digits are not removed. any idea why?
thanks

A: This worked, try pasting into the location box of your browser:
javascript:alert("item number:237728".replace(/[^0-9]/g,""))

As Neal says, I suspect your problem might be that of string mutability. Make sure you catch the return value from replace().

A: Are you assigning the returned value and using that,  e.g. str = str.replace(/[^0-9]/g,'');, or expecting the original string to change?
String functions don't modify the original string, they return the modified strings.


text:
Q: Does Delphi provide access to the Android Auth.GoogleSignInApi class? More specifically, is it possible to translate this Java code, which retrieves a ID token, to Delphi?
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
    GoogleSignInAccount acct = result.getSignInAccount();
    String idToken = acct.getIdToken();
    mIdTokenTextView.setText("ID Token: " + idToken);
    // TODO(user): send token to server and validate server-side
} else {
    mIdTokenTextView.setText("ID Token: null");
}

I could not find a wrapper class in the Delphi Docwiki, or a feature request in the quality portal.

A: I'm not sure which library you need to use in your particular case or if it's already included in Delphi but using the supplied Java2OP tool, it should be possible to generate Delphi wrapper units to use any custom Java library.


text:
Q: CKEDITOR on blur event not working Using ck editor i'm trying to create a DIV that is editable and when it is changed fire an event, which eventually will call an ajax request. I've seen this stack overflow page however I cant seem to figure out why it isn't working. The navbar.php is where I link all the libraries that I will need.
Any help would be greatly appreciated, thanks.
HTML:
<?php
  include"navbar.php";
?>

        Hi this is editable

        Some text

JS:
$(document).ready(function(){
  CKEDITOR.disableAutoInline = true;
  CKEDITOR.inline("editor1",{
    on: {
      blur: function(){
        var data = CKEDITOR.instances.editor1.getData();
        console.log(data);
      }
    }
  });
})

Navbar libraries:

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

<link rel="stylesheet" href=" https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css ">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/sweetalert2/6.4.4/sweetalert2.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.25.0/codemirror.min.css">

<link href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.6.5/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.6.5/css/froala_style.min.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" href="css/navbar.css">

A: Trying out your code I have noticed that CKEDITOR.disableAutoInline = true; is executed too late causing error which results in inline method not being called. The CKEDITOR.disableAutoInline = true; needs to be called before the first editable element is loaded.

$(document).ready(function(){
  CKEDITOR.inline( "editor1" ,{
    on: {
      blur: function( evt ){
        console.log(evt.editor.getData());
      },
      change: function( evt ){
        console.log(evt.editor.getData());
      }
    }
  });
});

    Inline Editor Content Title

    Inline Editor Content...


text:
Q: Motion - takes snapshot without motion detected I've been installed the standard motion 3.2.12 package on debian 7.5.
I would like to get snapshot ONLY when motion is detected, but it still saves a picture every second without any activity in front of the camera.
I'm using a TENVIS JPT3815W IP camera
motion.conf
here is my configuration file
setup_mode off
target_dir /media/videos/log/webcam

netcam_url http://webcam/snapshot.cgi
netcam_tolerant_check on
netcam_userpass admin:alpha1237

# Output frames at 1 fps when no motion is detected and increase to the
# rate given by webcam_maxrate when motion is detected (default: off)
webcam_motion off
output_all off

# detection settings 1-255 default 32
noise_level 50
# Maximum framerate for webcam streams (default: 1)
webcam_maxrate 25
pre_capture 0

framerate 25
gap 30
locate on
mail technical@live.fr

text_right "FRONT CAMERA %Y/%m/%d - %T"
text_double on

ffmpeg_cap_new on
ffmpeg_cap_motion on
ffmpeg_video_codec mpeg4

output_motion off
snapshot_interval 0

# Quality of the jpeg (in percent) images produced (default: 50)
quality 90

# Restrict webcam connections to localhost only (default: on)
webcam_localhost off

# Limits the number of images per connection (default: 0 = unlimited)
# Number can be defined by multiplying actual webcam rate by desired number of seconds
# Actual webcam rate is the smallest of the numbers framerate and webcam_maxrate
webcam_limit 0

Issue
when I start motion images are stored  in /media/videos/log/webcam nearly every second. I hjust want to get images when a motion is detected and the according video clip
Any idea where the configuration fails ?

A: Check the following attributes (I'll show my values): snapshot_interval 0, threshold 1500, framerate 4, minimum_motion_frames 1, emulate_motion off.


text:
Q: VPL start with java I am trying to create a generic node that can modified and to ones wishes but I have run in some trouble because my skills in Swing and such is not so good.
Problem 1: I can't seem to get two Node/Jpanels in the same JFrame.
lesser Problem 2: The stroke is cut off from the JPanel border (Should I build in a kind of bleed so this will not happen?)
Any aid is helpful :)
public class SimpleGui {

    public SimpleGui() {
        JFrame frame = new JFrame();

        NodePanel panel = new NodePanel(3, 2);
        panel.setLayout(new javax.swing.SpringLayout());
        frame.add(panel);

        NodePanel panel2 = new NodePanel(3, 2);
        panel2.setLayout(new javax.swing.SpringLayout());
        frame.add(panel2);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setResizable(true);
        frame.setVisible(true);

        panel.setLocation(50, 50);
        panel2.setLocation(150, 150);
    }
}

The generic node/panel class that is added to the JFrame:
public class NodePanel extends JPanel {

    private int x = 0, int y = 0;
    private PortPanel inPortPanel;
    private PortPanel outPortPanel;
    int iH;
    int oH;
    private int width = 120;
    private int height = 30;
    Graphics2D g2;

    public NodePanel(int input, int output) {

        inPortPanel = new PortPanel(input);
        this.add(inPortPanel);

        outPortPanel = new PortPanel(output);
        this.add(outPortPanel);

        setPreferredSize(calculateDimension());
    }

    public void paintComponent(Graphics g) {
        g2 = (Graphics2D) g;

        g2.setColor(Color.black);
        g2.setStroke(new BasicStroke(4));

        inPortPanel.setLocation(x, y + (height - iH) / 2);
        outPortPanel.setLocation(x + width, y + (height - oH) / 2);

        drawNode();
    }

    private void drawNode() {
        g2.drawRoundRect(x, y, width, height, 5, 5);
    }

    private Dimension calculateDimension() {

        iH = inPortPanel.getPreferredSize().height;
        int iW = inPortPanel.getPreferredSize().width;
        oH = outPortPanel.getPreferredSize().height;
        height = iH > oH ? iH + iW : oH + iW;

        return new Dimension(width, height);
    }
}

The port panel that is part of the Node Panel
public class PortPanel extends JPanel {

    int x = 0;
    int y = 0;
    int portWidth = 14;
    int portHeight = 14;
    int count = 0;
    int offset = 22;
    Graphics2D g2;

    public PortPanel(int i) {
        this.count = i;
        setPreferredSize(calculateDimensions());
    }

    public void paintComponent(Graphics g) {
        g2 = (Graphics2D) g;
        g2.setColor(Color.black);
        drawPorts();
    }

    private void drawPorts() {
        for (int i = 0; i < count; i++) {
            g2.fillOval(x, y + (i * offset), portWidth, portHeight);
        }
    }

    private Dimension calculateDimensions(){
        int overallHeight = (offset * (count-1)) + portHeight;
        return new Dimension(portWidth,overallHeight);
    }
}

A: *

*Node should be a logical class, not a GUI component class.

*You should have a single drawing JPanel that can draw all the visual representation of your logical entities.

*This way the model can hold multiple logical entities that all can be drawn by the single drawing JPanel without having to worry as much about layout managers.

*Don't forget to call your JPanel's super.paintComponent method within its override method so your JPanel can do house-keeping painting.

*Avoid giving your JPanels Graphics or Graphics2D fields as that increases the risk of your code throwing a NPE. Use the Graphics object given to your paintComponent method, and if you need to use it in another method that is called by paintComponent, pass it into that method.


text:
Q: Google analytics - do exceptions stop session? I use google analytics to track user behaviour in an application. What I do is this:

*

*Send a start session

*Send a custom event "Lifetime start"

*If there is an error: send a fatal exception

*Send a custom event "Lifetime stop"

*Send a stop session
Now when I look at the statistics, I see that a certain percentage of users had an exception over tha last 30 days. However, all users have had sessions without exception!. This is almost impossible, since I know there are users where the application crashes every time.
Is it possible that the fatal exception I submit terminates the session? So even users where the app crashes everytime get a second (short) session, containing only the "Lifetime stop" custom event? (That would explain my statistics)

A: That being said, I ran a test using Universal Analytics via the web (so this was not done in an app), but the results should be consistent with your setup.
I started a session and sent a "Before Exception" event which showed up in my real-time event report. I then waited a few seconds and successfully sent a fatal exception (which there is not a real-time report for). Without refreshing I then sent an "After Exception" event which came through fine in my real-time report.
From the following screenshot (User Explorer), you can see the two "Exception Test" events that I described both in the same session.

I would think that whatever fatal crash you're seeing is what is preventing additional data from appearing in Google Analytics- not that Google Analytics is ending the session at the time of the fatal exception. If it was ending the session, you'd still see events for "Lifetime stop", but it sounds like you aren't seeing those events at all.
The only things that end a GA session:

*

*Session timeout (default: 30 minutes)

*End of day

*UTM/AdWords/Referral

*Manually ending the session as you described
You may need to come up with some context clues to actually get to the bottom of this (maybe a remote server log?), but from the information provided (and if I'm understanding it correctly) I'm leaning towards the crash preventing the rest of the code from running.


text:
Q: What is the difference between accessing the Global Keys using InheritedWidget and defining them Globally? Using InheritedWidget I need to doKeysToBeInherited.of(context).homeKey1 for using the keys in different parts of the app:
    class ShowcaseStatefulWidget extends StatefulWidget {
  @override
  _ShowcaseStatefulWidgetState createState() => _ShowcaseStatefulWidgetState();
}

class _ShowcaseStatefulWidgetState extends State<ShowcaseStatefulWidget> {

  final GlobalKey _homeKey1 = GlobalKey();
  final GlobalKey _homeKey2 = GlobalKey();
  final GlobalKey _homeKey3 = GlobalKey();
  final GlobalKey _storeKey1 = GlobalKey();
  final GlobalKey _storeKey2 = GlobalKey();
  final GlobalKey _storeKey3 = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return KeysToBeInherited(
       homeKey1: _homeKey1,
       homeKey2: _homeKey2,
       homeKey3: _homeKey3,
       storeKey1: _storeKey1,
       storeKey2: _storeKey2,
       storeKey3: _storeKey3,
      child: AppRoutes(),
    );
  }
}

class KeysToBeInherited extends InheritedWidget {
  KeysToBeInherited({
    required this.homeKey1,
    required this.homeKey2,
    required this.homeKey3,
    required this.storeKey1,
    required this.storeKey2,
    required this.storeKey3,
  }) : super(child: child);

  final GlobalKey homeKey1;
  final GlobalKey homeKey2;
  final GlobalKey homeKey3;
  final GlobalKey storeKey1;
  final GlobalKey storeKey2;
  final GlobalKey storeKey3;

  static KeysToBeInherited? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<KeysToBeInherited>();
  }

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return true;
  }
}

Or defining the like:
  final GlobalKey homeKey1 = GlobalKey();
  final GlobalKey homeKey2 = GlobalKey();
  final GlobalKey homeKey3 = GlobalKey();
  final GlobalKey storeKey1 = GlobalKey();
  final GlobalKey storeKey2 = GlobalKey();
  final GlobalKey storeKey3 = GlobalKey();

Both approche work and I am not sure which one should I pick, and what are the prose and cons of using either approch?
ShowcaseStatefulWidget does not ncessarily need to be statefull.
The AppRoute() is where I define Matterial app and the routes.

A: if your keys are constant use the second approach and if your keys might change and you need your children to be notified, use the first approach.