text:
Q: Prestashop : Get products by features In my module on Prestashop I need to display list of products but I need to get them by features, for example : i need to get all products where the id feature 1 has the id value 2.
Is this function exist in Prestashop ?

A: This could be your solution:
$featuresObj = new Product($product['id_product']);
$features = $featuresObj->getFrontFeatures($this->context->language->id);

foreach($features as $feature)
{
    var_dump($feature);
}


text:
Q: Trying to create a new drive under a user MsGraph I am trying to make a Post to add a new Drive to an already existing user but I am getting request invalid. I don't know if I am missing something or if it is not possible.
var createNewDrive = await graphServiceClient
    .Users["5715609d-b9b6-471a-b337-bdc9a98dca2f"]
    .Drives
    .Request()
    .AddAsync(new Drive()
    {
        Name = "PleaseWork",
        DriveType = "documentLibrary"
    })
    .ConfigureAwait(false);

A: #1 - First get the list of drives for the user. This will give the list of all drives for the given user.
GET https://graph.microsoft.com/v1.0/users/MeganB@M365x214355.onmicrosoft.com/drives
#2 - Now look for the newly created drive for the user by checking it's ID's or display name. Here i assume that i have the id for the newly created drive (say either i got it from the delta or captured the ID when the new drive is created).
say, id: b!-RIj2DuyvEyV1T4NlOaMHk8XkS_I8MdFlUCq1BlcjgmhRfAj3-Z8RY2VpuvV_tpd
#3, Now get the items from the above drive:
GET https://graph.microsoft.com/v1.0/users/MeganB@M365x214355.onmicrosoft.com/drives/b!-RIj2DuyvEyV1T4NlOaMHk8XkS_I8MdFlUCq1BlcjgmhRfAj3-Z8RY2VpuvV_tpd
Here's the documentation for getting the onedrive or list the drives.
Also here's the C# code as well:
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var drive = await graphClient.Users["MeganB@M365x214355.onmicrosoft.com"].Drives["b!-RIj2DuyvEyV1T4NlOaMHk8XkS_I8MdFlUCq1BlcjgmhRfAj3-Z8RY2VpuvV_tpd"]
.Request()
.GetAsync();

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'DeprecationWarning: Collection#find: pass a function instead' i am trying to make a bot dm all members with a specific role, but get the error: DeprecationWarning: Collection#find: pass a function instead
here is the code:

  //dm
  if (command === "dm") {
    const args = message.content.split(" ");
    const roleArgs = args.slice(0, 1);
    const messageArgs = args.slice(1)

    const role = message.guild.roles.find("Members")
    if (!role) return message.reply('There is not such a role!');

    for (let i = 0; i < message.guild.members.size; i++) {
        if (message.guild.members.roles.has(role.id)) {
            message.guild.members.user.send(messageArgs.join(" "))
        }
    }
  }

A: You have to use a function for the find. Replace this line:
const role = message.guild.roles.find("Members")

With this line:
const role = message.guild.roles.find(r => r.name === "Members");

EDIT:
For your other issue, you are trying to access role of multiple members. That does not work. Replace your for loop with this:
message.guild.members.forEach(m => if(m.roles.has(role.id)) { m.user.send(messageArgs.join(" ")) });


text:
Q: Reporting services 2005: Is there a way to dymanically change a report header? I have a report that needs different header text on pages depending on the content of the page. Is there a way change the text in the header based on a piece of information on a page?

Page 1 header:   ITINERARY
Page 2 header:   ITINERARY
Page 3 header:   FARE RULES
Page 4 header:   RECEIPT

The other issue is that each section of information may be one or more pages long.
At the moment I've had to set out my report spacing out the pages and putting a dummy header at the start of each section.
What is the best way to do this?

A: Melissa,
You might be able to dynamically render the header content by using the Expression part of the header.  Your logic might go something like this:
If ReportItems!Textvalue = "this", do "that"
When I mean the Expression part, right click on the textbox (assuming that's what you're using in the header) and change the expression from there.  You also might want to look at the IIF (Immediate If) function too.
For example:
Dim i As Integer = 0
IIf(i = 0, "I am zero", "I am not zero")
Hopefully that should get you in the right direction as I employed a similar situation with Reporting Services last year.
coson

A: Maybe you can find some info here: http://www.bigresource.com/MS_SQL-SSRS-Dynamic-Header-Jy99Q93u.html (scroll down to see more header-related links)
Or is this what you are looking for? http://social.msdn.microsoft.com/forums/en-US/vsreportcontrols/thread/a82d32e1-2314-4c09-a828-6ce2109a0252

A: What you could do is create each report section in its own separate report, then create a "Master" report that has all of the other reports as sub reports. Then all you'd have to do is put the headers on the master page.


text:
Q: Code is working fine in chrome, but not in IE and Firefox I have some code here. That is working fine in Chrome, but not in IE and Firefox.
$(document).ready(function(){
    $(".thumb").click(function(){
        alert ("Reached here.");
        var cat_id = $(this).attr('id'); // get category id
        alert (cat_id);

    });
});

Its even not hitting the alert in Firefox and IE. Can someone please help me to identify the issue.
Any help will be highly appreciated.
Devesh

A: It looks like a bug with jQuery 2.0.2. I fiddled it and IE threw errors on just the $(document).ready().
SCRIPT5: Access is denied. jquery-2.0.2.js, line 1378 character 2
SCRIPT5009: '$' is undefined _display, line 21 character 1

Swapped the jQuery version to 1.9.1 and everything worked fine.
http://jsfiddle.net/taneleero/pLRNF/3/

A: Keeping everything to be done together in one call to $(document).ready ensures no problems with race-conditions etc in which order the functions added are called.
If one function adds the element to the DOM and another require its presence you might get conflicts and unexpected behavior due to varying calling order...


text:
Q: Flutter Dependencies Error DART I am doing an App in flutter, and i had the following issue

/Users/pedro/Desktop/Development/flutter/bin/flutter --no-color packages get
  Running "flutter packages get" in wemystic...
  The current Dart SDK version is 2.1.0-dev.0.0.flutter-be6309690f.
  Because flutter_cache_manager >=0.1.0-rc.1 depends on uuid >=0.0.7 <1.0.3 which requires SDK version <2.0.0, flutter_cache_manager >=0.1.0-rc.1 is forbidden.
  So, because wemystic depends on flutter_cache_manager 0.1.0-rc.1, version solving failed.
  pub get failed (1)
  Process finished with exit code 1

My dependencies in pubspec.yaml are:

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  firebase_auth: any
  google_sign_in: any
  flutter_html_view: any

Thanks

A: The flutter_cache_manager package is outdated and needs update

*

*https://github.com/renefloor/flutter_cache_manager/issues/26

*https://github.com/renefloor/flutter_cache_manager/issues/41
Adding this to pubspec.yaml should fix it as workaround until the package is updated
dependency_overrides:
  uuid: ^1.0.3


text:
Q: Python run a file as adminstrator as the title says, I'm trying to figure out a way to run a file as an adminstrator.
tried all of the answers I found online with no success... this one seems to be the closest to my needs -
prog = subprocess.Popen(['runas', '/noprofile', '/user:userAdmin',
'filepath.exe'], stdin=sp.PIPE)
prog.stdin.write('password')
prog.communicate()

problem with the code above is that it just doesn't run the program if the file requires admin privilages... (no errors are showed).
tried to run same on a file which doesn't require admins privilage works fine.
help! :)
thanks for reading.


text:
Q: How to create a virus isolating environment to run children games
*

*I have a Linux Centos 6 server in the garage without a monitor or keyboard, and it does not hold any sensitive information.

*My wife has a Windows 7 laptop which she surfs the Internet, checks emails, uses MS Word, and pays bills online.

*My 10 year old Daughter wants to play Minecraft on the laptop, spent the past 2 weeks earning money to buy the base program, and now needs to download various executable programs.

I am a little nervous about my wife surfing the Internet on the same Machine that she pays bills, but I am very nervous about my Daughter running executables, so I told her last night she couldn't play Minecraft on the laptop, and she burst off in tears.
Without buying a new PC, what options do I have to be reasonably safe? I am thinking of creating a virtual box on the Linux server, install Windows and Minecraft on it, and somehow letting access that platform via the laptop and play her game.  Is this possible, will it contain most viruses, and if so how?  Thank you

A: Minecraft is a virus-free game, so your daughter can safely install and play it on laptop. You don't need to worry about that.
Anyways, there is also a java runnable file for Minecraft, too. You can try installing JRE first, and then run the .jar file. This way your daughter won't run executables!


text:
Q: Getting a error in PDO My previous question was using the mysql_* which is depreciated. I am now learning to convert mysql_* to PDO but am getting an error when I try to run the file. The error is :

 Catchable fatal error: Object of class PDOStatement could not be converted   to string in C:\xampp\htdocs\username_check.php on line 13

now my php is this:
<?php
require_once 'db_connect.php';

 $conn = dbConnect();
  if (isset($_POST['username']))
{
    $username = $conn->prepare($_POST['username']);

    if (!empty($username))
{
        $username_query = $conn->query("SELECT COUNT(id)
                                       FROM users
                                       WHERE username = '$username'");

 //where am getting the error line 13 is above//

                    $username_query->execute();
        $num_rows = $username_query->fetchColumn();

         if($num_rows==0)
         {
           echo "Username doesn't exist";
           exit;
         }
        else
        {
          echo "Username already exists";
          exit;
        }
   }
}

?>

my connection php is this:
 <?php

 function dbConnect(){
 $db = null;
 $db_host = "localhost";
 $db_username ="user";
 $db_pass ="pass";
 $db_name = "logins";

try{
$db = new PDO('mysql:host='.$db_host.';dbname'.$db_name,$db_username,$db_pass);

}
catch (PDOException $e) {
  echo '
Cannot connect to database !!
';
  exit;
}
return $db;
}
?>

I am also going to show my jQuery just incase the bug is in there:
 jQuery( '#box1' ).keyup(function(){
var username = jQuery(this).val();

jQuery( '#msg_out1' ).html('   Checking availability... ');

 if (username != '') {
 jQuery.post('/click/username_check.php', { username: username }, function(data){
    jQuery( '#msg_out1').text(data);

 });
 }else {
 jQuery( '#msg_out1' ).html('Choose a Username.').css('color','grey').css('font-size','15px').css('margin-left','40px');
 }
 });

A: First, you're doing this the wrong way, preparing does not work like mysqli_real_escape_string..
What you need to prepare is the statement which in your case should look like this
"SELECT COUNT(id)
                                       FROM users
                                       WHERE username = :username"
then, when executing, you need to bind the parameters to your previous prepared statement so it should look like this
$username_query->execute(array(":username" => $_POST['username']));

So your final code which should work will look like this
<?php
require_once 'db_connect.php';

$conn = dbConnect();
if (!empty($_POST['username']))
{
    $stmt = $conn->prepare("SELECT COUNT(id)
                                   FROM users
                                   WHERE username = :username");

    $stmt->execute(array(":username" => $_POST['username']);
    $num_rows = $stmt->fetchColumn();

     if($num_rows==0)
     {
       echo "Username doesn't exist";
       exit;
     }
    else
    {
      echo "Username already exists";
      exit;
    }
}

?>

A: Ok, I am in for this rewriting craze, just to show the right way
db_connect.php
<?php
$db_host = "localhost";
$db_username ="user";
$db_pass ="pass";
$db_name = "logins";

$db = new PDO('mysql:host='.$db_host.';dbname'.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

main file
<?php
require_once 'db_connect.php';

if (isset($_POST['username']))
{
    $stmt = $db->prepare("SELECT 1 FROM users WHERE username = ?");
    $stmt->execute(array($_POST['username']));

    if($stmt->fetchColumn())
    {
        echo "Username already exists";
    }
    else
    {
        echo "Username doesn't exist";
    }
}

Always try to avoid useless and unnecessary code.
All the explanationd for the above code you can find in the tag wiki: https://stackoverflow.com/tags/pdo/info

A: Yeah... that's super wrong.
$username_query = "SELECT COUNT(id) FROM users WHERE username = ?";

if( ! $sth = $conn->prepare($username_query) ) {
  // probably an error in your SQL syntax
  die( "Prepare error: " . var_export($conn->errorInfo(), true) );
}

if( ! $sth->execute(array($_POST['username'] ) {
  // probably a SQL integrity constraint violation [ie: duplicate key] or a server error
  die( "Execution error: " . var_export($sth->errorInfo(), true) );
}

if( $sth->rowCount() ) {
  echo "Username exists.";
} else {
  echo "Username does not exist.";
}

A: Read the PHP Manual carefully before you use it. There is a lot of examples on it and explain how to use it in Detail.
In Manual it said:

*

*PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.
so if you use query() to fetch your result, you don't need to run prepare() and execute(), just do it as follows:
$sql = 'select count(id) from test';
$return = $dbh->query ( $sql );
$result = $return->fetchColumn();

If you will execute the query multiple times in the code below, you can use a prepare statement(something like a compiled code):

*

*Prepares an SQL statement to be executed by the PDOStatement::execute() method.
and to do it:
$username = $_POST['username'];
$sql = "SELECT COUNT(id) FROM users WHERE username = ?";

$stmt = $conn->prepare($sql);
$stmt->bindParam(1,$username);
$stmt->execute();

$result = $stmt->fetchColumn();

Don't misunderstood these two kinds of statements.


text:
Q: Has anyone come across this php error before, Warning: imagejpeg()? Warning: imagejpeg() [function.imagejpeg]: Unable to open '/home/SITENAME/public_html/files/cache/052f225905c1618003df0c5088aec7a9.jpg' for writing: Permission denied in /home/SITENAME/public_html/concrete/helpers/image.php on line 172

I emptied the cache directory and still no luck, and if I change the permissions on the cache folder then I get another error and I can't use the site at all:
Warning: require_once(Zend/Cache/Backend/File.php) [function.require-once]: failed to open stream: No such file or directory in /home/MYACCOUNT/public_html/concrete/libraries/3rdparty/Zend/Cache.php on line 133

Fatal error: require_once() [function.require]: Failed opening required 'Zend/Cache/Backend/File.php' (include_path='.:/usr/lib/php:/usr/local/lib/php:/home/owen/php') in /home/MYACCOUNT/public_html/concrete/libraries/3rdparty/Zend/Cache.php on line 133

I don't get it? I've never had this problem before.

A: Sounds like a permissions problem to me, but we can't tell from this end.
If you can FTP (or CD) into that /home/SITENAME/public_html/files/
and see if 'files' is owned by, and has the same permissions as public_html
Then see what permissions they NEED to have for your hosting setup.

A: *

*Check that directory exists.

*Check if web server daemon, most of the time - www-data, has write permissions to that particular directory.

A: For future reference the problem was the PHP handler. It has been changed to CGI mode (as opposed to DSO) and they turned suEXEC 'off' - might be useful for someone down the line.


text:
Q: How do I detect collisions in a 2D project in Unity (without using a RigidBody2D)? I'm trying my hands on Unity for the first time and, as a "hello-world" kind of project I'm aiming for a 2D "Asteroids" game.
I'm advancing well, but the collisions are causing me headaches. They don't register. I've tries with and without a RigidBody. But The RB forced me to set it to Kinematic as it would otherwise fall down due to gravity, which is not what I want in a top-down shooter.
I tried setting "Full Kinematic Contacts" without any luck.
There are many different possible combinations and I can't find the right one. Rigid Body or not? Collider or not? Maybe both?
Here's a little demo project that reproduces the issue. I would expect it to show a log-line in the console when the circle touches the square. But it does not. How do I get that done?
https://github.com/exhuma/unity-collision-test

A:
The RB forced me to set it to Kinematic as it would otherwise fall
down due to gravity

You may uncheck the gravity in Rigidbody component. (Gravity Scale on Rigidbody2D)
Rigidbody is a way to contact with physics.

Rigid Body or not? Collider or not? Maybe both?

Add both.
I had viewed you code on github and I would like to suggest
Use Velocity
rigidbody.velocity = new Vector2(300 * Time.deltaTime, 0);

instead of
transform.Translate(Vector2.right * Time.deltaTime * 3);

and also add
public Rigidbody2D rigidbody;
void Start()
{
     rigidbody = GetComponent<Rigidbody2D>();
}

The script attached gameobject must have Rigidbody2D

Here is the doc link:
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
Thanks


text:
Q: Why do mobile devices have to periodically check servers for updates? I understand that some applications need to check against a server periodically, but why don't servers let a mobile device know when it's time to update.
For example, let's say you receive an e-mail in gmail. As it stands now, there can be a delay between receiving the e-mail and your device notifying you. I assume this has to do with waiting until the device has checked the gmail server, at which point it sees the new e-mail and notifies the user. It makes more sense to me that when the gmail server receives an e-mail, it should ping (or however the creator wants to implement it) all registered devices to let them know that it's time to update. This way notifications would be synchronized and mobile device could save battery by not having to periodically check a server.

A: What you are describing is called a "server push". Some mobile applications does use server push. And Google actually have a technology in place to make this easier to implement, named "Cloud to device messaging" (C2DM). It works by having the servers sending a tiny little message, via googles C2DM servers, to the application running on the device, informing it its time for a update. And the device then retrieves the actual update from the original server (not from C2DM).
Its good stuff. It allows the service listening for C2DM manages to wake up the phone and everything. The downside is, the user of the application needs a google account. For android users, this isnt really a downside though.

A: Except they do, in some cases. In the "Mail, Contacts, Calendars" section of Settings on my iPod, there's a submenu labeled "Fetch New Data", which contains an option to have the mail server or whatever "Push" the data to the iPod. The Fetch aspect, which you can set the schedule for, is for when Push is off or you're syncing with applications that don't support push.

A: That is how Android does it.  It pushes notifications to the device and that api is open to third party developers as well so they can push notifications to their users.

A: That thing is it is difficult to know the address of a mobile device at any particular time, the I.P address is dynamic, on a server the address is much more stable, so the device knows it will always find Google at google.com but Google has no real way of knowing where to find the device, it wouldn't know where to ping in the first place.
This is where push comes in, there are different implementations but i think they work by having the device maintain a connection to the server, and reestablishing it if its lost.
See http://en.wikipedia.org/wiki/Push_technology
This of course is much harder to implement and maintain then a simple client pull.


text:
Q: What triggers code first migration? How does the command Enable-Migration know whether to generate the migration code files?
I have the following in a project using the standard MVC 5 template in Visual Studio:
public class UsersContext : IdentityDbContext<ExtendedUser>
{
    public DbSet<Log> Logs { get; set; }

    public UsersContext() : base() { }

    public UsersContext(string ConnectionString) : base(ConnectionString) { }
}

public class Log
{
    public Int32 Id { get; set; }
    public DateTime Time { get; set; }
    public string Message { get; set; }
}

When I run Enable-Migrations, the Migrations folder is created but there is only the Configuration.cs file.  There is no code generated to handle the creation of the Logs table.
A second related question is: do I have to run Add-Migration every time there are model changes after the previous Add-Migration was run?

A: When you run Enable-Migrations, it searches the project for any DBContexts and configures that project to use migrations.
Do I have to run Add-Migration every time there are model changes after the previous Add-Migration was run?
Yes. Running Add-Mingration ... creates files that details your model changes.
Running Update-Database pushes your changes to the database. Update-Database -Script (before running just update-database) generates an SQL script of your model changes.
After you update the database, if you make more model changes, you would add another migration. And the cycle goes on...
See Tips for Entity Framework Migrations

A: Take note that Enable-Migrations is not the same as Automatic migrations.
Automatic migrations will, if enabled, automatically create and run your migration scripts during runtime, which means that you do not need to run the "add-migrations" and "update-database" commands manually every time your model is updated.


text:
Q: Visual Studio Code + Python Установил portable версию Python 3.6 (указана как совместимая с Windows 10) и Visual Studio Code. Добавил в переменные окружения все пути
переменная PATH

Переменная PYTHONPATH

При работе в VS Code (расширение Python от Microsoft) скрипты выполняются, но не видит IDE отладчик:
    pydev debugger: CRITICAL WARNING: This version of python seems to be incorrectly compiled (internal generated filenames are not absolute)
pydev debugger: The debugger may still function, but it will work slower and may miss breakpoints.
pydev debugger: Related bug: http://bugs.python.org/issue1666807
pydev debugger: Unable to find real location for: tokenize.py
pydev debugger: Unable to find real location for: codecs.py
pydev debugger: Unable to find real location for: urllib\parse.py
pydev debugger: Unable to find real location for: queue.py
pydev debugger: Unable to find real location for: C:\Users\abukreev\AppData\Roaming\Python\Python36\site-packages
pydev debugger: Unable to find real location for: threading.py
0b111001

Перерыл все настройки, не могу понять где прописать путь до установленного Python


text:
Q: Why do I get the error "the byte at index is not ASCII" when using AsciiString::from_ascii on a byte array? I am getting an error whilst running ascii::AsciiString::from_ascii on a byte array.
The error is thread 'main' panicked at 'Failed: the byte at index 3 is not ASCII'
The byte at position 3 is 137 which should be a ë. I also got the values of positions 2 and 4 just to be certain I wasn't getting anything wrong with the indexing and they all appeared to have suitable values.
bytes[2] = 38  // &
bytes[3] = 137 // ë
bytes[4] = 56  // 8
I don't understand what I am doing wrong here. Reading the documentation for this function I am not entirely sure why this won't work.
What am I doing wrong and why is this error being thrown?

A: ASCII ends at ordinal value 127; ë is not ASCII (nor is 137 the ordinal value of ë in either latin-1 or cp1252, which people often mistake for ASCII). The error is correctly informing you of this.


text:
Q: play-services-base and support-v4 double method count According to methods.com play-service-base has a total of 15k methods. However, I've already included Android support-v4 (~9k methods) in my build.gradle. Is there anyway to make sure that the total method counts in my app is 15k instead of 24k = 15k + 9k?
My build.grade:
...
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
    androidTestCompile('com.android.support.test:runner:0.5') {}
    androidTestCompile 'com.android.support.test:rules:0.5'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.2') {
        exclude group: 'com.android.support', module: 'design'
        exclude group: 'com.android.support', module: 'appcompat'
        exclude group: 'com.android.support', module: 'support-v4'
        exclude module: 'recyclerview-v7'
        exclude module: 'support-annotations'
    }
    androidTestCompile 'com.android.support:support-annotations:23.4.0'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.1@aar') {
        transitive = true;
    }
    compile('com.android.support:appcompat-v7:23.4.0') {
        force true
    }
    compile('com.android.support:support-v4:23.4.0') {
        force = true;
    }
    compile('com.android.support:recyclerview-v7:23.4.0') {
        force = true;
    }
    compile('com.android.support:cardview-v7:23.4.0') {
        force = true;
    }
    compile('com.android.support:design:23.4.0') {
        force = true;
    }
    apt 'com.jakewharton:butterknife-compiler:8.2.1'
    compile 'com.android.support:percent:23.4.0'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.google.android.gms:play-services-base:9.2.0'
    compile 'com.google.android.gms:play-services-location:9.2.0'
...
}
...

The results from the Android plugin:

A: Method counts are not strictly additive like that. The 64k method limit is a limit on the number of entries in the method_id_item list in the dex file. This is a list of unique method ids (class name + method name + parameters + return type) that are referenced anywhere in the dex file. So any methods that are referenced from both libraries will be de-duplicated in the final dex file, and the total method count contributed by both will be somewhat less than the 15k + 9k from the individual libraries.

A: Currently there isn't a function in the stable version of Android Studio.
There is a beta analize in the beta versions.
However you can use some tools to count the methods:

*

*dexcount-gradle-plugin reports the number of method references in your APK or AAR on each build

*dex-method-counts is a commandline tool that counts the number of method references in an APK

*www.methodscount.com is a web service which will count the method references in any APK that you upload.

You can also use this gradle plugin to count the methods:
   apply plugin: 'com.android.application'
    apply plugin: 'com.getkeepsafe.dexcount'

    buildscript {
        repositories {
            mavenCentral() // or jcenter()
        }

        dependencies {
            classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.5.5'
        }
    }

However you can make your APK file as small as possible by using the split support-v4 libraries with the new 24.2.0


text:
Q: Eclipse - plugin for feeding html syntax? I'm trying to make use of Eclipse to be my primary tool for making websites, but I'm looking for a functionality that exists in Dreamweaver - html attributes sugestions. Is there any plugin that would enable that?
I'm already using HTML Tidy for checking the syntax. (I was going to use it to format, but I cannot get used to code being so tighthly formatted.)

A: Take a look at Aptana Studio
There are few versions (2nd, 3rd, 2nd for Ruby support); the 3rd one is still beta. It can be used as it is, or can be installed as plugin for your Eclipse.
IMHO this is the best plugin if you need to use HTML/CSS/JavaScript and do it in Eclipse IDE (the reason does not matter :)
UPDATE: just forgot to mention that it has built-in support for popular JS frameworks (like YUI, jQuery, etc.).


text:
Q: laravel custom command to generate file I came across this article on Spatie Actions https://freek.dev/1371-refactoring-to-actions and I would like to make a command to generate the files for me, similar how you can generate Model or livewire components etc.
php artisan make:action PublishPostAction Post

This is as far as I got
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class GenerateActionTemplate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:action {name} {model}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new action file.';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $name = $this->argument('name');
        $model = $this->argument('model');

        $fileContents = <<<'EOT'
        <?php

        namespace App\Actions;

        class PublishPostAction // name
        {
            private $post;

            public function execute(Post $post) // model
            {
                $this->post = $post;
            }

        }

        EOT;

        $this->info($name . 'has been created successfully!');
    }
}

*

*How would I do the logic, so if I do like make:action post.PublishPostAction would create a new folder called post in App\Actions\Post\

*In the EOT how would I pass in the variables?

Any help or link to an example would be great! I have looked through a few tutorials and was able to scrap this up and laravel docs don't really show any example to generate a new file.

A: Here is the full code to get this working. You need to create 2 files.

// action.stub

<?php

namespace {{ namespace }};

use {{ namespacedModel }};

class {{ class }}
{
    private ${{ modelVariable }};

    public function execute({{ m }} ${{ modelVariable }})
    {
        $this->{{ modelVariable }} = ${{ modelVariable }};
    }
}

// makeAction.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;
use InvalidArgumentException;
use Symfony\Component\Console\Input\InputOption;

class makeAction extends GeneratorCommand
{
    protected $signature = 'make:action {name} {--m=}';

    protected $description = 'Create action file';

    protected $type = 'Action file';

    protected function getNameInput()
    {
        return str_replace('.', '/', trim($this->argument('name')));
    }
    /**
     * Build the class with the given name.
     *
     * @param  string  $name
     * @return string
     */
    protected function buildClass($name)
    {
        $stub = parent::buildClass($name);

        $model = $this->option('m');

        return $model ? $this->replaceModel($stub, $model) : $stub;
    }

    /**
     * Replace the model for the given stub.
     *
     * @param  string  $stub
     * @param  string  $model
     * @return string
     */
    protected function replaceModel($stub, $model)
    {
        $modelClass = $this->parseModel($model);

        $replace = [
            '{{ namespacedModel }}' => $modelClass,
            '{{ m }}' => class_basename($modelClass),
            '{{ modelVariable }}' => lcfirst(class_basename($modelClass)),
        ];

        return str_replace(
            array_keys($replace), array_values($replace), $stub
        );
    }

    /**
     * Get the fully-qualified model class name.
     *
     * @param  string  $model
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    protected function parseModel($model)
    {
        if (preg_match('([^A-Za-z0-9_/\\\\])', $model)) {
            throw new InvalidArgumentException('Model name contains invalid characters.');
        }

        return $this->qualifyModel($model);
    }

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return  app_path().'/Console/Commands/Stubs/action.stub';
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Actions';
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['model', 'm', InputOption::VALUE_OPTIONAL, 'Model'],
        ];
    }
}

Command to run
PHP artisan make:action task.AddTaskAction --m=Task

it will create the following file
<?php

namespace App\Actions\task;

use App\Models\Task;

class AddTaskAction
{
    private $task;

    public function execute(Task $task)
    {
        $this->task = $task;
    }
}


text:
Q: Android ListView alpha in background color only I have a list view and now all cells have white background.
What I want is to keep the white color in listview's background and put some "alpha" value to make it semi transparent so the user can see the whole view's background.
If I put android:alpha in listview , everything gets alpha ( the content too ). I want the content of the listview to be fully visible and the background color to be semi-transparent. Is there any way to achive this?

A: Don't use white color as background, define a color in resources that has a transparency, you could do something like #66FFFFFF, this is a transparent white.


text:
Q: How to write conditions for paginate finder to retrieve items based on associated item in a many to many relation? I am using CakePHP 3.x
I am following the bookmarkr tutorial found here and here
I want to add one more feature where I can fetch bookmarks that belong to the same tag based on tag id.
I wrote the following function in BookmarksController
/**
 * Index view by tag method
 *
 * @return void
 */
    public function index_by_tag($tag_id) {
        $conditions = [
            'Bookmarks.public' => true,
        ];
        $this->paginate = [
            'conditions' => $conditions,
            'contain' => [
                'Users' => function ($q) {
                   return $q
                        ->select(['username', 'id']);
                }
            ],
            'order' => [
                'Bookmarks.updated' => 'desc',
                'Bookmarks.id' => 'desc'
            ]
        ];
        $this->set('bookmarks', $this->paginate($this->Bookmarks));
    }

How should I alter the $conditions so I can retrieve only those bookmarks that belong to same tag?
Bear in mind that Bookmarks and Tags are in a many to many relation.
UPDATE1
I found this idea of using matching. Which gets me what I want if I use query builder.
See http://book.cakephp.org/3.0/en/orm/query-builder.html#using-matching-when-finding-results
However, there is no mention of how to use matching with paginate.
UPDATE2
I just realized there is already a custom finder method that does what I want except that it does not work with the paginate.
http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html#getting-bookmarks-with-a-specific-tag

A: The answer lies in changing the tags action in BookmarksController.php
Originally in the tutorial, the tags action look like this:
public function tags() {
    $tags = $this->request->params['pass'];

    $bookmarks = $this->Bookmarks->find('tagged', [
        'tags' => $tags
    ]);

    $this->set(compact('bookmarks', 'tags'));
}

The change lies in changing how to define $bookmarks.
public function tags() {
    $tags = $this->request->params['pass'];

    // you can call custom finder methods within paginate
    // the link is at http://book.cakephp.org/3.0/en/controllers/components/pagination.html#using-controller-paginate
    // scroll down just a bit to look at custom finder methods
    $this->paginate = [
        'finder' => [
            'tagged' => [
                'tags' => $tags
            ]
        ]
    ];

    $bookmarks = $this->paginate($this->Bookmarks);

    $this->set(compact('bookmarks', 'tags'));
}


text:
Q: Sonata user bundle listing error I am getting below error when i try  to access  user listing(user/list).
An exception has been thrown during the rendering of a template ("Could not convert database value "" to Doctrine Type array") in "SonataAdminBundle:CRUD:list.html.twig".
I  had verified  mappings using app/console  doctrine:mapping:info and it is all fine
[OK]   Sonata\MediaBundle\Entity\BaseGallery
[OK]   Sonata\MediaBundle\Entity\BaseGalleryHasMedia
[OK]   Sonata\MediaBundle\Entity\BaseMedia
[OK]   Application\Sonata\MediaBundle\Entity\Gallery
[OK]   Application\Sonata\MediaBundle\Entity\GalleryHasMedia
[OK]   Application\Sonata\MediaBundle\Entity\Media
[OK]   Application\Sonata\UserBundle\Entity\Group
[OK]   Application\Sonata\UserBundle\Entity\User
[OK]   Sonata\UserBundle\Entity\BaseGroup
[OK]   Sonata\UserBundle\Entity\BaseUser
[OK]   FOS\UserBundle\Entity\Group
[OK]   FOS\UserBundle\Entity\User

A: The  issue happened because of corrupted entry in fos_user_user table. This happened when i tried to create user using command app/console fos:user:create --super-admin  and  row created  have username, roles as empty which triggered  error.
I had removed the corrupted row and it worked fine.

A: Every User in Sonata Admin with roles=null, will generate this error, to solve this search the database table user for Rules with empty or Null then delete or Update these Users


text:
Q: How to register custom exception in Intel SGX? I'm having difficulty to get my custom exception handler to work.
This is the Enclave code:
#include "Enclave_DivideZero_t.h"
#include "sgx_trts_exception.h"
#include "sgx_trts.h"
#include <string>

static char buf[200] = "Handler not called";

int divide_by_zero_handler(sgx_exception_info_t* info) {

    buf[0] = '1';
    return EXCEPTION_CONTINUE_EXECUTION;
}

void Enclave_DivideByZero() {
    Ocall_printf(buf);
    if (sgx_register_exception_handler(1, divide_by_zero_handler) == NULL) {
        Ocall_printf("register failed");
    } else {
        Ocall_printf("register success");
    }
    int a(1);
    int b(3/(a-a));
    (void) a;
    (void) b;
    Ocall_printf(buf);
}

We used buf as an indication of whether the handler has been actually executed. However, the output is this:
Enclave created!
[Ocall printf] - Handler not called
[Ocall printf] - register success
[Ocall printf] - Handler not called <-- should be: "1andler not called" ("1andler" instead of "Handler")

Also, here is the App code (i.e. the untrusted code)
#include "stdafx.h"
#include "sgx_urts.h"
#include "Enclave_DivideZero_u.h"
#define ENCLAVE_FILE _T("Enclave_DivideZero.signed.dll")
sgx_status_t createEnclave(sgx_enclave_id_t *eid) {
    sgx_status_t        ret   = SGX_SUCCESS;
    sgx_launch_token_t  token = {0};
    int                 updated = 0;
    ret = sgx_create_enclave(ENCLAVE_FILE, SGX_DEBUG_FLAG, &token, &updated, eid, NULL);
    return ret;
}
void Ocall_printf( char* str) {
    printf("[Ocall printf] - %s\n", str);
}
int _tmain(int argc, _TCHAR* argv[]) {
    sgx_enclave_id_t eid;
    sgx_status_t res = createEnclave(&eid);
    if (res != SGX_SUCCESS) {
        printf("App: error-, failed to create enclave.\n");
        return -1;
    } else {
        printf("Enclave created!\n");
    }
    Enclave_DivideByZero(eid);
    return 0;
}

The Problem: As you can see from the output indicates that the handler is registered successfully, but is not executed.
1- Why the registration doesn't work?
2- I tried to put the registeration with the App code, and for this I had to add the handler in the edl, the problem for this is passing the sgx_exception_info_t *info param, which is not clear which flags it needs (i.e. [in, .. <'flags'>]). So, is it correct to define it inside the Enclave?
p.s. I ran the code with Prerelease Mode.
[EDIT] I documented the project + code that I conducted on SGX here

A: So the question is a bit old now, but I got stuck at the same place, so maybe someone can still use my insight.
In trts_veh.cpp, where it is checked whether the exception was handled, it says in a comment that the "instruction triggering the exception will be executed again". This leads to the exception handling loop, as you noticed yourself.
However, you can increase the rip yourself, as it is stored in the pointer to the sgx_exception_info_t, by using "info->cpu_context.rip += 2;". Adding this inside your exception handler should do the trick.


text:
Q: Ubuntu 18.04 error install tesseract I've installed Ubuntu 18.04.
I've installed tesseract using sudo apt-get install tesseract-ocr
When I type:
tesseract -v

I had an error:
tesseract: symbol lookup error: /usr/lib/x86_64-linux-gnu/libtesseract.so.4: undefined symbol: pixaDisplayTiledInColumns

Below is the output of apt-cache policy tesseract-ocr:
Installed: 4.00~git2288-10f4998a-2
Candidate: 4.00~git2288-10f4998a-2
Version table:
   *** 4.00~git2288-10f4998a-2 500
          500 in.archive.ubuntu.com/ubuntu bionic/universe amd64 Packages
          100 /var/lib/dpkg/status

A: This is a bug of tesseract package, which is found in release 4.00~git2481-555f6ffc-1.
Do this:
sudo apt install libtesseract-dev libleptonica-dev liblept5
tesseract -v

If it did not help, just build tesseract from source...
Update 1:
You can do
sudo apt purge tesseract* libtesseract*
sudo apt autoremove --purge

to remove everything that belongs to tesseract  with configurations. However, it may also remove dependant packages, such as opencv (depends to libtesseract4)

A: On my clean Ubuntu 18.04 LTS VM with all updates Tesseract installs without any issues.
So it is completely operable.
The linked bug by @Olimjon is not related to current problem as it was reported after 18.04 LTS feature freeze.
On my system I have done the following:

$ sudo apt install tesseract-ocr -y

and got

$ tesseract -v
tesseract 4.0.0-beta.1
 leptonica-1.75.3
  libgif 5.1.4 : libjpeg 8d (libjpeg-turbo 1.5.2) : libpng 1.6.34 : libtiff 4.0.9 : zlib 1.2.11 : libwebp 0.6.1 : libopenjp2 2.3.0

 Found AVX
 Found SSE

$ apt-cache policy tesseract-ocr
tesseract-ocr:
  Installed: 4.00~git2288-10f4998a-2
  Candidate: 4.00~git2288-10f4998a-2
  Version table:
 *** 4.00~git2288-10f4998a-2 500
        500 http://archive.ubuntu.com/ubuntu bionic/universe amd64 Packages
        100 /var/lib/dpkg/status

So, if @mayurpanchal really want to solve Tesseract problem - then please update all packages in your system and install tesseract-ocr again and add requested output of ldd /usr/lib/x86_64-linux-gnu/libtesseract.so.4 to the question.
It may be PPA or third-party libraries issue.

A: Here is the solution for ubuntu 18.04
Please first install the libraries which are required for tesseract-ocr
sudo apt install libtesseract-dev libleptonica-dev liblept5

Then simply install tesseract using command
sudo apt install tesseract-ocr -y


text:
Q: Testing socket.io-client with Jest (React) - How do I simulate an event from the server? I built a simple React app that has a list component, together with another component that has a text input and a button.
When You add text in the input and click the button, that text is added to the list.
The app has a Node.js backend which communicates with the React client via Websocket (Socket.io). When the user clicks the button, what happens in practice is:

*

*The Socket.io client emits an event to the backend with the new item as the event payload

*The backend saves it to a database

*The backend then emits an event to all connected clients with the updated list.

*The client side listens for this 'update-list' event, and refreshes the list.

I want to test this app - basic UI testing.
Specifically, I want to test the functionality of adding text to the input, then clicking the button and validating that the text is added to the list.
As you can gather from my description above, to be able to create a UI test for this functionality that can be run independent of a backend, I need to simulate an 'update-list' event with a mocked payload in my Jest testing environment.
I know there are npm packages such as socket.io-mock But I couldn't figure out how to use them to simulate a specific event with a specific mock payload.
I couldn't find how this can be done anywhere, would appreciate any help.


text:
Q: Building Program-Specific Shortcuts in UNIX I have a program, called carmel, which I can run from the command line via:
carmel -h
or whichever suffix I chose. When loading a file, I can say:
carmel fsa1.fst where fsa1.fst is located in my heme folder, /Users/adam/.
I would prefer to have the default file location be, e.g., /Users/adam/carmel/files, and would prefer to not type that in every time. Is there a way to let UNIX know, when I type carmel to then look in that location?

A: There is no standard Unix shortcut for this behaviour. Some applications will check an environment variable to see where their files are. but looking at carmel/src/carmel.cc on GitHub, I'd say you'd have to write a wrapper script. Like this:
#!/usr/bin/env bash
# Save as ${HOME}/bin/carmel and ensure ${HOME}/bin is before
# ${carmel_bin_dir} in your ${PATH}. Also ensure this script
# has the executable bit set.

carmel_bin_dir=/usr/local/bin # TODO change this?
working_directory=${CARMEL_HOME-${HOME}/carmel/files}

if [[ ! -d "${working_directory}" ]]; then
    echo "${working_directory} does not exist. Creating."
    mkdir -p "${working_directory}" || echo "Failed to create ${working_directory}"
fi

pushd "${working_directory}"
echo "Launching ${carmel_bin_dir}/carmel ${@} from $(pwd)..."
${carmel_bin_dir}/carmel ${@}
popd

Alternatively, since the source is freely available, you could add some code to read ${CARMEL_HOME} (or similar) and submit this as a pull request.
Good luck!


text:
Q: Comparing floor and roof areas using QGIS? I am trying to show the available roof area for installing photovoltaic moduls in comparison to the respective floor area in QGIS.
I have two vector layers so far. One contains the floor area of the houses, the second one the appropriate roof areas. All I want is the amount of roof area in percent (or at least in m²) of their respective floor area. Important is, that only the roof areas that sit in the floor areas shall be involved. As you can see in the picture below, some of the roof areas are bigger then the floor areas. I thought this problem would be very easy to solve, even for a newbie like me, but i could not handle this yet.
So you can better imagine the problem, a screenshot of how it looks like:

A: For your goal

percent of roof area of their respective floor area (only the roof areas that sit in the floor areas)

I suggest the following steps:

*

*add a column with the floor area to the floor layer if it doesn't exist

*intersect the roof layer with the floor layer

*add a column with the intersection area to the intersection result layer

*compute the percentage as intersection area / floor area


text:
Q: Complex analysis using Kronecker delta.. I have some trouble with proving the formula below;
$$\sum_{k=1}^n \sin\Big(\frac{kr \pi}{n+1}\Big)\sin\Big(\frac{ks \pi}{n+1}\Big) = \frac{n+1}{2}\delta_{rs}$$
by making use of complex analysis for any $r, s=1, 2, 3, \ldots, n$.
To solve this, I wanted to use the Kronecker delta's property, $$\delta_{rs} = \frac{1}{n}\sum_{k=1}^ n{e}^{2\pi i \frac{k}{n} (r-s)}$$
So I changed the first formula using addition formulas for sinusoidal functions,
$$\sum_{k=1}^n \frac{1}{2}\left[\cos\Big(\frac{k\pi}{n+1}(r-s)\Big)-\cos\Big(\frac{k\pi}{n+1}(r+s)\Big)\right]$$
I'm stuck in this situation. How can I get started..?


text:
Q: Is there any foolproof way or method to ascertain that my sentence is perfectly grammatically correct? If you advise to consult an editor, how would I know that the editor is perfect in grammar? AI (artificial intelligence) apps cannot be as accurate as a human.
I don't understand why this question is off-topic and why it is closed and not accepting answers.

A: To answer your question, I think you're best chance is to go to someone with lots of credibility and experience. If you want to be very diligent, you can bring it to a few people. Of course, we're all humans and people we all make mistakes, but chances are that any mistakes a trained professional makes would go unnoticed by someone who isn't. There's also plenty of weird grammar in English where there are solid arguments for different grammatical structures, as in, there can be more than one right answer sometimes.


text:
Q: Selected value not showing when selecting from mat-select element with two radio groups inside I'm trying to create a dropdown that has two radio groups inside. It would look something like this:
Sort By:
  Option 1
  Option 2
  Option 3

Order:
  Ascending
  Descending

Image of the dropdown:

Left: image of what I'm trying to achieve Right: what happens when I make a selection (placeholder value remains):

I have the styling the way I want it but I'm running into an issue where when I make a selection, the dropdown does not populate with the selected value. I would want to show the value in the 'Sort By:' radio group.
sample.component.html
<mat-form-field class="c-table-header__sort" (click)="sort()">
  <mat-select class="c-table-header__sort-select" placeholder="Sort">
    <mat-option class="c-table-header__sort-select-option">

Sort by

      <mat-radio-group class="c-table-header__sort-select-option-rgroup__sort" #sortOptionGroup [(ngModel)]="radioData">
        <mat-radio-button name="order" class="c-table-header__sort-select-option-rgroup__sort-rbutt"
          *ngFor="let sort of sortOptions.options" [value]="sort">{{sort}}
        </mat-radio-button>
      </mat-radio-group>

Order

      <mat-radio-group class="c-table-header__sort-select-option-rgroup__order" #sortOrderGroup [(ngModel)]="radioTwoData">
        <mat-radio-button name="sort" class="c-table-header__sort-select-option-rgroup__order-rbutt"
          *ngFor="let sort of sortOptions.order" [value]="sort">{{sort}}
        </mat-radio-button>
      </mat-radio-group>
    </mat-option>
  </mat-select>
</mat-form-field>

sample.component.ts (relevant parts)
Component({
    ...
    encapsulation: ViewEncapsulation.None
})
export class BillPayScheduledDashboardComponent implements OnInit {

...

radioData;
radioTwoData;

...

    sort() {
        console.log(this.radioData);
        console.log(this.radioTwoData);
    }

}

sample.component.css (relevant parts)
.c-table-header__sort-select-option{
    min-width: 75px;
    min-height: 500px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.c-table-header__sort-select-option-rgroup__sort,
.c-table-header__sort-select-option-rgroup__order{
    display: flex;
    flex-direction: column;
}

As I'm writing this, I'm also wondering if putting this all in a form would be possible/easier. Appreciate any insights/solutions.

A: If you want to set the placeholder value of your mat-select to the currently selected radio button value you can do it like this.
In your component:
radioData = '';
radioTwoData = '';

getPlaceholder(): string {
  if (!this.radioData && !this.radioTwoData) {
    return 'Sort';
  } else {
    return this.radioData + ' ' + this.radioTwoData;
  }
}

And in your template:
<mat-select class="c-table-header__sort-select" [placeholder]="getPlaceholder()">

This will show the selected option(s) as the placeholder in your mat-select. If you want to display the selected values in the select element below the placeholder then you need to use the [value] binding of the mat-options, but as it seems from your question that is not what you want.

Here
  is a stackblitz of it all.


text:
Q: Why isn't the latest version of expo installed when trying to install it? I wanted to do the run:android command but found out that the expo-cli version I have is NOT compatible to install the expo SDK version that's required to run the run:android command; the SDK version required is 41 and above.
The expo-cli needed to have the SDKs of 41 and above is 4.4.1, which I've been trying to install but it didn't work well. After typing the command, the install process begins and everything seems to be installed as usual as in other packages. But when checking the version of the cli, it gives the same version as it was beforehand.
Why does this happen?
The last attempt was to uninstall and install it back again. Here are the commands and their results:

$ npm -g uninstall expo-cli

$ npm install -g --force expo-cli
npm WARN using --force I sure hope you know what you are doing.
npm WARN deprecated graphql-tools@3.0.0: This package has been deprecated and now it only exports makeExecutableSchema.\nAnd it will no longer receive updates.\nWe recommend you to migrate to scoped packages such as @graphql-tools/schema, @graphql-tools/utils and etc.\nCheck out https://www.graphql-tools.com to learn what package you should use instead
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated querystring@0.2.0: The
npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated uuid@3.0.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
C:\Users\User\AppData\Roaming\npm\expo -> C:\Users\User\AppData\Roaming\npm\node_modules\expo-cli\bin\expo.js
C:\Users\User\AppData\Roaming\npm\expo-cli -> C:\Users\User\AppData\Roaming\npm\node_modules\expo-cli\bin\expo.js
+ expo-cli@4.12.0
added 1646 packages from 751 contributors and updated 3 packages in 243.278s

P.S1: "run:android" command gives this:

$ expo run:androd
"run:androd" is not an expo command -- did you mean build:android?
 See "expo --help" for the full list of commands.

A: Understanding the problem
If I understand correctly; you upgraded Expo-CLI to latest version using: npm install -g expo-cli. This worked fine but you project still breaks with the wrong SDK error mentioned above?
Solution
It seems like you upgraded the Expo-CLI, not the Expo SDK version used for your specific project.
To upgrade your project to use the latest Expo SDK, use the command:
expo upgrade.
To upgrade you project to a specific Expo SDK, use the command:
expo upgrade @{required sdk version}

For example: expo upgrade @41.0.0

Upgrading Expo SDK
If you are behind a couple of versions, upgrading your project's Expo SDK version can be difficult because of the number of breaking changes and deprecations in each upgrade. Don't worry. This document links to all the breaking changes in each SDK version upgrade. We strongly recommend upgrading SDK versions incrementally if possible. Doing so will help you pinpoint breakages and issues that arise during the upgrade process.
Expo maintains ~6 months of backward compatibility. Once an SDK version has been deprecated, you will no longer be able to use the Expo Go app for development or build new binaries via expo build. However, you will still be able to publish updates via eas update, and build using eas build. Deprecations will not affect standalone apps you have in production.


text:
Q: how to animate google map view when change lat and lng? I added google map inside column.
my inspector like this:
Scaffold
 - stack
  - singlechildscrollview
   - form
    - container
     - padding
      - column
       - sizedbox
        - googlemap
                     SizedBox(
                          width: width,
                          height:height * .4,
                          child: GoogleMap(
                            gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>[
                              Factory<OneSequenceGestureRecognizer>(
                                      () => EagerGestureRecognizer())].toSet(),
                            mapType: MapType.normal,
                            initialCameraPosition: CameraPosition(
                                target: LatLng(lat, lng),
                                zoom: 15),
                            onCameraMove: (_)=>CameraPosition(
                                target: LatLng(lat, lng),
                                zoom: 15),
                            markers: Set<Marker>.of(<Marker>[
                          Marker(
                          markerId: MarkerId('id'),
                        position: LatLng(lat, lng),
                        icon: BitmapDescriptor.defaultMarker,
                          ),
                        ]),
                        onMapCreated: (GoogleMapController controller) {
                              setState(() {
                                controller.animateCamera(CameraUpdate.newLatLng(
                                  LatLng(lat, lng),
                                ));
                              });
                            },
                          )),

Google map search
            RaisedButton(
                onPressed: _handlePressButton,
                child: Text("Search places"),
              ),

  Future<void> _handlePressButton() async {
    Prediction p = await PlacesAutocomplete.show(
      context: context,
      apiKey: kGoogleApiKey,
      mode: Mode.overlay,
    );
    displayPrediction(p);
  }

  Future<void> displayPrediction(Prediction p) async {
    if (p != null) {
      PlacesDetailsResponse detail =
          await _places.getDetailsByPlaceId(p.placeId);
      setState(() {
        lat = detail.result.geometry.location.lat;
        lng = detail.result.geometry.location.lng;
      });
    }
  }

After change lat and LNG map is not animated but the marker changed.. how to animate google map view?

A: this is how you would go about it
 final GoogleMapController controller = await mapController;

    mapCcontroller.animateCamera(CameraUpdate.newCameraPosition(
      CameraPosition(
        bearing: 0,
        target: LatLng(lat, lon),
        zoom: 16.0,
      ),
));


text:
Q: PHP Fatal Error not getting displayed on browser screen I am new to PHP and trying to understand how to debug the code. I am using the ini_set and ini_get functions.
Here's my code:
<?php
 error_reporting(E_ALL);

 ini_set('display_errors', 1);
 ini_set('log_errors', 1);
 ini_set('log_errors_max_len', 0); // 0 = unlimited length
 ini_set('error_log', '/var/www/html/debugging/php_errors.log');

 echo $error->abc; // should give error

 // E_ERROR - run out of memory
 ini_set('memory_limit', '1K');
 var_dump((object) range(0, 100000));
 require 'abc.php';

?>

All the errors get logged into the php_errors.log file as well are displayed on the browser. But when I use var_dump((object) range(0, 100000)); to introduce a fatal error to run out of memory, I get a blank screen on the browser, whereas the error gets logged into the php_errors.log.
Do I need to change any other setting to get the error displayed on the browser as well as log into the file. I am just trying to play with PHP here.

A: 1K is too low for PHP to render the error in the browser.
[Updated]
PHP needs to have enough memory available in order to be able to trigger the error handler that displays the error messages in the browser. So in this case, php did not have enough memory when it tried to output the message to the browser and just stopped.
The amount of memory required depends on loaded extensions, server environment, and other php.ini settings.
For example, when an out of memory error is triggered at 1 MB allocated, it requires 1.5 MB in order to display an error message in the browser. See: Tracking Memory Usage in PHP
Demo: http://ideone.com/VmPO0w
<?php
// error.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$x = str_repeat(' ', 1024 * 1024); //store 1 MB to a string
ini_set('memory_limit', '1535K'); //minimum of 1536K (1.5 MB) needed to display error
while (true) {
    echo 'not real: ' . (memory_get_peak_usage(false) / 1024 / 1024) . " MB\n";
    echo 'real: ' . (memory_get_peak_usage(true) / 1024 / 1024) . " MB\n\n";
    $x .= str_repeat(' ', 1024 * 500); //store 500K more to string
}

Command line usage result: $>php error.php
not real: 1.2208786010742 MB
real: 1.5 MB

Fatal error: Allowed memory size of 1571840 bytes exhausted (tried to allocate 512001 bytes) in error.php on line 10

While when loaded in the browser, the result would be a blank page.

Windows Environment php 5.6 x64 NTS + built-in webserver. Use at least 256K.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo $error->abc; // should give error
// E_ERROR - run out of memory
ini_set('memory_limit', '256K'); //tested with 255K - blank page
var_dump((object) range(0, 100000));

( ! ) Fatal error: Allowed memory size of 262144 bytes exhausted
  (tried to allocate 32 bytes) in ...

Linux Environment php 5.6 x64 NTS + php-fpm + Apache FCGI. Use at least 512K.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo $error->abc; // should give error
// E_ERROR - run out of memory
ini_set('memory_limit', '512K'); //test with 511K - blank page
var_dump((object) range(0, 100000));

( ! ) Fatal error: Allowed memory size of 524288 bytes exhausted
  (tried to allocate 32 bytes) in ...


text:
Q: How to solve for a distribution function over which another function is integrated? How to solve for a distribution function $F$ in:
$$T(x) = \int_a^x p(y) dF(y)$$
Let me provide you with the following example.  A company may advertise a price in range between $[a,x]$ for its product. $F(y)$ stands for a probability that the company advertises a price smaller than or equal to $y$ ($y \in [a,x]$), and greater than $a$. $p(y)$ is the proportion of consumers (which can be assumed as a unity mass) to which the advertisement of price $y$ reaches; obviously, $0 \leq p(y) \leq 1.$  Finally, $T(x)$ is the probability that a particular consumer observes an ad offering a price $x$ or lower (and greater than $a$).
Given the above equation, how to solve for $F$ in terms of $T()$ and $p()$ for $y \in [a,x]$?

A: This is a problem of functional optimization. $T$ depends on $F$ and $p$ is given (or at least could be known using polls).
Let us first follow @Ian's comment by assuming that $F$ is absolutely continuous. This means that $\mathrm d F(y)=f(y)\mathrm dy$, where $f$ is the probability density of the price. As $T$ depends not on a single variable, but on all the values of $f$, one uses the notation $T[f]=\int_a^xp(y)f(y)\mathrm dy$. Let us consider $\delta f$ an arbitrary function satisfying $$\int_a^x\delta f(y)\mathrm dy=0\tag 1$$ (to ensure the normalization of $f+\delta f$).
If $f$ is the optimal price probability, the quantity $T[f+\delta f]-T[f]$ must be negative for any function $\delta f$. Now we should notice that $T[f+\delta f]-T[f]=T[\delta f]$. This does not depend on $f$ ! In this case, there is a solution only if $p(y)=\frac1{x-a}$ is the uniform distribution. In any other case, one can find a function $\delta f$ satisfying (1) and $T[\delta f]>0$. (take any function satisfying (1) such that $\operatorname{sign}\left(\delta f(y)\right)=\operatorname{sign}\left(p(y)-\frac1{x-a}\right)$.)
So we have a first solution:
If $p$ is a uniform distribution, any choice of $F$ is optimal.
In a second case, if $p$ is not uniform, we have shown that $F$ cannot be continuous. Let us concentrate on the discontinuities and chose $F$ as steps
$$F(y)=\sum_{i=1}^n a_i\Theta(y-y_i)\tag 2 $$
where $y_i\in[a,x]$, $a_i>0$ and $\sum_{i=1}^Na_i=1$. Therefore
$$T=\sum_{i=1}^Na_ip(y_i).$$
If $p$ reaches its absolute maximum on $[a,x]$ at point $y_{\mathrm m}$, then the maximum of $T$ is reached for $N=1$, $y_1=y_{\mathrm m}$ (and $a_1=1$). If the absolute maximum of $p$ is reached at several values
of $y$, any solution of the form (2) with $y_i$ equal to these values is optimal. This is the optimal solution because if $F$ grows between to discontinuities, this will result in diminishing the coeffients $a_i$.
If $p$ is not uniform, the optimal solution are $F$ of the form
(2) where the discontinuities are located where $p$ reaches its absolute maximum.
In a way, a uniform distribution reaches its absolute maximum everywhere, so the two cases merge.
Note Few words concerning the income function $P=\int yp(y)\mathrm dF(y)$ : the reasoning is the same except that the function $p$ is replaced by $q(y)=yp(y)$. The "reference" function is therefore not the uniform distribution but $p(y)=1/y$. For this function, any choice of $F$ is optimal. Otherwise, apply the same reasoning with the discontinuities and locate the absolute maximum of $q$ on $[a,x]$. Example: if $p(y)=A\exp(-y/y_0)$, the optimal price is $\max\left\{\min\{x,y_0\},a\right\}$.


text:
Q: Joint Entropy of two time series I have two time series of same length like following:
X=[ 1.1833
    1.1467
    1.1767
    1.1833
    1.1000
    1.2367
    1.1633
    1.2100
    1.1200
    1.1800 ]

and
Y=[ 1.2067
    1.1800
    1.1400
    1.1900
    1.1467
    1.1467
    1.2167
    1.1967
    1.1633
    1.1300 ]

I want to calculate Joint Entropy of X and Y. I know the formula for H(x,y), but I am facing problem while calculating Joint probability.


text:
Q: onclick of radio button go to url I want to link  the onclick event of the radio button to the new web page.
The web pages are developed in php and syntax is as follows
echo """<input class="radio" type="radio" name="alg_Type" id="HP" value="HP" onclick="location.href='highP.php'"/>  High precision""";

and I get the following error
Parse error: parse error, expecting ','' or';''
Any help would be appreciated.
Thanks

A: echo '<input class="radio" type="radio" name="alg_Type" id="HP" value="HP" onclick="location.href=\'highP.php\'"/>  High precision';

A: You're grossly misusing quotes. Try:
<?php
  //some code
  ?>
  <input class="radio" type="radio" name="alg_Type" id="HP" value="HP" onclick="location.href='highP.php'"/>
  High precision
  <?
  //more php code

A: Try :
echo '<input class="radio" type="radio" name="alg_Type" id="HP" value="HP"  onclick="location.href=\'highP.php\'"/>  High precision';


text:
Q: How to tokenize a Oracle SQLPlus script into individual statements in JavaScript I would need to process the content of a script that typically would be processed by Oracle SQLPlus within an application.
The scripts contains blocks like:

*

*comments (-- this is a comment)

*SQLPlus commandos (set echo off)

*plain SQL statements (select * from dual;)

*PL/SQL statements like (create function foo returning number as begin return 1; end;/)

and I would need to execute the individual blocks individually.
Is there a reasonably simple way to tokenize the statements in JavaScript or would I need a full blown tokenizer that fully understand the SQLPlus syntax?

A: The simplest method is to assume that the SQL script was written in a reasonably readable manner and that there is either 1 statement-per-line or that statements are split over multiple lines and you will not have the case where there are multiple statements on a single line.
The majority of cases can be handled by:
Read the next line and trim any leading white-space:

*

*If it starts with SET or COLUMN then you have a SQL/Plus directive which will (typically) consist of a single line; that line is your statement.

*If it starts with CREATE FUNCTION, CREATE PROCEDURE, CREATE PACKAGE, DECLARE or BEGIN (and a following white-space character) then you will have a PL/SQL block that will be terminated with a / on a separate line and you can read lines until you have found it and that is your complete statement.

*If it starts with -- then it is a comment and you can skip the rest of the line and prepend it to the next statement (since comments are part of the next statement).

*If it starts with /* then it is an inline comment and you can read until the next */ and then repeat by processing the rest of the line (the comment will be prepended to the next statement).

*Otherwise, read until the next ; that is at the end of a line (or followed by a comment) (or / on a separate line) and that is your complete statement.

Then repeat, reading the next line.
This is not guaranteed to work on 100% of cases (i.e. if you have multi-line string literals which happen to have a ; at then end of a line within the literal). You should review the output to see if there are any additional cases that need to be handled but for relatively simple scripts it should work.
If you have developers that like writing (less readable) scripts with multiple statements on the same line then you may need to implement a parser.


text:
Q: Clojure data structure traversal/searching I'd like to be able to do something like this:
(search data
  list?
  (fn [x] (and (list? x) (= 4 (first x))))
  (fn [x] (and (set? x) (contains x 3))))

And have it recursively search a nested data structure data:

*

*first for the shallowest lists (might be in a set of sets, for example).

*then within those lists for the shallowest lists who's first element is 4.

*then in those lists for the shallowest sets that contain 3.

*finally returning a list of items found in step 3.

Before I reinvent the wheel, is there a standard way of doing this?

A: Clojure has standard ways for traversing trees. You should look into clojure.zip and look into tree-seq as well.
(loop [loc dz]
  (if (end? loc)
    (root loc)
    (recur (next (if (= '* (node loc))
                   (replace loc '/) loc)))))

(loop [loc dz]
  (if (end? loc)
    (root loc)
    (recur (next (if (= '* (node loc))
                   (remove loc) loc)))))

These two examples at the end of clojure.zip seem to make it clear that you don't need to know what the data structure looks like. The use of loop also shows that you could easily accumulate only the values you are interested in as you traverse the data structure.


text:
Q: How to describe commutative rules in prolog? I intend to describe "a rule is commutative" in my database, an immediate idea is that like the code.
certain_rule(X,Y) :- X = struct(_X,Others) , Y = some_process_base_on(_X).
certain_rule(Y,X) :- X = struct(_X,Others) , Y = some_process_base_on(_X).

But if X is unbound, it will make X bind with struct(_X,Others) directly, then some_process_base_on(_X) will be unknown. Now my solution is insert compound(X) before breakdown X.
Usually, compound/1 is not strict enough, something unexpected will be taken in, functor/3 may be a better solution but too many rules will exist since too many functors I need to compare, even if I use member/2 to find functor in list I still construct too many combination.
Is there any better way to describe 'commutative', BTW, is there any better way to screen some specified structures out?

A: First, note that your clauses are equivalent to writing:
certain_rule(struct(X,_), some_process_base_on(X)).
certain_rule(some_process_base_on(X), struct(X,_)).

A possible solution to screen for valid structures is to use a table of valid structures. For example:
valid_structure(-) :-
    !,
    fail.
valid_structure(struct(_,_)).
valid_structure(some_process_base_on(_)).
...

The first clause will screen out variables while preserving first-argument indexing for the predicate. You could then define a gatekeeper predicate:
certain_rule_gatekeeper(X, Y) :-
    once((valid_structure(X); valid_structure(Y))),
    certain_rule(X, Y).

To address commutativity, would a definition such as the following would work in your specific case?
certain_rule_gatekeeper(X, Y) :-
    once((valid_structure(X); valid_structure(Y))),
    once((certain_rule(X, Y); certain_rule(Y, X))).

Sample calls using just one of the clauses above for the certain_rule/2 predicate (thus avoiding duplicated information):
| ?- certain_rule_gatekeeper(X, Y).
no

| ?- certain_rule_gatekeeper(struct(X,_), Y).
Y = some_process_base_on(X)
yes

| ?- certain_rule_gatekeeper(Y, struct(X,_)).
Y = some_process_base_on(X)
yes

| ?- certain_rule_gatekeeper(some_process_base_on(X), Y).
Y = struct(X,_)
yes

| ?- certain_rule_gatekeeper(Y, some_process_base_on(X)).
Y = struct(X,_)
yes


text:
Q: Wpf Charting Toolkit Missing Time series values in Line Graph I am working on Wpf Charting Toolkit. There is a very basic problem which I am facing. I have done binding of my graph with a List which takes objects of KeyValuePair.
    List<KeyValuePair<DateTime,decimal>>

The list which I am providing contains few missing DateTime Values. Is there any possibility that graph can ignore those missing values and not show a long straight line where this gap occurs?


text:
Q: Is it possible bulk insert in HANA? I want to insert into HANA by bulk. Currently I am using Java to insert line by line from the result set. Is there a way to insert multiple rows at a time? Is it possible to do? (I do not want import only bulk insert) I searched all over and could not find any good answer. Any help is appreciated.

A: For JAVA/JDBC code, there exists the so-called batch interface.
Here's an old example that I used for testing:
myDBconn.setAutoCommit(false);

PreparedStatement insStmt = myDBconn
        .prepareStatement("INSERT INTO EFASHION.SHOP_FACTS_INS_DEMO VALUES"
                + " (?, ?, ?, ?, ?, ?, ?, ?  )");

for (int i = 1; i <= LOOPCNT; i++) {
    myfacts.createNewFact();  // create a JAVA object with new data

    // prepare the new data for the batch
    // note that this is a typed assignment.
    insStmt.setInt(1, i);
    insStmt.setInt(2, myfacts.article_id);
    insStmt.setInt(3, myfacts.color_code);
    insStmt.setInt(4, myfacts.week_id);
    insStmt.setInt(5, myfacts.shop_id);
    insStmt.setDouble(6, myfacts.margin);
    insStmt.setDouble(7, myfacts.amount_sold);
    insStmt.setInt(8, myfacts.quantity_sold);

    // add the new data to the batch
    insStmt.addBatch();

    // limit the batch size, to  prevent client side out of memory errors.
    // but DON'T commit yet!
    // Remember the data in the current batch is kept in client
    // memory as long as we don't send it to the HANA server
    if (i % BATCHSIZE == 0) {
        // executeBatch returns the number of affected rows.
        // if we want to use this in the application we just keep adding this up
        affectedRows += insStmt.executeBatch();
    }
}
// the final batch execution for whatever remained in the
// last batch
affectedRows += insStmt.executeBatch();

// finally commit
myDBconn.commit();

All that is documented in the JDBC docu so it shouldn't be a problem to follow this.
Remark: ARRAY data types are not supported (neither for single prepared statements nor for batches) - just in case that is what you wanted to do...


text:
Q: Mysql gone away with peewee as second database in Django I'm using peewee to access a remote MySql database to retrieve data that I need to display in a Django app. It means that peewee isn't really used to access the main db but just to like, define custom models:
Example in databases.py :
from django.conf import settings
from playhouse.pool import PooledMySQLDatabase

database = PooledMySQLDatabase(
    settings.DB_PEEWEE,
    **{
        "use_unicode": True,
        "charset": "utf8",
        "max_connections": 32,
        "stale_timeout": 300,  # 5 minutes.
        "password": settings.DB_PEEWEE_PSWRD,
        "user": settings.DB_PEEWEE_USER,
        "host": settings.DB_PEEWEE_HOST,
        "port": settings.DB_PEEWEE_PORT,
    }
)

in models.py:
from .databases import database

class BaseModel(peewee.Model):
    class Meta:
        database = database

class CountryGroups(BaseModel):
    africa = peewee.CharField(null=True)
    group_code = peewee.AutoField()
    group_name = peewee.CharField()
    latin_eur = peewee.CharField(null=True)
    type = peewee.CharField()

    class Meta:
        table_name = "country_groups"
...
# other main django models

So the model can be easily called from the views.py file as :
CountryGroups_list = (
        CountryGroups.select()
        .where(CountryGroups.group_name << ["ERROR", "INFO"])
        .order_by(CountryGroups.group_name.desc())
        .limit(1000)
    )

I can run the query fine. But I get an error after 24 hours where the connection is broken:
(2006, "MySQL server has gone away (error(32, 'Broken pipe'))")
The suggested method of solving this in Django is trough the usage of a middleware but this assume that in that case peewee related db is the main one, and has resulted in errors like this one:
File "/home/user/Dev/project/project/wsgi.py", line 14, in <module>
    from configurations.wsgi import get_wsgi_application
  File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/configurations/wsgi.py", line 14, in <module>
    application = get_wsgi_application()
  File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
    return WSGIHandler()
  File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 135, in __init__
    self.load_middleware()
  File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/django/core/handlers/base.py", line 37, in load_middleware
    mw_instance = middleware(handler)
TypeError: object() takes no parameters

So my question is, how would I implement the auto connect() and close() to my generic database model so that I don't get the  error?

A: You need to write a new Django-style middleware. i've updated the docs accordingly:
http://docs.peewee-orm.com/en/latest/peewee/database.html#django
def PeeweeConnectionMiddleware(get_response):
    def middleware(request):
        database.connect()
        try:
            response = get_response(request)
        finally:
            if not database.is_closed():
                database.close()
        return response
    return middleware


text:
Q: (javascript) Failed to parse nested JSON data I'm currently learning about JSON and got stuck to get nested data.
I want to get "id" and "city".
Here's my code:
var url = "jsonURL";
$.getJSON (url, function(b) {
    for (var i = 0; i < b.friends.data.length; i++) {
    var data = b.friends.data[i];
       if (data.id == undefined) {
            html+= " - 	";
        }
        else {
            html+= "" + data.id + "	";
        }
        if (data.location.location.city == undefined) {
            html+= " - 	";
        }
        else {
            html+= "" + data.location.location.city + "	";
        }
    }
}

And JSON looks like this.

    {
       "friends": {
          "data": [
             {
                "id": "friend1",
                "location": {
                   "location": {
                      "city": "Tangerang",
                      "country": "Indonesia"
                   },
                   "id": "1"
                }
             },
             {
                "id": "friend2",
                "location": {
                   "location": {
                      "city": "Makassar",
                      "country": "Indonesia"
                   },
                   "id": "2"
                }
             }
          ],
       },
       "id": "myID"
    }

The problem: total data for "id" is about 600.
If i do not try to get "city", the looping seems fine.
And if i do, the looping for "id" only showing 4 data.
The result is

"Uncaught TypeError: Cannot read property 'location' of undefined"

Fixed
I change it into
data.location == undefined || data.location.location == undefined || data.location.location.city == undefined

A:
Uncaught TypeError: Cannot read property 'location' of undefined

Uncaught means the error was not caught in a catch statement, and TypeError is the error's name.
Seems like you are trying to access the property 'location' of the undefined object. Test that data.location are defined before executing the if statements to get the city.
It always work :
try{
    if (data.location.location.city == undefined) {
        html+= " - 	";
    } else {
        html+= "" + data.location.location.city + "	";
    }
}catch(e){
    if(e){
    // If fails, Do something else
    }
}


text:
Q: model binding and sumbit button mvc4 I have multiple forms on a cshtml page. The first of these forms binds correctly, but I have not been able to get the second one to bind. Each time I click the submit button the passed values are all 0 or null (int and stings respectively)
My model contains two objects. AccountInfo and a list of AccountSettings:
public class AccountDetailViewRequest
{
    public Account AccountInfo { get; set; }
    public List<AccountSettings> Settings { get; set; }
}

public class AccountSettings
{
    public int AccountID;
    public string Name;
    public string Value;
    public int ID;
}

My actions. The first action that works correctly, but the second does not.
public ActionResult UpdateAccountDetails(Account model)
{...}

public ActionResult DeleteSetting(AccountSettings model)
{...}

In my cshtml page I have this block which works correctly
@using (Html.BeginForm("UpdateAccountDetails", "Account"))
{
    <input type = "hidden" name = "AccountInfo.AcctID" value = @Model.AccountInfo.AcctID />

            Company @Html.TextBox("AccountInfo.Company")
            <--More text boxes here-->

            <input name="Save" type="submit" value="Save Changes"/>

}

Later in the page I have this block. When I use the associated submit button the function is called, but the parameters are all 0 or null regardless of the content of the text boxes. The boxes populate properly from my DB when I view the source of the code.
@for (int index = 0; index < Model.Settings.Count; index++)
{
    var setting = Model.Settings[index];
    using (Html.BeginForm("DeleteSetting", "Account"))
    {

            @Html.TextBox("Name", @Model.Settings[index].Name)
            @Html.TextBox("Value", setting.Value)
            @Html.Hidden("ID", setting.ID)
            @Html.Hidden("AccountID", Model.AccountInfo.AcctID)
            <input type="submit" value="Delete"/>

    }
}

I've tried a number of different variations on the syntax but cannot seem to get it right.
Suggestions, solutions and resources welcome.
Thank you in advance.

A: Try something like this

        @Html.TextBox("AccountSettings.Name", @Model.Settings[index].Name)
        @Html.TextBox("AccountSettings.Value", setting.Value)
        @Html.Hidden("AccountSettings.ID", setting.ID)
        @Html.Hidden("AccountSettings.AccountID", Model.AccountInfo.AcctID)
        <input type="submit" value="Delete"/>

Your view model is AccountDetailViewRequest of which Name, Value, etc aren't properties.
It'd be tidier if you did something like this:
@foreach (var setting in Model.Settings)
{
    using (Html.BeginForm("DeleteSetting", "Account"))
    {

            @Html.TextBoxFor(m => setting.Name)
            @Html.TextBoxFor(m => setting.Value)
            @Html.HiddenFor(m => setting.ID)
            @Html.HiddenFor(m => setting.AcctID)
            <input type="submit" value="Delete"/>

    }
}

Note that I improvised the above code and you might need to tweak it to work


text:
Q: What is "Accept-EncodXng" in Apache config? This appears in .htaccess in HTML5 boilerplate.
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding

Is "Accept-EncodXng" documented somewhere?

A: Interesting! Apparently, this is because some proxies and security software obfuscate the Accept-Encoding header, which has the negative effect of requesting the server respond without GZIP compression.
Apparently this information comes from the book Even Faster Web Sites: Performance Best Practices for Web Developers, with the relevant information being available in the Going beyond gzipping slides. The following is the table of software which strips or obfuscates the header from the PDF slides.

------------------------------+-------------------------------
Software                      | Accept-Encoding modification
------------------------------+-------------------------------
Ad Muncher                    | Stripped
CA Internet Security Suite    | Accept-EncodXng: gzip, deflate
CEQURUX                       | Stripped
Citrix Application Firewall   | Stripped
ISA 2006                      | Stripped
McAfee Internet Security 6.0  | XXXXXXXXXXXXXXX: +++++++++++++
Norton Internet Security 2005 | ---------------: -------------
Novell iChain 2.3             | Stripped
Novell Client Firewall        | Stripped
WebWasher                     | Stripped
ZoneAlarm Pro 5.5             | XXXXXXXXXXXXXXX: XXXXXXXXXXXXX

Those slides also reference X-cept-Encoding, though I don't see it listed in the table.


text:
Q: Playwright on google colab : Attempt to free invalid pointer 0x29000020c5a0 I was trying to run playwright on google colab but getting an error
Installed playwright and chromium
!pip install playwright
!playwright install

To run run async stuff in a notebook
import nest_asyncio
nest_asyncio.apply()

My Code
import time
import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page(storage_state='auth.json')
        await page.goto('https://www.google.com')
        time.sleep(6)
        html = await page.content()

        time.sleep(5)

        # await browser.close()

asyncio.run(main())

which gives me following error
/usr/lib/python3.7/asyncio/futures.py in result(self)
    179         self.__log_traceback = False
    180         if self._exception is not None:
--> 181             raise self._exception
    182         return self._result
    183

Error: Browser closed.
==================== Browser output: ====================
<launching> /root/.cache/ms-playwright/chromium-1015/chrome-linux/chrome --disable-field-trial-config --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-back-forward-cache --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --no-sandbox --user-data-dir=/tmp/playwright_chromiumdev_profile-IAbW15 --remote-debugging-pipe --no-startup-window
<launched> pid=656
[pid=656][err] src/tcmalloc.cc:283] Attempt to free invalid pointer 0x29000020c5a0
=========================== logs ===========================
<launching> /root/.cache/ms-playwright/chromium-1015/chrome-linux/chrome --disable-field-trial-config --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-back-forward-cache --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --no-sandbox --user-data-dir=/tmp/playwright_chromiumdev_profile-IAbW15 --remote-debugging-pipe --no-startup-window
<launched> pid=656
[pid=656][err] src/tcmalloc.cc:283] Attempt to free invalid pointer 0x29000020c5a0

A: When I try to run the chromium browser that downloaded by playwright using this command
!/root/.cache/ms-playwright/chromium-1033/chrome-linux/chrome

It gives this error
src/tcmalloc.cc:283] Attempt to free invalid pointer 0x18400020c5a0

It means the problem is somehow related to the browser downloaded by playwright.
We can use a different browser.
First, install chromium.
!apt install chromium-chromedriver

Set executable_path and user_data_dir with launch_persistent_context in your code.
import nest_asyncio
nest_asyncio.apply()

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch_persistent_context(
            executable_path="/usr/bin/chromium-browser",
            user_data_dir="/content/random-user"
        )
        page = await browser.new_page()
        await page.goto("https://google.com")
        title = await page.title()
        print(f"Title: {title}")
        await browser.close()

asyncio.run(main())

I know this is not the right solution but it works.
Update
Since google colab updated to ubuntu 20.04 installing chromium-browser requires snap and I couldn't install chromium with snap.
But in this github comment someone had already found the real problem(it is about root privilege).
If we follow the same steps and for testing save the code below into a file named test_playwright.py on google colab
import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page()
        await page.goto("https://google.com")
        title = await page.title()
        print(f"Title: {title}")
        await browser.close()

asyncio.run(main())

Run it with sudo:
!sudo python test_playwright.py

It works.


text:
Q: how to remove OnSeekBarChangeListener once set in Android? I've searched around and tried some of the suggestions but still no success.
I have a listview that contain seekbars that are used to set parameters in the code. I would like to trigger the seekbar listener based on a toggle button so that the user does not accidentally move the seekbars while scrolling the list.
my problem is that once the toggle is turned off, the seekbar listener is still active. I've tried passing null to the setOnSeekBarChangeListener, but it does not work.
thanks for your help. I'm a newbie to Android and handling the user intput chain of events is still confusing to me. Thanks in advance for your help.

A: Try this..
mySeekBar.setEnabled(false);

EDIT:
Try setting the focus to false like this..
  mySeekBar.setFocusable(false);

A: This should work.
myView.setOnSeekBarChangeListener(null);


text:
Q: What to use instead of 'Table' input in QGIS 3 modeller In QGIS 2 graphical modeler I had an input parameter 'Table' for spreadsheets, csv etc. with no geometry. By now, I'm re-creating all my existing QGIS 2 models from scratch (cp. Using QGIS 2.x processing model in QGIS 3.0?) and miss this input parameter 'Table' in QGIS 3.
What should I use instead?

A: Use Vector Layer with geometry type "Geometry not required"


text:
Q: QTcpSocket does not emit a signal I wrote a small server for tcp in qt, and moved to a second thread (easier to handle for me). The code for the server is:
#include "server.h"

Server::Server(QString ipAddr, quint32 port)
{
    Server::ipAddr = ipAddr;
    Server::port = port;
    firstTime = true;
    sessionOpened();
    qDebug() << "New server created (from Server)!";

    //connect(Server::tcpServer, SIGNAL(newConnection()), this, SLOT(createConnection()));
    qDebug() << "Connections created!";

}

void Server::showSignals()
{
    exit(0);
    qCritical() << m_pSignalSpy->wait(10000);
//    for(int index = 0; index<m_pSignalSpy->size(); index++)
//    {
//        QList<QVariant> listItem = m_pSignalSpy->value(index);

//        qDebug() << "Signal Arguments: ";
//        for(int index2 = 0;index2 < listItem.size();index2++)
//        {
//            qDebug() << listItem[index2].toString().toStdString()<<" ";
//        }
//    }
}

void Server::sessionOpened()
{
    Server::tcpServer = new QTcpServer(this);
    connect(tcpServer, &QTcpServer::newConnection, this, &Server:: gotAConnection);
    if(!Server::tcpServer->listen(QHostAddress::Any, (quint16)Server::port))
    {
        //QMessageBox::information(this, tr("Server"), tr("Unable to start the server: %1.").arg(Server::tcpServer->errorString()));
        Server::tcpServer->close();
        exit(0);
        return;
    }

    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
                ipAddressesList.at(i).toIPv4Address()) {
            Server::ipAddr = ipAddressesList.at(i).toString();
            break;
        }
    }
    // if we did not find one, use IPv4 localhost
    if (Server::ipAddr.isEmpty())
        Server::ipAddr = QHostAddress(QHostAddress::LocalHost).toString();

    qDebug() << Server::ipAddr;
    qDebug() << Server::tcpServer->hasPendingConnections();
//    connect(Server::tcpServer, SIGNAL(newConnection()), this, SLOT(gotAConnection()));
//    Server::m_pSignalSpy = new QSignalSpy(Server::tcpServer, SIGNAL(newConnection()));
//    connect(Server::tcpServer, SIGNAL(newConnection()), this, SLOT(showSignals()));
}

void Server::getInfo()
{
    sendData("Hello");
}

void Server::destroyConnection()
{
    Server::clientConnection->disconnectFromHost();
}

void Server::gotAConnection()
{
    qDebug() << "Got new Connection!";
    exit(0);
}

void Server::createConnection()
{
    qDebug() << "Got new connection, more info later!";
    Server::clientConnection = tcpServer->nextPendingConnection();
    qDebug() << "Got new connection from " << Server::clientConnection->peerAddress().toString();
    emit Server::gotNewConnection(Server::clientConnection->peerAddress().toString());
}

void Server::sendData(QVariant data)
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << (quint16)0;
    out << data;// << '\n' << data.type();
    qCritical() << "Sending Data!";
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));
    connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));
    clientConnection->write(block);
}

void Server::closeServer()
{
    destroyConnection();
    return;
}

Server.h:
#ifndef SERVER_H
#define SERVER_H
#include <QTcpServer>
//#include <QtTest/QTest>
#include <QSignalSpy>
#include <QTcpSocket>
#include <QDebug>
//#include <QMessageBox>
#include <QNetworkInterface>
#include <typeinfo>
//#include <QSignalSpy>

class Server : public QObject
{
    Q_OBJECT
public slots:
    void sessionOpened();

    void getInfo();
    void closeServer();
    void createConnection();
    void gotAConnection(void);
    void destroyConnection();
    void sendData(QVariant data);
    void showSignals(void);
signals:
    void gotNewConnection(QString);
private:
    QTcpServer *tcpServer;
    QString ipAddr;
    quint32 port;
    QTcpSocket *clientConnection;
    quint32 BlockSize;
    bool firstTime;
    QSignalSpy * m_pSignalSpy;
//    template <typename t>
//    void getD
public:
    Server(QString ipAddr, quint32 port);
};

#endif // SERVER_H

I can run the server, and I connect to it (for example via Telnet), but tcpServer does not emit a signal once something is connected to it. Why? Did I do something wrong?
EDIT: Updated code added

A: connect(Server::tcpServer, SIGNAL(newConnection()), this, SLOT(gotAConnection()));

I believe this is the problem and the connection here is failing.
In order to connect, the first parameter should be the address of an instance of an object derived from QObject. The member tcpServer has not been instantiated, you should be connecting to the instance and calling it after creation of the QTcpServer object.
Remove the connect in the constructor and add it to the SessionOpened function, after the creation of the QTcpServer instance.
If you use C++11, you can also use the new connection syntax, which will warn you at compile time if there is a problem.
Server::tcpServer = new QTcpServer(this);
connect(tcpServer, &QTcpServer::newConnection, this, &Server:: gotAConnection);


text:
Q: Show that $A^{\dagger} A$ is strictly positive? Show that $A^{\dagger} A$ is positive definite if $\det(A)$ is not equal to zero. I do not know how to make use of $\det(A)$ is not equal to zero.

A: Hint: If $\det(A)$ is non-zero, then $A$ is invertible.  In particular: in such a situation, we have
$$
\|Ax\| = 0 \iff x = 0
$$

A: $A^\dagger A$ is Hermitian, thus can be diagonalized with real eigenvalues. The fact that $\det(A)\neq 0$ means that none of the eigenvalues are zero. This should be sufficient to prove that $A^\dagger A$ is positive definite.