text:
Q: How to do routing in Codeigniter I have a problem with routing in CI.
I have a controller with parameters that supports categories and subcategories
category$1/subcategory$2

I came up with such entries, but they do not quite work.
$route['(:any)'] = 'ads/cat/$1';
$route['(:any)/(:any)'] = 'ads/cat/$1/$2';
$route['(:any)/(:any)/(:num)'] = 'ads/cat/$1/$2/$3';

Everything works until I add pagination - $3.
I mean pagination works only for category/subcategory/10... but when I turn it on category/10 it treats the 10 as the second parameter, not pagination ...
How to make it work?
This is the code for my controller:
public function cat( $cat_alias, $subcat_alias = null)
    {
        $this->load->library('pagination');
        $limit = 10 ;

        if (!empty($subcat_alias)) {
        $start = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        }
        else
        {
        $start = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
        }

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

        }

        $where = array( 'catalogue' => $cat_alias );
        $ad_category = $this->Site_model->get_single( 'categories' , $where );
        $children = $this->Site_model->get_childrens($ad_category->id);

        foreach ($children as $child)
        {
            $childs[] = $child->id;
        }

        if ( !empty( $ad_category ) )
        {

            if (!empty($subcat_alias))
                {

                $where = array( 'catalogue' => $subcat_alias );
                $ad_category2 = $this->Site_model->get_single( 'categories' , $where );

                $data['meta']['title'] = $ad_category2->title;
                $data['meta']['desc'] = $ad_category2->description;

                $where = array('category_id' => $ad_category2->id);

                }

                else
                {

                $where = array( 'category_id' => $childs );
                $data['meta']['title'] = $ad_category->title;
                $data['meta']['desc'] = $ad_category->description;
                }

            $ads = $this->Site_model->get( 'ads' , $where, $limit, $start );
            $data['counter'] = $this->Site_model->get_count( 'ads' , $where);

            if ( !empty( $ads ) )
            {

                foreach ( $ads as $ad )
                {
                    $ad_ids[] = $ad->id;
                }
                $where = array( 'id' => $ad_ids );

            if (!empty($city))
                {
                $wher = array( 'slug' => $city );
                $ad_city = $this->Site_model->get_single( 'cities' , $wher );

                $where_filter['city_id'] = $ad_city->id;
                $data['ads'] = $this->Site_model->filter('ads', $where, $where_filter, $limit, $start);

                }
                else
                {

                $data['ads'] = $this->Site_model->get( 'ads' , $where, $limit, $start );

                }

if (!empty($subcat_alias)) {
        $config['base_url'] = site_url(''.$cat_alias.'/'.$subcat_alias.'');
        $config['uri_segment'] = 3;
    }
    else
    {
        $config['base_url'] = site_url(''.$cat_alias.'/');
        $config['uri_segment'] = 2;
    }
        $config['total_rows'] = $data['counter'];
        $config['use_page_numbers'] = TRUE;
        $config['per_page'] = 10;
        $config['full_tag_open'] = '

';
        $config['full_tag_close'] = '

';
        $config['first_link'] = false;
        $config['last_link'] = false;
        $config['first_tag_open'] = '
';
        $config['first_tag_close'] = '
';
        $config['prev_link'] = '←';
        $config['prev_tag_open'] = '
';
        $config['prev_tag_close'] = '
';
        $config['next_link'] = '→';
        $config['next_tag_open'] = '
';
        $config['next_tag_close'] = '
';
        $config['last_tag_open'] = '
';
        $config['last_tag_close'] = '
';
        $config['cur_tag_open'] =  '
';
        $config['cur_tag_close'] = '
';
        $config['num_tag_open'] = '
';
        $config['num_tag_close'] = '
';

        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();

        $data['categories'] = $this->Site_model->get_categories();
        $data['current'] = $this->uri->segment(1);
        // $data['meta']['title'] = $ad_category->title;
        // $data['meta']['desc'] = $ad_category->description;
        $this->load->view( 'cat' , $data );

            }
            else
            {
                $this->session->set_flashdata( 'alert' , 'Aktualnie brak ogłoszeń w tej kategorii.' );
                 redirect( '/' );
            }

        }
        else
        {
            $this->session->set_flashdata( 'alert' , 'Niepoprawna nazwa kategorii.' );
             redirect( '/' );
        }

    }

A: I'm guessing your controller looks something like this:
function cat($category, $subcategory, $pagination){...}

You need to change it a bit so it can detect if the second parameter is the pagination like so:
function cat($category, $subcategory, $pagination=null)
{
    if($pagination == null && is_numeric($subcategory)) $pagination = $subcategory;
    //your code
}

This will work if the $category & $subcategory are strings but if they are numbers (ids) than you need a bit more check


text:
Q: Best practice to map points with level I have a "points" field in the users table which increments points for the user after certain actions. I want to associate this with a "level" field (e.g. Level 1 , 2 ,3 ... etc).
I thought of creating a new table with numbers from 1 to 5000 for example, and map each range of numbers to their corresponding level. But I might need more points in the furure (maybe 100,000 points) which will make the table big. I feel there is a better solution.

A: I'd go with a simple little helper function/method:
<?php

function getLevel($numberOfPoints) {
    if ( $numberOfPoints >= 10001 ) {
        return 'Level 3';
    } elseif ( $numberOfPoints >= 5001 ) {
        return 'Level 2';
    } elseif ( $numberOfPoints >= 1 ) {
        return 'Level 1';
    }
}

echo getLevel(52); // Level 1
echo getLevel(5000); // Level 1
echo getLevel(1233010); // Level 3

Extend the function with new levels as required

redpajama_set_name: RedPajamaStackExchange


text: Q: I want the code of previous version of my Django app. How can I get it? I tried git reset --hard but it's not working. It's showing email not found s I deleted the requirements.txt file and again created a new requirements.txt file using pip freeze > requirements.txt And after deploying, it is showing an application error. So I rolled back to the previous version. But I am not able to get the code of that previous version. I tried with the "git reset --hard eeb02c91" command. But it's not working. It's showing "HEAD is now at eeb02c9 Email not registered error added". Someone, please help me to get the code of the previous version.


text:
Q: Issues using custom testInstrumentationRunner I've not found any post on Stack Overflow that helped, so I'm posting my own question.
I have a custom testInstrumentationRunner that when set doesn't run any tests.
The logs says:
App restart successful without requiring a re-install.
Running tests
adb shell am instrument -w -m  --no-window-animation  -e debug false -e class 'com.my.app.MyFragmentTest' com.my.app.debug.test/com.my.app.CustomTestRunner
Connected to process on device

When running the normal androidx.test.runner.AndroidJUnitRunner the tests run, but fail, because I need the custom runner.
The runner is set up like the androidx one, in:
defaultConfig {
// testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner
   testInstrumentationRunner "com.my.app.CustomTestRunner"
}

It's also located in the com.my.app package in androidTest-folder
The code for the runner is:
package com.my.app

import ...

class CustomTestRunner: AndroidJUnitRunner() {
    override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
        DexOpener.install(this)
        Timber.i("This should print hopefully")
        return super.newApplication(cl, ApplicationTest::class.java.canonicalName, context)
    }
}

Not sure if it matters, but here's the code for the application class, which extends the application class used for the app itself:
package com.my.app

class ApplicationTest: MyApplication() {
    override fun onCreate() {
        super.onCreate()
        appContext = applicationContext
        initializeDependencyInjection()
    }

    override fun initializeDependencyInjection() {}
}

I have a test-case I'm trying to run, which contains 7 tests. The androidx runner fails on 7/7 tests. But when I run with the custom runner, I get duration 0ms and 0/0 tests.
So it seems like Android isn't detecting this runner. I also get the same results using a random name in the testInstrumentationRunner, like testInstrumentationRunner "not.a.TestRunner"

A: I'm sure you've already solved the issue or switched jobs to growing potatoes or something more productive, but I just spent my whole morning debugging this same exact scenario and managed to find a solution:
The custom instrumentation runner you have is not ignored, but there is something broken in your custom Test Application initialization. Probably in your replacement dependency injections, like it was in my case. When you run the tests using the custom runner, the custom Test Application silently crashes immediately, but this is not indicated in the test results or in any other easily visible place. The crash stack trace is, however, accessible in logcat. So solve that first, and then try using your custom test runner again.

A: Do not mix between Instrumentation Tests and Unit Tests:
Unit Tests
Unit tests runs in local JVM and minimizes the execution time.
Unit Tests cannot test UI of the app without mocking activity objects.
Unit test are used for white box testing for testing code.
Most of the time Unit Tests are written by Developers.
You don't need a device connected for execution of Unit Tests.
Instrumentation Tests
Instrumentation tests are used for black box testing.
It is used to test GUI of the application along with its functionality in real environment.
For execution of Instrumentation tests you need a device /emulator on which the application is first installed and then tests are executed.
Automation Testers are involved in writing instrumentation framework.

A: When testing a library module, you can link the test application in src/androidTest/AndroidManifest.xml:
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:name="com.my.app.ApplicationTest"/>
</manifest>


text:
Q: How to apply parallax effect to UITableView header that contains horizontal UICollectionView? I created screen that contains UITableView. The tableView header contains horizontal UICollectionView and that collectionView contains cells with imageView and some other view.
The question is how to apply parallax effect to all view in the tableView header?

A: Implement the UIScrollViewDelegate method scrollViewDidScroll. There you can examine the contentOffset of the table view and modify the collection view height (via the constant of a NSLayoutConstraint) and its contentOffset.


text:
Q: Average class not compliling I tried looking up my error problems and I cannot figure out where I went wrong with my code.
Objective:
This class will allow a user to enter 5 scores into an array. It will then rearrange the data in descending order and calculate the mean for the data set.
Attributes:
• data[]—the array which will contain the scores
• mean—the arithmetic average of the scores
Methods:
• Average—the constructor. It will allocate memory for the array. Use a for loop to repeatedly display a prompt for the user which should indicate that user should enter score number 1, score number 2, etc. Note: The computer starts counting with 0, but people start counting with 1, and your prompt should account for this. For example, when the user enters score number 1, it will be stored in indexed variable 0. The constructor will then call the selectionSort and the calculateMean methods.
• calculateMean—this is a method that uses a for loop to access each score in the array and add it to a running total. The total divided by the number of scores (use the length of the array), and the result is stored into mean.
• toString—returns a String containing data in descending order and the mean.
• selectionSort—his method uses the selection sort algorithm to rearrange the data set from highest to lowest.
import java.util.Scanner;

public class Average
{
  private int [] data;
  private double mean;

  public Average()
  {
    data = new int[5];
    Scanner keyboard = new Scanner (System.in);

    for (int index = 0; index < data.length; index++)
    {
      System.out.println("Enter score #" + (index + 1) +  ": ");
      data[index] = keyboard.nextInt;
    }
    keyboard.close();
    return data;
  }

  /**
   * calculateMean Method
   */

  public static float calculateMean(int[] data)
  {
    int total = 0;
    for (int index = 0; index < data.length; index++)
    {
      total += data[index];
    }
    float mean = ((float)total) / data.length;
    return mean;
  }

  /**
   * selectionSort Method
   */

  public static void selectionSort(int[] data)
  {
    int startScan, index, minIndex, minValue;

    for (startScan = 0; startScan < (data.length-1); startScan++)
    {
      minIndex = startScan;
      minValue = data[startScan];
      for(index = startScan + 1; index < array.length; index++)
      {
        if (data[index] < minValue)
        {
          minValue = data[index];
          minIndex = index;
        }
      }
      data[minIndex] = data [startScan];
      data [startScan] = minValue;
    }
  }

  /**
   * toString method
   */

  public static void main(String[] args)
  {
    int[] data = new int[5];
    Scanner keyboard = new Scanner(System.in);

    for (int index = 0; index < data.length; index++)
    {
      System.out.println("Enter score #" + (index + 1) + ": ");
      data[index] = keyboard.nextInt();
    }
    selectionSort(data);
    float average = calculateMean(data);
    System.out.println(Arrays.toString(data));
    System.out.println("Average is " + average);
  }
}

Sorry everyone, I should've posted what and where my errors were. This is what I get when I compile:
Compilation completed.  The following files were not compiled:
4 errors found:
File: C:\Users\bryan\Downloads\Average.java  [line: 16]
Error: cannot find symbol
  symbol:   variable nextInt
  location: variable keyboard of type java.util.Scanner
File: C:\Users\bryan\Downloads\Average.java  [line: 19]
Error: incompatible types: unexpected return value
File: C:\Users\bryan\Downloads\Average.java  [line: 50]
Error: cannot find symbol
  symbol:   variable array
  location: class Average
File: C:\Users\bryan\Downloads\Average.java  [line: 78]
Error: cannot find symbol
  symbol:   variable Arrays
  location: class Average

A: Your methods are static and have unfortunate extra semi-colons, and mix method parameters and class variables indiscriminately. You can't return a value from a void method. When I fix the syntax errors (and move the array into your main() method) it seems to work. So, I think you wanted something like
class Average {
    /**
     * calculateMean Method
     */
    public static float calculateMean(int[] data) {
        int total = 0;
        for (int index = 0; index < data.length; index++) {
            total += data[index];
        }
        float mean = ((float) total) / data.length;
        return mean;
    }

    /**
     * selectionSort Method
     */

    public static void selectionSort(int[] data) {
        int startScan, index, minIndex, minValue;

        for (startScan = 0; startScan < (data.length - 1); startScan++) {
            minIndex = startScan;
            minValue = data[startScan];
            for (index = startScan + 1; index < data.length; index++) {
                if (data[index] < minValue) {
                    minValue = data[index];
                    minIndex = index;
                }
            }
            data[minIndex] = data[startScan];
            data[startScan] = minValue;
        }
    }
    public static void main(String[] args) {
        int[] data = new int[5];
        Scanner keyboard = new Scanner(System.in);

        for (int index = 0; index < data.length; index++) {
            System.out.println("Enter score #" + (index + 1) + ": ");
            data[index] = keyboard.nextInt();
        }
        selectionSort(data);
        float average = calculateMean(data);
        System.out.println(Arrays.toString(data));
        System.out.println("Average is " + average);
    }
}


text:
Q: start thinking sphinx on rails server startup I have a chain of nginx + passenger for my rails app.
Now after each server restart i need to write in terminal in project folder
rake ts:start

but how can i automatize it?
So that after each server restart thinking sphinx is automatically started without my command in terminal?
I use rails 3.2.8   and ubuntu 12.04.
I can not imagine what can i try ever, please help me.
How can i do this, give some advices?

A: What I did to solve the same problem:
In config/application.rb, add:
module Rails
  def self.rake?
    !!@rake
  end

  def self.rake=(value)
    @rake = !!value
  end
end

In Rakefile, add this line:
Rails.rake = true

Finally, in config/initializers/start_thinking_sphinx.rb put:
unless Rails.rake?
  begin
    # Prope ts connection
    ThinkingSphinx.search "test", :populate => true
  rescue Mysql2::Error => err
    puts ">>> ThinkingSphinx is unavailable. Trying to start .."
    MyApp::Application.load_tasks
    Rake::Task['ts:start'].invoke
  end
end

(Replace MyApp above with your app's name)
Seems to work so far, but if I encounter any issues I'll post back here.
Obviously, the above doesn't take care of monitoring that the server stays up. You might want to do that separately. Or an alternative could be to manage the service with Upstart.

A: If you are using the excellent whenever gem to manage your crontab, you can just put
every :reboot do
  rake "ts:start"
end

in your schedule.rb and it seems to work great. I just tested on an EC2 instance running Ubuntu 14.04.

A: There's two options I can think of.

*

*You could look at how Ubuntu manages start-up scripts and add one for this (perhaps in /etc/init?).

*You could set up monit or another monitoring tool and have it keep Sphinx running. Monit should boot automatically when your server restarts, and so it should ensure Sphinx (and anything else it's tracking) is running.

The catch with Monit and other such tools is that when you deliberately stop Sphinx (say, to update configuration structure and corresponding index changes), it might start it up again before it's appropriate. So I think you should start with the first of these two options - I just don't know a great deal about the finer points of that approach.

A: I followed @pat's suggestion and wrote a script to start ThinkingSphinx whenever the server boots up. You can see it as a gist -
https://gist.github.com/declan/4b7cc4fb4926df16f54c
We're using Capistrano for deployment to Ubuntu 14.04, and you may need to modify the path and user name to match your server setup. Otherwise, all you need to do is

*

*Put this script into /etc/init.d/thinking_sphinx

*Confirm that the script works: calling /etc/init.d/thinking_sphinx start on the command line should start ThinkingSphinx for your app, and /etc/init.d/thinking_sphinx stop should stop it

*Tell Ubuntu to run this script automatically on startup: update-rc.d thinking_sphinx defaults
There's a good post on debian-administration.org called making scripts run at boot time that has more details.


text:
Q: How do I disable back navigation and remove the back arrow on a Fragment, using Android Jetpack's Navigation component?
I am using Google's recommended single activity pattern with Android
  Jetpack's Navigation component.

Fragment 1 is an authentication screen. After the user is authenticated and navigates to Fragment 2, I would like to make pressing of the Android back button close the app, and remove the back arrow in the app bar.
I have found methods, like onBackPressedDispatcher, to add / remove functionality from the back press, but nothing that also removes the back arrow.
I have also tried app:popUpTo="@+id/firstFragment" when navigating from Fragment 1 to Fragment 2, but that doesn't work either.
This should be possible to specify with a single line of code. Still trying to find. Any tips?

A: You need to remove fragment1 from back-stack when navigation to fragment2
fragment1
<fragment
android:id="@+id/fragment1"
android:name="packagenameforFragment1"
android:label="fragment1"
tools:layout="@layout/fragment_1" >
<action
    android:id="@+id/action_Fragment1_to_Fragment2"
    app:destination="@id/Fragment2_id"
    app:launchSingleTop="true"
    app:popUpTo="@+id/your_MainGraph_id"
    app:popUpToInclusive="true" />

then when you navigate from fragment1 to fragment2 call this
findNavController(fragment).navigate(R.id.action_Fragment1_to_Fragment2)

to remove the back button from Fragment2 you can use this
in Activity onCreate()
val appBarConfiguration = AppBarConfiguration
        .Builder(R.id.your_fragment2_id,R.id.any_other_ids_you_want)
        .build()

then setup your toolbar like this
setupActionBarWithNavController(this, yourNavController, appBarConfiguration)


text:
Q: Is Connectify safe? I am using Connectify. However, I am not sure whether the hotspot is safe to connect or not. Will Connectify information (such as password, message etc.) from whatever devices connected to the hotspot?

A: It's quite hard to say. It's third party software that controls routing your web traffic. It has a good reputation and has been around since 2009. I doubt it's malicious, and I believe from this page it actually just gives a graphics interface/expansion to the Wireless Hosted Network feature in Windows:

What security protocols does Hotspot support?
Hotspot uses the Windows Hosted Network feature to create its wireless
  networks. Because of this, Hotspot only supports WPA2 encryption. This
  means you need to have a password for your hotspot and your passwords
  must be at least 8 characters long.

As such, if you're worried, you could cut out this software and host a network without using this software. It does use WPA2 encryption, so you are protected against MITM attacks.
Realistically I'd say that it's not a security risk at the moment, but it IS a third party software, and it's impossible to know what data it harvests and uses. Even if I could say with absolute certainly that today, it is perfectly safe, nobody knows what it may do in the future.
If you're worried and using very important information, don't use it.


text:
Q: SQL Server's ISNUMERIC function, with just a minus-sign I'm not sure if this is a question or a warning to other SQL Server users.
We use SQL Server's ISNUMERIC function, to determine if a string is a number or not.  But today, we had an issue where the user had passed just a minus sign as their string.
SQL Server's ISNUMERIC returns 1 for this string, suggesting that it is a number.
It can CAST this string into an int (it casts to a value of 0), but fails when casting it into a numeric.
DECLARE @str NVARCHAR(200)

SET @str = '-'

--  This returns 1  (i.e. this string IS a number)
SELECT ISNUMERIC(@str)

--  This works (and returns 0)
SELECT CAST(@str as int)

--  This throws an error of "Arithmetic overflow error converting nvarchar to data type numeric."
SELECT CAST(@str as numeric(12, 0))

--  This throws an error of "Arithmetic overflow error converting nvarchar to data type numeric."
SELECT CAST(@str as numeric(12, 7))

Are there any other odd cases where this is likely to happen ?

A: You can make a simple check:
;WITH cte AS (
SELECT 1 as num
UNION ALL
SELECT num+1
FROM cte
WHERE num< 256
)

SELECT  num,
        CHAR(num),
        ISNUMERIC(CHAR(num))
FROM cte
WHERE ISNUMERIC(CHAR(num)) = 1
OPTION (MAXRECURSION 1000)

This will show that not only numbers are considered valid numeric type:
$
+
,
-
.
\
€
¤

One of the workarounds is to use NOT LIKE '%[^0-9]%'
F.e. if I add this nd CHAR(num) NOT LIKE '%[^0-9]%' to WHERE statement of below query it will return numbers from 0 to 9
Or use TRY_PARSE(.. as int)
Some links:

*

*https://msdn.microsoft.com/en-us/library/hh213126.aspx

*http://www.sqlservercentral.com/articles/ISNUMERIC()/71512/

A: here's a possible replacement user function - only accepts integers - it cannot guarantee conversion due to maximum integer size limits (which of course vary for BIGINT) - it does accept -1 but rejects -.
    -- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
CREATE FUNCTION ISINTEGER
(
    -- Add the parameters for the function here
    @SINT nvarchar(20)
)
RETURNS int
AS
BEGIN

    IF LEN(@SINT) = 0
        RETURN 0;

    IF LEFT(@SINT, 1) IN('+', '-') AND LEN(@SINT) > 1
        RETURN CASE WHEN SUBSTRING(@SINT, 2, 1) IN ('+', '-') THEN
                                        0
                                    ELSE
                                        DBO.ISINTEGER(RIGHT(@SINT, LEN(@SINT) - 1))
                                    END;

    RETURN CASE WHEN @SINT NOT LIKE '%[^0-9]%' THEN 1 ELSE 0 END;

END
GO


text:
Q: Web Addin deployment: Sideload vs Admin center deployment We are working on excel web add-in - for the moment it is a Ribbon element with a task-pane shown when a button on the Ribbon is pressed.
Technical details: we implemented shared JavaScript runtime
Use Case:
So we have an Excel web Add-in which is deployed through MS Admin center (we upload the manifest directly through admin center and make it available for our MS Teams users). The Add-in is correctly loaded for users when excel file is opened in the browser (sic! MS Teams has got a problem here - if excel file is opened in MS Teams the Add-in is not loaded but ok - we live with it for the moment)
At the same time the same Excel web Add-in is deployed by our developers using private deployment (sideload). The Add-in is correctly loaded when excel file is opened in the browser.
Problem:
There is a serious problem - with the first solution one important feature is not available - the automatic show of the task pane after F5 (refresh) is pressed in the browser.
With the second method of deployment the task pane is shown correctly after refresh (F5 in the browser).
Any ideas why this might happen?

A: After exploring https://github.com/OfficeDev/Office-OOXML-EmbedAddin we found a problem with our way of filling the excel file. After correction it started to work fine.
For our case (Centralized Deployment without App Store) we put "EXCatalog" both for store and storeType attributes.


text:
Q: Process: com.example.whatsappclone java.lang.IllegalArgumentException i am getting this error
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter it
i don't know which variable is null i have used everything
need help , i am a beginner in android development , pls don't judge me
i know it's a simple mistake but unable to find it
Following is the entire code.
enter image description here
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.whatsappclone.Adapters.ChatAdapter
import com.example.whatsappclone.Models.MessageModel
import com.example.whatsappclone.databinding.ActivityChatDetailBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import com.squareup.picasso.Picasso
import java.util.*
import kotlin.collections.ArrayList

class ChatDetailActivity : AppCompatActivity() {

    private lateinit var binding: ActivityChatDetailBinding//view binding
    private lateinit var mDbRef: DatabaseReference
    private lateinit var auth: FirebaseAuth
    private lateinit var messageList: ArrayList<MessageModel>
    private lateinit var chatAdapter: ChatAdapter
    private var senderRoom: String? = null
    private var receiverRoom: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        //view binding
        super.onCreate(savedInstanceState)
        binding = ActivityChatDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //removing action bar
        supportActionBar?.hide()

        //getting instance of auth
        auth = FirebaseAuth.getInstance()

        //getting database reference
        mDbRef = FirebaseDatabase.getInstance().reference

        messageList = ArrayList()

        val senderId = auth.currentUser?.uid//sender Id
        val receiverId = intent.getStringExtra("userId")//receiver Id

        senderRoom = senderId + receiverId
        receiverRoom = receiverId + senderId

        //getting intent extra
        val userName = intent.getStringExtra("userName")
        val profilePic = intent.getStringExtra("profilePic")

        //putting intent extra values in views
        binding.username.text = userName
        if (!profilePic.equals("")) {
            Picasso.get().load(profilePic).placeholder(R.drawable.defaultprofile)
                .into(binding.IVProfileImage)
        }

        //on click listener on back button
        binding.btnBack.setOnClickListener {
            val intent = Intent(this@ChatDetailActivity, MainActivity::class.java)
            startActivity(intent)
            this.finish()
        }

        //chat recycler view adapter
        chatAdapter = ChatAdapter(messageList, this)
        binding.chatRecyclerView.adapter = chatAdapter
        binding.chatRecyclerView.layoutManager = LinearLayoutManager(this)

        mDbRef.child("chats")
            .child(senderRoom!!).addValueEventListener(object : ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot) {
                    messageList.clear()
                    for (postSnapshot in snapshot.children) {
                        val model = postSnapshot.getValue(MessageModel::class.java)
                        messageList.add(model!!)
                    }
                    chatAdapter.notifyDataSetChanged()
                }

                override fun onCancelled(error: DatabaseError) {

                }

            })

        //on click on send button
        binding.send.setOnClickListener {
//            Toast.makeText(this, "sid:- " + senderId.toString(), Toast.LENGTH_SHORT).show()
//            Toast.makeText(this, "rid:- " + receiverId.toString(), Toast.LENGTH_SHORT).show()
            val message = binding.etMessage.text.toString()
            val model = MessageModel(senderId!!, message)
//            Toast.makeText(this, "mess- ${messageList.size}", Toast.LENGTH_SHORT).show()
//            Toast.makeText(this, "id- ${senderId}", Toast.LENGTH_SHORT).show()
            model.timeStamp = Date().time
            binding.etMessage.setText("")

            mDbRef.child("chats").child(senderRoom!!).push()
                .setValue(model).addOnSuccessListener {
                    mDbRef.child("chats").child(receiverRoom!!).push()
                        .setValue(model)
                }
        }

    }
}


text:
Q: Invoking a python script from a makefile in another directory I have a makefile that invokes a python script that lives in the same directory as the makefile. It works just fine.
In makefile #1:
auto:
   ./myscript.py

Now, I have another makefile, in another directory, and wish to call the first makefile from it.
In makefile #2:
target:
    cd $(DIR); $(MAKE) auto;

The problem is, when the script runs, it runs as though it's in the same dir as makefile #2. On stdout, I see "make[3]: Leaving directory" and the path to #1, just after the make is executed and before the script is run.
On a suggestion I tried modifying makefile #2 to:
target:
    ( cd $DIR; $MAKE auto; )

but that's interpreted as "cd IR; AKE auto". When I replace the parentheses around DIR and MAKE, I get the same behavior as before.
I've tried modifying the python script by having it assume it's in dir #2 and giving it a path to #1, but the behavior doesn't change.
What's going on, and what should I do?
Update:
My comment below messed up code formatting so it's here:
I tried this out and got essentially what you describe. Might it have anything to do with the fact that target auto invokes a "makefile.rules" file?
auto:
    @echo this is makefile \#1 making $@ in $(PWD)
    FLAG=1 $(MAKE) -f makefile.rules rulestargetA
    FLAG=2 $(MAKE) -f makefile.rules rulestargetB
    ./myscript.py

I omitted that fact for simplicity, but now I wonder.
Update 2:
I don't understand why the makefiles aren't causing myscript.py to be run as though it's in the directory in which it resides, but I have been trying to get the script to operate correctly even when invoked from a different directory. It opens a couple of subprocesses, runs an executable in each subprocess, and saves the stdout from each subprocess to files. Python's subprocess.Popen passes in the current working directory, which would be where the script is invoked from, not where it resides, by default. I've added script to pass in the residential directory as cwd into the Popen call. For some reason, though, when I run myscript.py in its own directory it works, but when I invoke it from elsewhere (from the command line) it hangs in proc.communicate().  I should solve this python issue, but I'd still like to know why the external makefile can't invoke this script as from its own directory.

A: This is very strange. First the easy part:
target:
  ( cd $DIR; $MAKE auto; )

The parentheses do nothing here, and Make interprets $DIR as $D followed by the letter 'I' and the letter 'R'. Since the variable D is not defined, this works out to 'IR'. Same for $MAKE.
Now for the real problem. The makefiles as written should work. And you say it leaves directory #1 before the script runs? All I can suggest is that you try a simpler problem first. Put this in Makefile #1:
auto:
  @echo this is makefile \#1 making $@ in $(PWD)

And then use Makefile #2 to make target. This should produce
make[1]: Entering directory 'path-to-one'
this is makefile #1 making auto in path-to-one
make[1]: Leaving directory 'path-to-one'

If this is what it says, then there's something screwy about your script. If it produces nothing like this, you're failing to reach Makefile #1 at all, and maybe your DIR isn't right. If it works but says it's in directory #2, then my best guess is that you have another rule referring to Makefile #1. Try the experiment and let us know.
EDIT:
Well, that probably explains how it can leave directory #1 before the script runs. I suggest you comment out those lines and see if the problem is still there. Now about this script: what does it do and how do you know where it's running?


text:
Q: java.net.Proxy using HTTPS scheme java.net.Proxy.Type is limited to DIRECT, HTTP, SOCKS only.
How to connect with a host using HTTPS proxy?
Curl equivalent example:
curl --proxy https://PROXY_HOST:2272 -Iv http://example.com

A: java.net.Proxy does not support HTTPS proxy.
Solution is to use other client, e.g. apache.http.client.HttpClient.


text:
Q: Change queries dynamically - php, jquery Hey I'm trying to get 2 main sql queries to be more dynamic.
When the user clicks the marketing link, I want the 2 queries below to be updated with that link Id:
1. <?php generate_pagination('SELECT * FROM explore WHERE category="marketing"'); ?>

so when the marketing link is clicked, I want the query to change the category in the query to whatever the link id or class is. In this case 'marketing'.
Here is the other query that needs to be updated dynamically with the same link click:
2. $sql = "SELECT * FROM explore WHERE category='marketing' ORDER BY category LIMIT $start,$per_page";

There are a total of three pages, posted below:
pagination.php
<?php
function generate_pagination($sql) {
  include_once('config.php');
  $per_page = 3;

  //Calculating no of pages
  $result = mysql_query($sql);
  $count = mysql_num_rows($result);
  $pages = ceil($count/$per_page);

  //Pagination Numbers
  for($i=1; $i<=$pages; $i++)
  {
    echo '
'.$i.'
';
  }
}
?>

<?php generate_pagination('SELECT * FROM explore WHERE category="marketing"'); ?>

Marketing

pagination_data.php:
<?php
include('config.php');
$per_page = 3;
if($_GET)
{
$page=$_GET['page'];
}

$start = ($page-1)*$per_page;
//$sql = "select * from explore order by id limit $start,$per_page";
$sql = "SELECT * FROM explore WHERE category='marketing' ORDER BY category LIMIT $start,$per_page";
$result = mysql_query($sql);
?>

<?php
while($row = mysql_fetch_array($result))
{
$msg_id=$row['id'];
$message=$row['site_description'];
$site_price=$row['site_price'];

?>

<?php echo $msg_id; ?>
<?php echo $message; ?>
<?php echo $site_price; ?>

<?php
}
?>

jquery_pagination.php:
$(document).ready(function(){

    //Display Loading Image
    function Display_Load()
    {
        $("#loading").fadeIn(900,0);
        $("#loading").html("");
    }
    //Hide Loading Image
    function Hide_Load()
    {
        $("#loading").fadeOut('slow');
    };

   //Default Starting Page Results

    $("#pagination li:first").css({'color' : '#FF0084'}).css({'border' : 'none'});

    Display_Load();

    $("#content").load("pagination_data.php?page=1", Hide_Load());

    //Pagination Click
    $("#pagination li").click(function(){

        Display_Load();

        //CSS Styles
        $("#pagination li")
        .css({'border' : 'solid #dddddd 1px'})
        .css({'color' : '#0063DC'});

        $(this)
        .css({'color' : '#FF0084'})
        .css({'border' : 'none'});

        //Loading Data
        var pageNum = this.id;

    $("#content").load("pagination_data.php?page=" + pageNum, function(){
          Hide_Load();
          $(this).attr('data-page', pageNum);
    });
});

// Editing below.
        // Sort content Marketing
        $("#pagination a#marketing").click(function () {

        Display_Load();

        //CSS Styles
        $("#pagination li")
        .css({'border' : 'solid #dddddd 1px'})
        .css({'color' : '#0063DC'});

        $(this)
        .css({'color' : '#FF0084'})
        .css({'border' : 'none'});

                var pageNum = $('#content').attr('data-page');

                $("#content").load("pagination.data.php?page=" + pageNum, Hide_Load());
                });

});

A: To simplify things, you should always query with a LIMIT and page size, even if the offset is 0.
.. LIMIT 0,3

Let another query or cached value count the records (for max page number) . Mysql's COUNT is better for this than num_row'ing SELECT *.
$start = intval($_GET['page']); // zero if null or false
$sql = "SELECT * FROM explore WHERE category='marketing' ORDER BY category LIMIT $start,$per_page";


text:
Q: SysML instance vs. class I'm a bit confused about the concept of blocks in SysML.
From UML I understand that there is a distinction between classes and instances/objects like in OOP.
However, I'm not sure how this is implemented in SysML.
My questions:

*

*Does SysML distinguish between classes and instances?

*Assume I want to describe a general type of sub-system e.g. a card reader. My system should include serval instances of indentical (or parameterized) card readers. How do I best model this in SysML.

*Currently, I'm testing the SW Enterprise Architect. Is there anything special I have to consider if I want to model classes/instances here?
Thank you for your hints.

A: There is no difference between SysML and UML instances. In both cases an instance is shown with and underlined name. So what you see as blocks in SysML are simple stereotyped classes in UML. If you instantiate a block (in EA ctrl-drag it onto a diagram and select Instance) you get a concrete block. E.g. a block Car being instantiated becomes MyMercedes:Car (on the diagram showing with underlined text).
If you want to show real card readers, you create multiple instances. If you have different types of card readers you create different blocks which e.g. inherit from a basic card reader (there are different ways here).
Your last bullet point is too broad. Read the manual and look into Sparx' forum if you run into trouble (or ask here).

A: In SysML you have blocks ~ classes, and parts ~ attributes, where the SysML best practice does not aggregate blocks to blocks, i.e. when you describe subsystems you would display them as parts (instances of other blocks) of the main block.


text:
Q: MySQL dense_rank not skipping numbers I fairly new to MYSQL and I'm having trouble getting dense rank to work correctly, I was hoping someone would be able to help adjust my query to get the desired results.  Issue I'm having is after a ranking that is the same it goes to the next number instead of skipping a number.  I have shown both current results and desired results below.
        SELECT  gameid,
            score
         , IF(score <> @pscore,@i:=@i+1,@i:=@i) rank
         , @pscore := score
        FROM playerstats x
        , (SELECT @i:=0,@prev:='',@pscore:='') vars
        ORDER
        BY score DESC;

Current Results:

Desired Results:

A: Basically you need to sort the tdata before you rank it.
MySQL

CREATE TABLE playerstats  (
  `Score` INTEGER,
  `Player` VARCHAR(11)
);

INSERT INTO playerstats
  (`Score`, `Player`)
VALUES
  ('2543', 'jkoffa'),
  ('2204', 'probins'),
  ('2010', 'rwatson'),
  ('2010', 'nbk'),
  ('2010', 'tthamos'),
  ('1950', 'en,acdonald'),
  ('1927', 'dmaginis');

SELECT
`Player`
,IF(@score <> `Score` , @rn := @rn + @cor +1, @rn:= @rn) rnknumber
,IF(@score = `Score` , IF(@cor > 0,@cor := @cor +1,@cor := 1), @cor := 0) correction
,@score := `Score` 'Score'
FROM
(SELECT `Score`, `Player` FROM playerstats ORDER BY Score DESC) t1
, (SELECT @score := -1) t2
,(SELECT @rn := 0) t3,(SELECT @cor := 0) t4

Player      | rnknumber | correction | Score
:---------- | :-------- | ---------: | ----:
jkoffa      | 1         |          0 |  2543
probins     | 2         |          0 |  2204
rwatson     | 3         |          0 |  2010
nbk         | 3         |          1 |  2010
tthamos     | 3         |          2 |  2010
en,acdonald | 6         |          0 |  1950
dmaginis    | 7         |          0 |  1927

db<>fiddle here
for Mariadb 10.3

CREATE TABLE playerstats  (
  `Score` INTEGER,
  `Player` VARCHAR(11)
);

INSERT INTO playerstats
  (`Score`, `Player`)
VALUES
 ('2010', 'tthamos'),
  ('1950', 'acdonald'),
  ('1927', 'dmaginis'),
  ('2010', 'nbk'),
  ('2543', 'jkoffa'),
  ('2204', 'probins'),
  ('2010', 'rwatson');

SELECT
`Player`
,IF(@score <> `Score` , @rn := @rn + @cor +1, @rn:= @rn ) rnknumber
,IF(@score = `Score` , IF(@cor > 0,@cor := @cor +1,@cor := 1), @cor := 0) correction
,@score := `Score` 'Score'
FROM
(SELECT `Score`, `Player` FROM playerstats ORDER BY Score DESC LIMIT 18446744073709551615) t1
, (SELECT @score := -1) t2
,(SELECT @rn := 0) t3,(SELECT @cor := 0) t4

Player   | rnknumber | correction | Score
:------- | :-------- | ---------: | ----:
jkoffa   | 1         |          0 |  2543
probins  | 2         |          0 |  2204
tthamos  | 3         |          0 |  2010
nbk      | 3         |          1 |  2010
rwatson  | 3         |          2 |  2010
acdonald | 6         |          0 |  1950
dmaginis | 7         |          0 |  1927

db<>fiddle here

A: nbk - I apologize for the pictures will make sure to use text next time. Thank you again for your time. Unfortunately it only works if data is entered in the correct order. If you were to take the bottom three entries and put them in first then tthomos would be ranked #1.
CREATE TABLE playerstats  (
  `Score` INTEGER,
  `Player` VARCHAR(11)
);

INSERT INTO playerstats
  (`Score`, `Player`)
VALUES
  ('2010', 'tthamos'),
  ('1950', 'acdonald'),
  ('1927', 'dmaginis'),
  ('2543', 'jkoffa'),
  ('2204', 'probins'),
  ('2010', 'rwatson');

then ran:
SELECT
`Player`
,IF(@score <> `Score` , @rn := @rn + @cor +1, @rn:= @rn) rnknumber
,IF(@score = `Score` , @cor := 1, @cor := 0) correction
,@score := `Score` 'Score'
FROM
(SELECT `Score`, `Player` FROM playerstats ORDER BY Score DESC) t1
, (SELECT @score := -1) t2
,(SELECT @rn := 0) t3,(SELECT @cor := 0) t4

You would get:
tthamos   1     0   2010
acdonal   2     0   1950
dmaginis  3     0   1927
jkoffa    4     0   2543
probins   5     0   2204
rwatshon  6     0   2010


text:
Q: How to convert columns of a dataframe to list with different lengths? I have a data frame with columns of different lengths. It looks like this:
Croptypes   VariableInputs   FixedInputs
barley      fertilizer       land
rapeseed                     labor
wheat                        capital

when I list the elements from the columns by the following codes:
Croptypes = list(df['Croptypes'])
VariableInputs = list(df['VariableInputs'])

I get this results.
['barley', 'rapeseed', 'wheat']
['fertilizer', nan, nan]

How can I tell "list" not to list the empty cells?
I expect:
['barley', 'rapeseed', 'wheat']
['fertilizer']

A: Use dropna and tolist:
>>> df['VariableInputs'].dropna().tolist()
['fertilizer']
>>>

Or for every column:
print({k: v.dropna().tolist() for k, v in df.to_dict('s').items()})

Output:
{'Croptypes': ['barley', 'rapeseed', 'wheat'], 'VariableInputs': ['fertilizer'], 'FixedInputs': ['land', 'labor', 'capital']}

A: You can create dictionary for each column with values as list as:
d = {col:df[col].dropna().tolist() for col in df}

d
{'Croptypes': ['barley', 'rapeseed', 'wheat'],
 'VariableInputs': ['fertilizer'],
 'FixedInputs': ['land', 'labor', 'capital']}


text:
Q: Weird Process.Start behavior under NUnit I'm using Process.Start on plink.exe to run a remote call on a Linux machine. This works well, unless run in the context of NUnit (I've tried both TestDriven.NET and ReSharper's unit test runner).
In the NUnit test, the process seems to close immediately and not actually do anything, like something is forcing it to close.
Here is the code, note that in the context of a console application, it works perfectly.
var processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = @"D:\Tools\plink\plink.exe";
processStartInfo.Arguments = "-ssh #some parameters here#;
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardOutput = true;

var process = new Process();

process.StartInfo = processStartInfo;
process.Start();
var output = process.StandardOutput.ReadToEnd();

A: May be you forgot:
process.WaitForExit();


text:
Q: Inheritance causes class to act like it is Shared When using inheritance on Winforms, it causes the class to appear Shared.
Why only the second line in the Main method displays a syntax warning? TestForm102.Widgets.Count should highlight the same issue.
Note: I added the MustInherit to TestForm101 to highlight the issue (...what it should display). If I remove it, the form simply acts like it is shared too.

A: The first line works because TestForm102 is an instance of TestForm102 rather than a type as one would expect. It's auto-generated by VS and you'll find it in My.Forms. You're last line fails because VS cannot auto-generate an instance of a MustInherit form and/or a form without a public parameterless constructor. At this point TestForm101 is a type, and as observed, you cannot reference a non-shared member without an object reference.
Dim y As Integer = My.Forms.TestForm102.Widgets.Count '<-Ok
Dim x As Integer = My.Forms.TestForm101.Widgets.count '<-Error

Error: 'TestForm101' is not a member of ...MyForms


text:
Q: undefined method `config' for Trello:Module I am using the ruby-trello gem (https://github.com/jeremytregunna/ruby-trello), and have been for some time with no issue.  Today, the console is giving me this error:
undefined method `config' for Trello:Module

I'm fairly certain this has nothing to do with this gem but rather, I suspect it has something to do with either rvm or some other issue.
I'm seeing the same issue with Ruby-1.9.3 and Ruby-2.0.0.  As far as I can tell, nothing has changed, no code commits, no Rails versions, but obviously something must have changed because this appeared all of the sudden.
UPDATE
backtrace:
NoMethodError: undefined method `config' for Trello:Module
    from (irb):2
    from /Users/kevin/.rvm/gems/ruby-2.0.0-p451/gems/railties-      3.2.9/lib/rails/commands/console.rb:47:in `start'
from /Users/kevin/.rvm/gems/ruby-2.0.0-p451/gems/railties-3.2.9/lib/rails/commands/console.rb:8:in `start'
from /Users/kevin/.rvm/gems/ruby-2.0.0-p451/gems/railties-3.2.9/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

Thanks for any help,
kevin

A: This turned out to be rvm.  Imploding and then reinstalling rvm and rubies fixed this.


text:
Q: Where to install mingw-make from? (CMAKE) I've been trying to compile my code with CMake using the "MSYS Makefiles" generator. I wrote the following command:
cmake -S . -B build/ -G "MSYS Makefiles
But I was presented with the following error:

    CMake Error: CMake was unable to find a build program corresponding to "MSYS Makefiles".  CMAKE_MAKE_PROGRAM is not set.  You probably need to select a different build tool.
    CMake Error: CMake was unable to find a build program corresponding to "MSYS Makefiles".  CMAKE_MAKE_PROGRAM is not set.  You probably need to select a different build tool.
    CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
    CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
    CMake Error: CMAKE_AR was not found, please set to archive program.

After some investigation, I found that I had to install something called "mingw-make" to do this. Apparently this "mingw-make" can be installed in the "MinGW gui". Note that I checked if I already have "mingw-make" installed and I don't.
I'm confused because I can't seem to find this "MinGW gui" anywhere. I installed MinGW, and only have an application on my computer called "Modify or Remove MinGW". I searched the install options, and couldn't find "mingw-make" anywhere.
Where can I download this "mingw-make" from? Thanks.

A: Use mingw32-make only with cmake -G"MinGW Makefiles".
Use make only with cmake -G"MSYS Makefiles".
But if you want the best performance you should get Ninja and use ninja with cmake -G"Ninja".
MinGW is all command line, though there are some GUI installers for it. MinGW-w64 is the successor to MinGW which also supports 64-bit Windows.
There are standalone MinGW-w64 Windows releases available from https://winlibs.com/ that don't require installation steps, just extract. This also includes mingw32-make


text:
Q: Prototype - TypeError: A.travelTo is not a function Script to generate canvas doodle
<script type="text/javascript">

var doodle = (function() {
    Function.prototype.bind = Function.prototype.bind || function(u) {
        var v = this;
        return function() {
            return v.apply(u, arguments);
        };
    };
    var g = false;
    var a = function(u) {
        g && console && console.log && console.log(u)
    };
    var n = document.documentElement;
    var h = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(u) {
        setTimeout(u, 17)
    };
    var m = Math.PI / 2,
        r = {};
    var b = function(u) {
        this.canvas = u;
        this.ctx = u.getContext("2d");
        this.objects = [];
        this.restart_timeout = 2500;
        this.paused = false;
        this.destroyed = false;
        return this
    };
    var e = 0,
        f, o = (new Date) * 1 - 1;
    var t = 50;
    var i = function() {
        var u = 1000 / ((f = new Date) - o);
        e += (u - e) / t;
        o = f
    };
    b.prototype.frame = function() {
        if (this.destroyed) {
            return
        }
        this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
        for (var v in this.objects) {
            if (this.objects[v].destroyed == true) {
                this.objects.splice(v, 1)
            } else {
                this.objects[v].tick(this.ctx)
            }
        }
        if (this.objects.length == 0) {
            var u = this;
            setTimeout(function() {
                a("restarting in " + u.restart_timeout);
                u.setup();
                u.frame()
            }, this.restart_timeout)
        } else {
            if (!this.paused) {
                h(this.frame.bind(this))
            }
        }
    };
    b.prototype.setup = function() {
        this.objects.push(d(this))
    };
    b.prototype.destroy = function() {
        this.destroyed = true;
        this.objects = []
    };
    var j = function(u, v) {
        this.x = u;
        this.y = v;
        this.planes = []
    };
    j.prototype.addPlane = function(w, u, x) {
        var z = this.x + w,
            y = this.y + u;
        var v = new c(r.jet_img, z, y, x, w, u);
        this.planes.push(v);
        return v
    };
    j.prototype.travelTo = function(u, B, w) {
        var A;
        for (var z in this.planes) {
            A = this.planes[z];
            A.travelTo(A.formation_x + u, A.formation_y + B, w)
        }
    };
    j.prototype.tick = function(u) {
        for (var v in this.planes) {
            if (this.planes[v].destroyed) {
                a("deleting plane " + v);
                this.planes.splice(v, 1)
            } else {
                this.planes[v].tick(u)
            }
        }
        if (this.planes.length == 0) {
            this.destroy()
        }
    };
    j.prototype.destroy = function() {
        this.destroyed = true
    };
    var d = function(w) {
        var z = Math.random() > 0.5 ? true : false;
        var u = z ? w.ctx.canvas.height : 10 + (w.ctx.canvas.height - 10) * Math.random();
        var v = z ? (w.ctx.canvas.width / 2 - 10) * Math.random() : 10;
        a("starting from:" + v + " ," + u);
        var A = new j(v, u);
        A.addPlane(0, 0, "255, 153, 51");
        A.addPlane(50, -50, "222, 222, 222");
        A.addPlane(100, 0, "0, 128, 0");
        var x = w.ctx.canvas.height - u;
        var y = w.ctx.canvas.width - v;
        A.travelTo(y, x, 3 + 3 * Math.random());
        return A
    };
    var c = function(y, x, v, z, w, u) {
        this.img = y;
        this.x = x;
        this.y = v;
        this.formation_x = w;
        this.formation_y = u;
        this.smoke_particles_list = [];
        this.smoke_rgb = z;
        this.destroy_plane = false;
        this.pather = new k();
        return this
    };
    c.prototype.draw = function(u) {
        u.save();
        var w = Math.atan(this.pather.slope) + m;
        u.translate(this.x, this.y);
        u.rotate(w);
        u.drawImage(this.img, 0, 0);
        u.restore();
        for (var v in this.smoke_particles_list) {
            if (this.smoke_particles_list[v].destroyed == true) {
                this.smoke_particles_list.splice(v, 1)
            } else {
                this.smoke_particles_list[v].draw(u)
            }
        }
    };
    c.prototype.travelTo = function(x, w, u) {
        this.pather.createPath(this.x, this.y, x, w, u)
    };
    c.prototype.tick = function(u) {
        this.pather.move();
        var A = Math.atan(this.pather.slope) + m;
        var y = -this.formation_x + this.formation_x * Math.cos(A) - this.formation_y * Math.sin(A);
        var x = -this.formation_y + this.formation_x * Math.sin(A) + this.formation_y * Math.cos(A);
        this.x = this.pather.x + y;
        this.y = this.pather.y + x;
        if (this.smoke_particles_list.length < 100 && !this.destroy_plane) {
            var B = (11 + 2 * Math.random()) * Math.cos(A) - (29 + 4 * Math.random()) * Math.sin(A);
            var z = (11 + 2 * Math.random()) * Math.sin(A) + (29 + 4 * Math.random()) * Math.cos(A);
            var v = new l(this.x + B, this.y + z, this.smoke_rgb);
            this.smoke_particles_list.push(v)
        }
        this.draw(u);
        var w = 50;
        if (this.x > u.canvas.width + w || this.y > u.canvas.height + w || this.x < 0 - w || this.y < 0 - w) {
            this.destroy_plane = true
        } else {
            this.destroy_plane = false
        }
        if (this.destroy_plane && this.smoke_particles_list.length == 0) {
            this.destroy()
        }
    };
    c.prototype.destroy = function() {
        this.destroyed = true
    };
    var k = function() {
        this.speed = 2.5;
        this.slope = null;
        this.x = 0;
        this.y = 0;
        this.delta_x = 0;
        this.delta_y = 0
    };
    k.prototype.createPath = function(x, z, w, y, u) {
        this.x = x;
        this.y = z;
        this.delta_x = w - x;
        this.delta_y = y - z;
        this.slope = this.delta_y / this.delta_x;
        this.speed = u
    };
    k.prototype.setSpeed = function(u) {
        this.speed = u
    };
    k.prototype.move = function() {
        this.x = this.x + Math.cos(Math.atan(this.slope)) * this.speed;
        this.y = this.y + Math.sin(Math.atan(this.slope)) * this.speed
    };
    var l = function(w, u, v) {
        this.x = w;
        this.y = u;
        this.opacity = 0.5;
        this.radius = 2 + Math.random();
        this.rgb = v
    };
    l.prototype.draw = function(u) {
        u.save();
        u.beginPath();
        u.fillStyle = "rgba(" + this.rgb + "," + this.opacity + ")";
        u.shadowColor = "rgba(" + this.rgb + ",1)";
        u.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
        u.fill();
        this.radius = this.radius + 0.05;
        this.opacity = this.opacity - 0.005;
        if (this.opacity <= 0) {
            this.destroyed = true
        }
        u.restore()
    };
    var q;
    var p = function(w) {
        var v = document.createElement("canvas");
        v.id = "canvas_doodle";
        v.height = window.innerHeight || n.clientHeight;
        v.width = window.innerWidth || n.clientWidth;
        var u = v.style;
        u.position = "fixed";
        u.top = 0;
        u.left = 0;
        u.zIndex = 1138;
        u.pointerEvents = "none";
        document.body.appendChild(v);
        q = new b(v);
        r.jet_img = new Image();
        r.jet_img.src = w;
        r.jet_img.onload = function() {
            q.setup();
            h(q.frame.bind(q))
        }
    };
    var s = function() {
        q.destroy();
        setTimeout(function() {
            document.body.removeChild(document.getElementById("canvas_doodle"))
        }, 50);
        delete q
    };
    return {
        init: p,
        destroy: s
    }
})();
doodle.init("//c7a8fc9299240f740ff1dbf9d91ec237093f18e4.googledrive.com/host/0B4ykP2BBAseJcVZpY05fSF8wNzA/plane.png");

</script>

The above code when included before body </body> throws exception TypeError: A.travelTo is not a function.
It only works if I remove all the jquery included in my index page, otherwise it throws above exception. You can test by including the script like below in plain html file
<html>
   <body style="background-color: #fff">
       <script type="text/javascript">
       Script Code as mentioned above
       </script>
   </body>
</html>

How could I resolve it ?

A: This is a shot in the dark, but try to change this
j.prototype.travelTo = function(u, B, w) {
    var A;
    for (var z in this.planes) {
        A = this.planes[z];
        A.travelTo(A.formation_x + u, A.formation_y + B, w)
    }
};

to that
j.prototype.travelTo = function(u, B, w) {
    var A;
    for (var z=0; z<this.planes.length; z++) {
        A = this.planes[z];
        A.travelTo(A.formation_x + u, A.formation_y + B, w)
    }
};

Update:
Considering your new error, change this
for (var v in this.smoke_particles_list) {

to that
for (var v=0; v<this.smoke_particles_list.length; v++) {

A shot at explaining this
The for..in loop, other than for, iterates over every enumerable property of your object. That is not only the indices of the array (0,1,2,3), but also methods or properties inherited from non-built-in objects. In your for-loops, the not a function error was indicating, that one element might be something other than your objects, maybe an inherited prototype function or something.
So I assume some library messed up one of the prototypes, but as I could not reconstruct the issue, I cannot tell you which one and how. And as I said, it was more of a guess.
For a detailed explanation see MDN docs here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...in

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype

This example shows what probably happened
Array.prototype.methodX = function(){}

var xyz = [];
xyz.push(1)
xyz.push(2)
xyz.push(3)

for (var item in xyz) {console.log(item)}
// Outputs:
//  0
//  1
//  2
//  methodX

Usually you're better of, iterating with for, when you have an array structure
for (var i=0; i<xyz.length; i++) {console.log(i)}
// Outputs:
//  0
//  1
//  2


text:
Q: A block in beamer I am unable to understand why this is not compiling,
\documentclass{beamer}
\begin{document}
  \begin{frame}{}
  \begin{block}
    $$\phi (S) \geq \lambda (1 - \sqrt {C \delta})$$
  \end{block}
  \end{frame}
\end{document}

*

*Can someone help?

A: The block environment expects a title. You can have it be empty, but it needs to be there:
\documentclass{beamer}
\begin{document}
  \begin{frame}{}
    \begin{block}{}
    \[\phi (S) \geq \lambda (1 - \sqrt {C \delta})\]
    \end{block}
  \end{frame}
\end{document}

A: It has only to do with an empty {} after the \begin{block} even without a title. As another hack, you can only insert an empty line after \begin{block}. So this works:
\documentclass{beamer}
\begin{document}
  \begin{frame}{}
  \begin{block}{}
    \[\phi (S) \geq \lambda (1 - \sqrt {C \delta})\]
  \end{block}
  \end{frame}
\end{document}

Also this:
\documentclass{beamer}
\begin{document}
  \begin{frame}{}
  \begin{block}

    \[\phi (S) \geq \lambda (1 - \sqrt {C \delta})\]
  \end{block}
  \end{frame}
\end{document}


text:
Q: Can't run Unity3d, can't create the ALF for the manual license activation I installed Unity 2021.3.11f1 on Windows 11, but when I run the editor it says "No valid Unity Editor license found. Please activate your license." So I tried to do [these instructions][1] to activate my license.
However, after running "unity.exe -batchmode -createManualActivationFile -logfile", I can't find the Activation License File (ALF) anyhwere, be it C:/Users/Naburu38, C:\ProgramData\Unity, C:\Users\Naburu38\AppData\Local\Unity, or C:\Users\Naburu38\AppData\LocalLow\Unity.
I run the CMD both as regular and admin. I checked my admin account folders too.
Any suggestions?


text:
Q: Python: Get index of last element that is smaller than a given number Let's say I have the following numpy array of time points of a certain measurement, where it can be assumed that it is ordered from small to large:
time_points = np.array([0.4, 0.8, 1.2, 2.0, 2.4, 2.8, 3.2, 3.6])

I would like to find the index of the last element that is lower or equal to three. In this example the element is 2.8 and the index is 5. So I would like a python code that gives me that 5. A relatively short code can do this:
index = 0
while time_points[index] <= 3:
    index += 1
index -= 1

But my time_points array can get very long and I was wondering if there is a faster way, just like the method index() to do this in only one line? Something like
>>> time_points = np.array([0.4, 0.8, 1.2, 2.0, 2.4, 2.8, 3.2, 3.6])
>>> index = function(time_points, 3)
5

Or perhaps code with multiple lines, but that uses the numpy library to make the operation faster.
Thanks in advance!

A: numpy.searchsorted is literally the exact function you need.
It uses binary search to find the closest point, where it "cuts" the list in half everytime and only looks at that half.
It can be used like this, say arr is the list.
>>> arr = np.array([0.4, 0.8, 1.2, 2.0, 2.4, 2.8, 3.2, 3.6])
>>> arr.searchsorted(3, 'right') - 1
5
>>> arr.searchsorted(2.8, 'right') - 1
5
>>> arr.searchsorted(0, 'right') - 1 # No greater item
-1

I doubt there is a faster numpy method as this is a one liner, and uses binary search which is generally the fastest search method on a sorted array.


text:
Q: How does MATLAB vectorized code work "under the hood"? I understand how using vectorization in a language like MATLAB speeds up the code by removing the overhead of maintaining a loop variable, but how does the vectorization actually take place in the assembly / machine code?  I mean there still has to be a loop somewhere, right?

A: Matlab 'vectorization' concept is completely different than the vector instructions concept, such as SSE. This is a common misunderstanding between two groups of people: matlab programmers and C/asm programmers. Matlab 'vectorization', as the word is commonly used, is only about expressing loops in the form of (vectors of) matrix indices, and sometimes about writing things in terms of basic matrix/vector operations (BLAS), instead of writing the loop itself. Matlab 'vectorized' code is not necessarily expressed as vectorized CPU instructions. Consider the following code:
A = rand(1000);
B = (A(1:2:end,:)+A(2:2:end,:))/2;

This code computes mean values for two adjacent matrix rows. It is a 'vectorized' matlab expression. However, since matlab stores matrices column-wise (columns are contiguous in memory), this operation is not trivially changed into operations on SSE vectors: since we perform the operations row-wise the data you need to load into the vectors is not stored contiguously in the memory.
This code on the other hand
A = rand(1000);
B = (A(:,1:2:end)+A(:,2:2:end))/2;

can take advantage of SSE instructions and streaming instructions, since we operate on two adjacent columns at a time.
So, matlab 'vectorization' is not equivalent to using CPU vector instructions. It is just a word used to signify the lack of a loop implemented in MATLAB. To add to the confusion, sometimes people even use the word to say that some loop has been implemented using a built-in function, such as arrayfun, or bsxfun. Which is even more misleading since those functions might be significantly slower than native matlab loops. As robince said, not all loops are slow in matlab nowadays, though you do need to know when they work, and when they don't.
And in any way you always need a loop, it is just implemented in matlab built-in functions / BLAS instead of the users matlab code.

A: Yes there is still a loop. But it is able to loop directly in compiled code. Loops in Fortran (on which Matlab was originally based) C or C++ are not inherently slow. That they are slow in Matlab is a property of dynamic runtime (they are also slower in other dynamic languages like Python).
Since Matlab has introduced a Just-In-Time compiler loop performance has actually increased dramatically - so the old guidelines to avoid loops are less important with recent versions than they once were.


text:
Q: Issues with KeyListener and Timer in Java Pong game I am currently trying to build a basic Pong game in Java, and I am having difficulty with two things. The first is that my rackets move up and down as they should, but once they reach the edge of the frame, they completely freeze up. I cannot figure why. Next, I am not sure how to use Timer or Thread.sleep to momentarily pause the game after each score. Once one of the players score, I want the game to return the ball back to the center and have it wait for about 3 seconds before the ball moves again to start the next point. Any help would be great. Thanks!
Here is my code
Pong Class
import java.awt.*;

import javax.swing.*;

public class Pong extends JFrame{

    public static final int appWIDTH = 500;     //width of jframe
    public static final int appHEIGHT = 500;    //height of jframe
    public final int rWIDTH = 20;               //width of racket
    public final int rHEIGHT = 60;              //height of racket
    PongPanel panel;                            //Jpanel to be added

    /*
     * constructor for a Pong object
     */
    public Pong() {
        setSize(appWIDTH, appHEIGHT);
        setTitle("PONG");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setBackground(Color.BLACK);
    }

    /*
     * Starts the application
     */
    public void start() {
        panel = new PongPanel(this);
        add(panel);
        addKeyListener(panel);
        setVisible(true);
        setFocusable(true);
    }

    //Returns a PongPanel
    public PongPanel getPanel() {
        return panel;
    }

    public static void main(String[] args) {
        Pong game = new Pong();
        game.start();
    }
}

Panel class
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class PongPanel extends JPanel implements KeyListener {

    private Pong game;
    private Ball ball;
    private Racket p1, p2;
    private int score1, score2;
    Timer timer;

    /*
     * Constructor for a PongPanel which is a JPanel that holds two rackets and a ball
     */
    public PongPanel(Pong game) {
        this.game = game;
        p1 = new Racket(game, KeyEvent.VK_W, KeyEvent.VK_S, 0);
        p2 = new Racket(game, KeyEvent.VK_UP, KeyEvent.VK_DOWN, game.getWidth() - game.rWIDTH);
        ball = new Ball(game);
        addKeyListener(this);
        setFocusable(true);
        setVisible(true);
    }

    /*
     * Returns the Racket object associated with player 1
     */
    public Racket getRacket1() {
        return p1;
    }

    /*
     * Returns the Racket object associated with player 2
     */
    public Racket getRacket2() {
        return p2;
    }

    //Increases score of the player indicated by the parameter
    public void increaseScore(int playerNo) {
        if(playerNo == 1)
            score1++;
        else
            score2++;
    }

    //Returns the score of the player indicated by the parameter
    public int getScore(int playerNo) {
        if(playerNo == 1)
            return score1;
        else
            return score2;
    }

    public void update() {
        ball.hitBTS();
        p1.move();
        p2.move();
        repaint();
    }

    public void keyPressed(KeyEvent ke) {
        p1.kpressed(ke.getKeyCode());
        p2.kpressed(ke.getKeyCode());
    }

    public void keyReleased(KeyEvent ke){
        p1.krelease(ke.getKeyCode());
        p2.krelease(ke.getKeyCode());
    }

    public void keyTyped(KeyEvent ke) {}

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        ball.paint(g);
        p1.paint(g);
        p2.paint(g);
        update();
    }
}

Ball Class
import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Ball {

    private JFrame frame = new JFrame();
    private Pong game;
    final int bWIDTH = 30;                  //ball width
    final int bHEIGHT = 30;                 //ball height
    private int xspeed = 1;                 //horizontal speed of the ball
    private int yspeed = 1;                 //vertical speed of the ball
    int x;                                  //x-coordinate of the ball
    int y;                                  //y-coordinate of the ball

    /*
     * Constructor of a ball object. Sets the ball in the center of frame
     */
    public Ball(Pong game) {
        x = game.getWidth() / 2 - (bWIDTH/2);
        y = game.getHeight() / 2 - (bHEIGHT/2);
        this.game = game;
    }

    /*
     * Checks whether the ball has hit the bottom or top of the frame
     * or if it has reached the left or right edge (score)
     */
    public void hitBTS() {
        x += xspeed;
        y += yspeed;

        if((x + bWIDTH) > game.getWidth()) {
            game.getPanel().increaseScore(1);
            x = game.getWidth() / 2 - (bWIDTH/2);
            y = game.getHeight() / 2 -(bHEIGHT/2);
        }

        else if(x < 0) {
            game.getPanel().increaseScore(2);
            x = game.getWidth() / 2 - (bWIDTH/2);
            y = game.getHeight() / 2 -(bHEIGHT/2);
        }

        else if(y < 0 || (y > game.getHeight() + bHEIGHT)) {
            yspeed = -yspeed;
        }

        checkScore();
        checkCollision();
    }

    //Shows a dialog box indicating the winter if one player reaches
    //a score of 3
    public void checkScore() {
        if(game.getPanel().getScore(1) == 3) {
            JOptionPane.showMessageDialog(frame, "Player 1 wins");
        }
        else if(game.getPanel().getScore(2) == 3) {
            JOptionPane.showMessageDialog(frame, "Player 2 wins");
        }
    }

    //Checks if the ball has hit a racket
    public void checkCollision() {
                 if(getBallBounds().intersects(game.getPanel().getRacket1().getBounds()) ||
getBallBounds().intersects(game.getPanel().getRacket2().getBounds())) {
            xspeed = -xspeed;
        }
    }

    public Rectangle getBallBounds() {
        return new Rectangle(x, y, bWIDTH, bHEIGHT);
    }

    public void paint(Graphics g) {
        g.fillRect(x, y, bWIDTH, bHEIGHT);
    }

}

Racket Class
import java.awt.*;
import java.awt.event.*;

public class Racket {

    private Pong game;
    private int yspeed = 0;     //Number of pixels that the racket moves
    int x;                      //x-coordinate of racket
    int y;                      //y-coordinate of racket
    int keyUp, keyDown;         //key code associated with the key pressed

    /*
     * Constructor for a racket object. Racket receives a keycode and horizontal
     * starting position.
     */
    public Racket(Pong game, int keyUp, int keyDown, int x) {
        this.game = game;
        this.x = x;
        this.keyUp = keyUp;
        this.keyDown = keyDown;
        y = game.getHeight()/2;
    }

    /*
     * Indicates how the racket should move depending on its position.
     */
    public void move() {
        if(y > 0 && y < game.getHeight() - game.rHEIGHT)
            y += yspeed;
        else if(y <= 0)
            y = y + 3;
        else if(y == game.getHeight() - game.rHEIGHT)
            y = y - 3;
    }

    /*
     * If key has been pressed, the number of pixels the
     * racket moves becomes positive or negative
     */
    public void kpressed(int keyCode) {
        if(keyCode == keyUp) {
            yspeed = -3;
        }

        if(keyCode == keyDown)
            yspeed = 3;
    }

    /*
     * When the key is no longer being pressed, the
     * racket stops moving.
     */
    public void krelease(int keyCode) {
        if(keyCode == keyUp)
            yspeed = 0;
        else if (keyCode == keyDown)
            yspeed = 0;
    }

    public Rectangle getBounds() {
        return new Rectangle(x, y, game.rWIDTH, game.rHEIGHT);
    }

    public void paint(Graphics g) {
        g.fillRect(x, y, game.rWIDTH, game.rHEIGHT);
    }
}

A: To answer your first question, change the move method of your racket class as follows:
public void move() {
    if(y > 0 && y < game.getHeight() - game.rHEIGHT)
        y += yspeed;
    else if(y <= 0)
        y = y + 3;
    else if(y >= game.getHeight() - game.rHEIGHT)
        y = y - 3;
}

Otherwise, when y becomes larger than game.getHeight() - game.rHEIGHT, it will freeze as it won't match any of the 3 conditions in the move method again.
To answer your second question, you can change the checkScore method of your Ball class as follows:
public void checkScore() {
    if(game.getPanel().getScore(1) == 3) {
        JOptionPane.showMessageDialog(frame, "Player 1 wins");
    }
    else if(game.getPanel().getScore(2) == 3) {
        JOptionPane.showMessageDialog(frame, "Player 2 wins");
    }
    else {
        x = game.getWidth() / 2 - (bWIDTH/2);
        y = game.getHeight() / 2 - (bHEIGHT/2);
        Thread.sleep(3000);
    }
}


text:
Q: Showdialog and Focus (incredible) I noticed a strange problem in VB.NET 2010.
If I call showdialog in a TextBox_LostFocus, when I close the form it causes a Loop, but ONLY if I pass from the first textbox to the second USING THE MOUSE! If I use tab it works normally.
I show whith an example:

*

*Create New project and create two forms, form1 and form2

*In form1, create two textboxes.

*In the textbox1.lostfocus, paste the following code

VB.NET Code:
Dim f As New Form2
f.ShowDialog()

Now: the focus is on textbox1. Right?

*

*If you move to textbox2 with tab key, form2 appears. If you close it it's all normal

*BUT if you move to textbox2 using the mouse, form2 appears and if you close it another form2 appears, until 23 times when you get an exception

I workarounded it moving the "dim" statement in declaration area of form1, but anyone has an idea of why of that behaviour?
Thanks in advance.


text:
Q: stuck at asking for CAMERA_ROLL permission. getting error: undefined is not an object (evaluating '_expo.Permission.askAsync') getting this warning (Almost an error, because app stuck at this point with showing yellow warning) while asking for the permission in react-native. Below is my code
//MY IMPORTS

import * as ImagePicker from 'expo-image-picker';
import * as Permissions from 'expo-permissions';

//My CODE

onImageUpload = async () => {

    const {status, permissions} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    try {

        if (status === 'granted') {
            console.log("granted!!")
        }
    } catch (err) {
        console.log('onImageUpload error:' + err.message);
    }
}

A: You do not seem to have installed the module correctly. Perform the installation command from the command.
you'll need to run expo install expo-permissions


text:
Q: Minimum of $\left| \sin x- 1\right| + \left|\sin x- 2\right| + \left| \sin x -3\right| + \left| \sin x+1\right|$ I would like to know the minimum value of $$\left| \sin x- 1\right| + \left|\sin x- 2\right| + \left| \sin x -3\right| + \left| \sin x+1\right|$$
for $x \in \mathbb{R}$.

A: $\sin x-1$ is always non-positive.
$\sin x - 2$ is always negative.
$\sin x -3$ is always negative.
$\sin x + 1$ is always non-negative.
Therefore the whole expression reduces to
$$
-(\sin x-1) -(\sin x-2) -(\sin x-3) + (\sin x+1).
$$
(But if you meant $\sin(x-1)$ where you wrote $\sin x-1$, then none of the above will help you.)
You get $7-2\sin x$.  Since the sine oscillates between $1$ and $-1$, the smallest this function ever gets is $7-2=5$.

A: As $x$ varies through $\mathbb R$, $\sin x$ varies through $[-1,1]$. The problem then reduces to finding the minimum of $f(y)=|y-1|+|y-2|+|y-3|+|y+1|$ for $y\in [-1,1]$.
But on $[-1,1]$, $f(y)=(1-y)+(2-y)+(3-y)+(y+1)=7-2y$, so the minimum value is $5$.

A: Here's the graph, which should do it for you:

(Here, I take $|\sin x-1|$, etc. to mean $|\sin(x)-1|$, etc.)
It looks like the minimum value is 5, and Mathematica confirms this:

A: For every $x \in \mathbb{R}$ we have
$$
-1 \le \sin x\le 1 \quad \forall\ x \in \mathbb{R},
$$
and therefore:
\begin{eqnarray}
f(x)&:=&|\sin x-1|+|\sin x-2|+|\sin x-3|+|\sin x+1|\\
&=&(1-\sin x)+(2-\sin x)+(3-\sin x)+(\sin x+1)\\
&=&5+2(1-\sin x).
\end{eqnarray}
The minimum is therefore equal to $5=f(\pi/2)$.

A: Note that $-1\le\sin x\le1$ for all real $x$. This allows you to rewrite each of the $4$ summands without the absolute value bars. For example: $\sin x-3\leq 1-3=-2<0$, so $|\sin x-3|=3-\sin x$; and $\sin x+1\geq -1+1=0$, so $|\sin x+1|=\sin x+1$. Simplify the resulting expression, and then use the fact that $\sin x$ ranges from $-1$ to $1$ (inclusive) to minimize it.

A: As $-1\leq\sin x\leq1\implies |\sin x-1|=1-\sin x$, $|\sin x-2|=2-\sin x$, $|\sin x-3|=3-\sin x$, $|\sin x+1|=1+\sin x$
Thus the given expression becomes, $1-\sin x+2-\sin x+3-\sin x+1+\sin x=7-2\sin x$ which is minimum when $\sin x $ is maximum and equal to $1$ which gives minimum value equal to $5.$

A: The number $\sin x$ is trying to decide where to live on the number line.
Her friends live at $-1$, $1$, $2$, and $3$.
She wants the sum of her distances to her friends to be as small as possible.
Where should $\sin x$ live? Unfortunately, she has to live between $-1$ and $1$. She starts at $-1$ and begins to travel to the right. For every tiny step she takes, her distance from $-1$ increases by $1$ step, and the sum of her distances from $1$, $2$, and $3$ decreases by $3$ steps, for a net decrease of $2$ steps.
So she should go to the right as far as her nature allows. I hope that $1$ doesn't mind when $\sin x$ moves in.


text:
Q: Show pi = 4(arctan(1/2)+arctan(1/3)) using complex arithmetic I am not sure how to do this. I know arctan(1/2)= arg(2+i) and arctan(1/3)=arg(3+i), but how do I go further. Any ideas?
Thanks

A: $\arctan(1/2) + \arctan(1/3) = \arg(2+i)+\arg(3+i) = \arg( (2+i)(3+i))$ $= \arg(5+5i) = \arg((1+i)/\sqrt{2}) = \arg(1^{1/8}) = 2\pi/8 + 2\pi k = \pi/4 + 2\pi k $ for $k\in\mathbb{Z}$.
A few facts about complex algebra (specifically the $\arg$ function) are used here to avoid trigonometry:
1) $\arctan(b/a) = \arg(a+ib)$
2) $\arg(z)+\arg(w) = \arg(zw)$
3) $\arg(\alpha z) = \arg(z)$ for $\alpha\in\mathbb{R_{>0}}$
4) $\arg(1^{1/n}) = 2\pi / n + 2\pi k$ for $n\in\mathbb{N}$ and $k\in\mathbb{Z}$, where $1^{1/n}$ is the principal $n$-th root of unity.
The fact that $\left[(1+i)/\sqrt{2}\right]^8 = 1$ and that it is in fact the principal root can be verified by the definition.

A: Hint:
$$(2+i)^4(3+i)=?$$
Now use the fact:
for $0<x<1,0<\arctan x<\arctan1=?$


text:
Q: Copying Result of Linq into DataTable What changes do i need to make so as to reduce of doing this task with fewer lines and better approach.
   DataTable dtStatusMsgs;
    var statusList = (
                    from items in dtInputTable.AsEnumerable()
                    where items.Field<int>("DepartmentId") == deptId
                    select new
                    {
                        statusId = items.Field<int>("StatusId"),
                        status = items.Field<string>("Status"),
                        statusOrder = items.Field<int>("StatusSortOrder"),
                        rowId = items.Field<int>("RowId")

                    }).Distinct();

    dtStatusMsgs = new DataTable();
    dtStatusMsgs.Columns.Add("StatusId", typeof(int));
    dtStatusMsgs.Columns.Add("Status", typeof(string));
    dtStatusMsgs.Columns.Add("StatusSortOrder", typeof(int));
    dtStatusMsgs.Columns.Add("RowId", typeof(int));

    foreach (var item in statusList)
        dtStatusMsgs.Rows.Add(item.statusId, item.status,item.statusOrder
                              , item.rowId);

I want it to be done something like this.
   DataTable dtStatusMsgs;
    var statusList = (
                    from items in dtInputTable.AsEnumerable()
                    where items.Field<int>("DepartmentId") == deptId
                    select new
                    {
                        statusId = items.Field<int>("StatusId"),
                        status = items.Field<string>("Status"),
                        statusOrder = items.Field<int>("StatusSortOrder"),
                        rowId = items.Field<int>("RowId")

                    }).Distinct();

dtStatusMsgs= statusList.CopyToDataTable<DataRow>();

And how to use Sum function on any of the column in this code.
I want to see a sample code on this for applying any aggregate function

A: dtStatusMsgs = new DataTable();
dtStatusMsgs.Columns.Add("StatusId", typeof(int));
dtStatusMsgs.Columns.Add("Status", typeof(string));
dtStatusMsgs.Columns.Add("StatusSortOrder", typeof(int));
dtStatusMsgs.Columns.Add("RowId", typeof(int));

statusList.ForEach(p => dtStatusMsgs.Rows.Add(p.StatusId, p.Status, p.StatusSortOrder,p.RowId));


text:
Q: SQLite : Return true if duplicate values are found in table I want to know how you can find duplicate values in a table and make it return True. I have seen alot of questions about this but none of them helped, Thanks!
Here's my example :
import hashlib
import sqlite3

con = sqlite3.connect('users/accounts.db')
cur = con.cursor()
info = cur.execute("SELECT * FROM accounts;").fetchall()

print("Sign Up.")
username = input("Input your username : ")
password = input("Input your password : ")
email = input("Input your email: ")

result = hashlib.sha256(password.encode("utf-8"))
result_2 = str(result.digest)

cur.execute("insert into accounts (username, password, email) values(?,?,?)", (username, result_2, email))

con.commit()
print(info)
con.close()

Disclaimer
To those wondering, No this will not be used in a production environment, It is unsafe and can be easily exploited. Haven't even salted the hashes.

A: If your goal be to prevent inserting a new user record with a username or email which already is being used by someone else, then an exists query provides one option:
INSERT INTO accounts (username, password, email)
SELECT ?, ?, ?
WHERE NOT EXISTS (SELECT 1 FROM accounts WHERE username = ? OR email = ?);

That is, in a single statement we also can check if the username or email provided already appears somewhere in the accounts table.
Updated Python code:
sql = """
    INSERT INTO accounts (username, password, email)
    SELECT ?, ?, ?
    WHERE NOT EXISTS (SELECT 1 FROM accounts WHERE username = ? OR email = ?)
"""
cur.execute(sql, (username, result_2, email, username, email))

A: Let's suppose you have this table:
create table foo (
   foo_id numeric(12,0) primary key,
   str_value varchar(200)
);

And you want to find duplicate values for str_value.
You could do:
select str_value
  from foo
 group by str_value
having count(1) > 1;

You will have a list of str_values with dups on it.
If you want to know how many duplicates there are for each str_value you could add count(1) to your select clause:
select str_value, count(1)
  from foo
 group by str_value
having count(1) > 1;

A: So this code worked
b = cur.execute("select * from accounts").fetchall()

sql = """INSERT INTO accounts (username, password, email)
         SELECT ?, ?, ?
         WHERE NOT EXISTS (SELECT 1 FROM accounts WHERE username = ? OR email = ?)"""
cur.execute(sql, (username, str(result.digest()), email, username, email))

a = cur.execute("select * from accounts").fetchall()

if a > b:
    print("Registration Complete.")
else:
    print("Failed : Username or Email already exists.")


text:
Q: Publish Android library with external dependencies I have an Android closed source module that will be be used as a library in other projects. It contains external dependencies.
To publish it, I'm creating a Maven artifact with the following gradle task:

apply plugin: 'maven'

def coreAarFile = file('...build\\outputs\\aar\\android-sdk-release.aar')

artifacts {
    archives coreAarFile
}

uploadArchives {
    repositories.mavenDeployer {
        repository(url: "file://.\\mvn-repo")
        pom.project {
            groupId 'a.blabla'
            artifactId 'blabla-sdk'
            version "1.0.0"
        }
    }
}

It generates the .aar file, the pom.xml, etc without problems.
Then I create a project that have a dependeny to my library declared. It works until it needs to access to the external dependencies, when throws a class not found exception.
How can I edit my gradle task to include external dependencies or at least a reference to them? They are published in mvnrepository.com and github.com.

A: I moved uploadArchives to the build.gradle of the module and removed the artifacts element. It works!
Thanks to CommonsWare for pointing to the right direction.


text:
Q: Check if a value among a list exist in multiple column R data.table Problem
I have a dataset with a lot of identical kind of variables which can contain the same values. I would like to check if among those variable, we can find at list one value among a list of values.
Example
Let say that we have a dataset with 3 variables of factor type DAS1, DAS2, DAS3.
The possible values for those variables are c("0", "1", "x", "y") (note that I'm not trying to differentiate numbers and letters. Consider every values as characters).
library(data.table)

start <- data.table::data.table(DAS1 = c("0","1","x","0","1","0","1"),
                       DAS2 = c("x","y","0","0","x","1","0"),
                       DAS3 = c("1","1","y","1","x","y","0"))

My objective is to find which row contain at least one observation of the values "x" or "y".
result <- data.table::data.table(DAS1 = c("0","1","x","0","1","0","1"),
                       DAS2 = c("x","y","0","0","x","1","0"),
                       DAS3 = c("1","1","y","1","x","y","0"),
                       xy = c(T,T,T,F,T,T,F))

Condition
I really want to do it with the data.table package and not dplyr because I mostly use data.table and I don't like to switch between the two packages if it's not necessary.
Answer by @lovalery
start[, xy := apply(start[,c("DAS1", "DAS2", "DAS3")],1, function(x) any(x %in% c("x", "y")))][]

A: You could do:
Reprex

*

*Code

library(data.table)

start[, xy := apply(start,1, function(x) any(x == "x" | x == "y"))][]

*

*Output

#>    DAS1 DAS2 DAS3    xy
#> 1:    0    x    1  TRUE
#> 2:    1    y    1  TRUE
#> 3:    x    0    y  TRUE
#> 4:    0    0    1 FALSE
#> 5:    1    x    x  TRUE
#> 6:    0    1    y  TRUE
#> 7:    1    0    0 FALSE

Created on 2022-03-04 by the reprex package (v2.0.1)

A: You can try this
> start[, xy := rowSums((.SD == "x") + (.SD == "y")) > 0][]
   DAS1 DAS2 DAS3    xy
1:    0    x    1  TRUE
2:    1    y    1  TRUE
3:    x    0    y  TRUE
4:    0    0    1 FALSE
5:    1    x    x  TRUE
6:    0    1    y  TRUE
7:    1    0    0 FALSE

or
> start[, xy := rowSums(Reduce(`+`, Map(`==`, c("x", "y"), list(.SD)))) > 0][]
   DAS1 DAS2 DAS3    xy
1:    0    x    1  TRUE
2:    1    y    1  TRUE
3:    x    0    y  TRUE
4:    0    0    1 FALSE
5:    1    x    x  TRUE
6:    0    1    y  TRUE
7:    1    0    0 FALSE


text:
Q: How to avoid code duplication inside two methods? I have two identical methods, but one of them have return statement inside try catch
public void A(Guid agentId)
{
     var agent = _agentsProvider.GetAgentById(agentId);
     var updateCompletionSource = C(agentId);
     try
     {
         var cacheEntry = UpdateAgentMetadataCacheEntry(agent, true, false);
         updateCompletionSource.SetResult(cacheEntry);
     }
     catch (Exception e)
     {
         updateCompletionSource.SetException(e);
     }
}

private Entry B(IAgent agent)
{
     var updateCompletionSource = C(agent.Id);
     try
     {
          var cacheEntry = UpdateAgentMetadataCacheEntry(agent, false, false);
          updateCompletionSource.SetResult(cacheEntry);
          return cacheEntry;
      }
      catch (Exception e)
      {
          updateCompletionSource.SetException(e);
          return GetPreviousCacheEntry();
      }
}

How to collect identical part and create new method with this part?

A: Unless GetPreviousCacheEntry could have problematic side-effects, it seems to me that you don't need method A at all.
Just call method B and ignore the return value if you're not interested in it.
As noted in comments, the methods aren't identical other than the return statements though - because they use a different second argument for UpdateAgentMetadataCacheEntry, and they have different parameters too (one has a Guid and one has an Agent). You could refactor this into:
private Entry B(IAgent agent, bool foo)
{
     var updateCompletionSource = C(agent.Id);
     try
     {
          var cacheEntry = UpdateAgentMetadataCacheEntry(agent, foo, false);
          updateCompletionSource.SetResult(cacheEntry);
          return cacheEntry;
      }
      catch (Exception e)
      {
          updateCompletionSource.SetException(e);
          return GetPreviousCacheEntry();
      }
}

... with a meaningful name for foo, obviously. I'll assume the difference in parameter type isn't a problem in reality.

A: Like Jon said, you don't need method A. Just add another parameter for boolean value.
public void A(Guid agentId)
{
    var agent = _agentsProvider.GetAgentById(agentId);
    AnotherA(agent, true);
}

private Entry B(IAgent agent)
{
    return AnotherA(agent, false);
}

private Entry AnotherA(IAgent agent, bool a)
{
    try
    {
         var cacheEntry = UpdateAgentMetadataCacheEntry(agent, a, false);
         updateCompletionSource.SetResult(cacheEntry);
         return cacheEntry;
    }
    catch (Exception e)
    {
        updateCompletionSource.SetException(e);
        return GetPreviousCacheEntry();
    }
}


text:
Q: Crossplatform framework is suitable to do all things in Mobile Application as Native? I am working in iPhone SDK.I have to convert from it to Crossplatform which may be either phonegap or titanium.As a iPhone Native application developer, I have some questions based on cross paltform.please consider the questions for other platforms android,etc also.I have already seen the stackoverflow Link.
1)Is it possible to get equal functionalities of all APIs which are in iPhone SDK through HTML5 and javascript?
2)If Apple releases New Version of iPhone SDK,will New APIs be included ASAP in Crossplatform?
3)If The App crashes in some situation, can I fix immediately through Device Debugging as we do in native Language?
4)The applications developed by Cross platform will be approved by Apple legaly?For example If i want to do live streaming in iphone , The restrictions have mentioned in Apple website.has it been followed by crossplatform?
5)will Application developed by cross platform  take more memory?I mention the size of device build for appstore?If we develop the same through objective C,will size be reduced?
***My Conclusion is When we want to develop simple Applications for Multiple devices,crossplatform is suitable.Am I right?***I hope doing through native language(iphonensdk, Android) will avoid lot of Unnecessary things.

A: *

*No.

*If the API can be made available, it depends on how fast the creators of the framework implement it.

*In principle, yes, as those frameworks employ a limited amount of OS capabilities to run web-technology (in most cases). This "wrapper" behaves as any native app does. For the content however the rules of the frameworks development language apply. It may be harder compared to native development to track down errors, since they must "pass the shell". Html errors for example may produce the same error for their enclosing webview again and again, despite being different in origin.

*Propably.

*That's hard to tell. It may depend on the framework. I wouldn't worry about the code as other ressources like imagery are usually the heavier load. But it may be very well the case that those frameworks bring along imagery necessary for their UI elements, since they do not rely on OS elements entirely. Compared to a native app which comes with no extra ressources at all, a crossplatform app with the same functionality might take more memory.

As to your conclusion: You're right. However I'd still encourage anyone to develop native applications whenever possible. Crossplatform frameworks tend to be slower at runtime and, in some cases, produce very ugly apps. I know several examples of apps which have been created with a variety of crossplatforms and I don't like any of them. They just don't feel right. Partly that's due to their UI elements which don't look and feel as you'd expect it on the platform you're on.
The principle behind crossplatform frameworks may appear to be logical, tempting and in some cases, straight economics mandate their use. But, for the time being, I find the results far from being satisfactory and for that reason would never touch a crossplatform framework.

A: In my experience (with a closed, private, expensive x-platform thing purchased by the employer), it was utterly frustrating, and incredibly difficult. Therefore, it is my preference to maintain multiple native apps.
The UI considerations that can be made/handled by the native app, as well as the functionality and speed gained by doing it natively, IMHO, far outweigh the benefit of having to write it 2 or 3 times.
In an ideal world, you would have a specialist for each platform that can lead the team on the "deep" things, and then everyone can generalize for all of the platforms, increasing their depth through the course of the project.


text:
Q: Transfer a label result across segue I am working on a BMI calculator as part of a wider app.
The idea is that the user calculates the BMI then goes to another screen where they find the BMI chart to compare their result.
The idea I have is that the calculated BMI result on the BMI screen is also displayed on the chart screen as a reminder of the score.
I have been attempting to transfer the calculated score (displayed on the calculation screen as a UILabel) across a segue and display it in another UILabel at the top of the screen.
I have been attempting to use the "prepare(for segue)" and "performSegue" commands but can't seem to get the data to transfer across.
I am very new to coding and no doubt I am doing something stupid, but if anyone can help me figure this out, I would be really grateful.
I have linked the screen via the "Active Segue" and have identified the Segue as "bmiSeg. The calculation view controller is named "BMICalc" and the chart view controller named "BMI_Result"
The UILabel on BMICalc is labelled bmiScoreLabel with a var called bmiResult used to collect the score.
The UILabel on BMI_Result is labelled bmiResultLabel with a var called bmiScore.
The goBMIButton takes the user to the chart screen.
Hope all that makes sense!
My current coding for the transfer is as follows:
@IBAction func goBMIButton(_ sender: UIButton) {
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(.success)

        performSegue(withIdentifier: "bmiSeg", sender: self)

    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "bmiSeg" {
            let destinationVC = segue.destination as? BMI_Result
            destinationVC?.bmiScore = Int(bmiResult)
        }
    }

On the second screen the target is simply the UILabel:
I have asked the data transfer to go into var bmiScore and then from there into the UILabel as follows:
bmiResultLabel.text = " (bmiScore)"
Hopefully that description of my thinking isn't too confusing and my apologies if it is!
Thanks everyone!!

A: On the second screen
var bmiScore:Int? {
  didSet {
     bmiResultLabel.text = "\(bmiScore)"
  }
}

DidSet is here to set the title of label whenever the bmiscore interrupted or get new value