text:
Q: base64string to string back to base64string I am trying an experiment to convert a base64string to a string then back to a base64string, however, I am not getting my original base64string:
String profilepic = "/9j/4AAQ";

string Orig = System.Text.Encoding.Unicode.GetString(Convert.FromBase64String(profilepic));

string New = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(Orig));

The string New returns "/f//4AAQ".
Any thoughts of why this is happening?

A: You are doing it wrong. You should do it as below:
namespace ConsoleApplication1
{
    using System;
    using System.Text;

    class Program
    {
        static void Main(string[] args)
        {
            string profilepic = "/9j/4AAQ";
            string New = Convert.ToBase64String(Encoding.Unicode.GetBytes(profilepic));
            byte[] raw = Convert.FromBase64String(New); // unpack the base-64 to a blob
            string s = Encoding.Unicode.GetString(raw); // outputs /9j/4AAQ
            Console.ReadKey();
        }
    }
}

A: You're assuming that the base64-encoded binary data in your example contains a UTF-16 encoded message. This may simply not be the case, and the System.Text.Encoding.Unicode class may alter the contents by discarding the bytes that it doesn't understand.
Therefore, the result of base64-encoding the UTF-16 encoded byte stream of the returned string may not yield the same output.
Your input string contains the binary sequence 0xff 0xd8 0xff 0xe0 0x00 0x10 (in hex). Interpreting this as UTF-16LE (which you're using with System.Text.Encoding.Unicode) the first character would be 0xffd8, but is placed in the string as 0xfffd, which explains the change.
I tried decoding it with Encoding.Unicode, Encoding.UTF8 and Encoding.Default, but none of them yielded anything intelligible.


text:
Q: Magnetic field of radially emitted alpha particles by a sphere of polonium A layer of polonium is deposited on the surface of a sphere of radius $R$. The metal emits alpha particles. Assume that these particles are emitted radially outward ($\vec e_r$), thus forming a current $\vec J(\vec r)=J(r)\vec e_r$. Will there be a magnetic field associated with this current?

A: The Maxwell way
First I assume that the current is homogeneous. In that case the important point to realise is that if current goes away, the sphere becomes charged. If the total current going away is $J$ and the process starts $t=0$ then the charge on the sphere is $q=-J t$.
Maxwell tells us
$$ \vec \nabla \times \vec B= \mu_0 \vec j +\mu_0 \varepsilon_0 \partial_t \vec E $$
As
$$\partial_t \vec E= \frac{1}{4 \pi \varepsilon_0} \partial_t \frac {-J t}{r^2}\frac{\vec r}{r}= -\frac{1}{4 \pi \varepsilon_0} \frac {J}{r^2}\frac{\vec r}{r}$$
and
$$\vec j= \frac{J}{4 \pi r^2} \frac{\vec r}{r}$$
the radial current density you finally get
$$ \vec \nabla \times \vec B= \mu_0 \frac{J}{4 \pi r^2} \frac{\vec r}{r} -\mu_0 \varepsilon_0 \frac{1}{4 \pi \varepsilon_0} \frac {J}{r^3}\vec r =0$$
So in the perfect case the answer is no, but you have to consider the accumulating charge on the sphere as well. On the other hand, decay is a statistical process such that there will be fluctuations in current density over time and solid angle. These fluctuations will results in some magnetic fields, but much smaller than what you would expect from a current $\vec J$.
The symmetry way
As the current is radial the whole system is fully rotational symmetric. As a consequence there is no specific direction in which the magnetic field could point other than in or out. If that would be the case, we would have created a magnetic monopole, which does not exist. The magnetic field, hence must be zero.
A little bit of both
If it was only about the current and we forget about the changing electric field we get something like
$$ \vec \nabla \times \vec B= \mu_0 \vec j$$
Symmetry requires the the current density is of the form (we know how it looks, but the general case is enough) $\mu_0 \vec j(\vec r)=\vec r f(r)/r$. We than can immediately say that there is an $F(r)$ with $\partial_\xi F'(\xi)=f(\xi)$ such that
$$\vec \nabla\cdot F(r)= \frac{\vec r}{r}f(r)$$
The current is a gradient field of a potential and an according source.
So the Maxwell equation without the electric field would require something like
$$ \vec \nabla \times \vec B= \vec \nabla\cdot F(r)$$
i.e.
$$ \vec \nabla\cdot (\vec \nabla \times \vec B)= \Delta F(r)$$
The lef hand side is zero, while we know that there is a source on the right, which is a contradiction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using foreach to categorize data I would like to know if it is possible to categorize data in groups when echoing it .
For example if I have a table of different phones and separate them by brand, i.e. Apple, Samsung etc, and I want the data to be displayed with a header of the brand of phone and under would have the phone type.
Apple
iphone 4
iphone 4s
iphone 5
Samsung
Galaxy Note 2
Galaxy S4

                <?php echo phones['brand']; ?>
                Price

            <?php foreach($phones as $phone): ?>

                    <?php echo $phone['name']); ?>

<?php echo $phone['price']); ?>

                    $<?php echo $phone['released']); ?>

            <?php endforeach; ?>

This is what I have so far, sorry for the wait.

A: Here's a really basic example. Assuming you have your phones in an array like this:
$phones = [
    ['Apple',  'iphone 4'],
    ['Apple','iphone 4s'],
    ['Apple','iphone 5'],
    ['Samsung','Galaxy Note 2'],
    ['Samsung','Galaxy S4']
];

You just keep track of the brand as you output them, and whenever the brand is different from the previous brand, output a header for it.
$previous_brand = null;
foreach ($phones as $phone) {
    list($brand, $model) = $phone;
    if ($brand != $previous_brand) {  // check if current brand is different than previous
        echo "
$brand
";
    }
    echo "$model
";
    $previous_brand = $brand;     // current brand becomes previous brand for next iteration
}

I kept the HTML minimal so it wouldn't be distracting from the working part. Obviously you can add whatever markup you need.
The important thing with this approach is that it totally depends on your array being sorted by brand, so if this is coming out of your database ORDER BY brand, or if it's some other source, use one of the various PHP sort functions to get it in that order first.

A: First do
$phonesByBrand = [];

foreach ($phones as $phone)
{
  $phonesByBrand[$phone['brand']][] = $phone;
}

Now in your view, you can do
<?php foreach($phonesByBrand as $brand => $phones): ?>

          <?php echo $brand; ?>
          Price

        <?php foreach($phones as $phone): ?>

              <?php echo $phone['name']); ?>

<?php echo $phone['price']); ?>

              $<?php echo $phone['released']); ?>

        <?php endforeach; ?>

<?php endforeach; ?>


text:
Q: Unpredictable behavior of Action invocation in Caliburn Micro I develop app for Windows Phone 7 with using of Caliburn Micro.
Hear is a code of app's main parts.
Part of MainView:
<Grid x:Name="LayoutRoot" Background="Transparent">
    <controls:Panorama>
        <controls:PanoramaItem x:Name="SubPanoramaItem"
                               DataContext="{Binding SubViewModel}">
            <StackPanel>

                <toolkit:ListPicker ExpansionMode="FullScreenOnly"
                                    ItemsSource="{Binding DataModeList}">

                    <toolkit:ListPicker.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Tag}" />
                        </DataTemplate>
                    </toolkit:ListPicker.ItemTemplate>

                    <toolkit:ListPicker.FullModeItemTemplate>
                        <DataTemplate>

                            <StackPanel x:Name="item"
                                        Margin="5, 24, 0, 24"
                                        cal:Action.TargetWithoutContext="{Binding ElementName=SubPanoramaItem,
                                                                                Path=DataContext}"
                                        cal:Message.Attach="[Event Tap] = [Action Tap($dataContext)]"
                                        Orientation="Horizontal">

                                <TextBlock FontSize="40"
                                           Text="{Binding PopupText}" />
                            </StackPanel>

                        </DataTemplate>
                    </toolkit:ListPicker.FullModeItemTemplate>

                </toolkit:ListPicker>

            </StackPanel>
        </controls:PanoramaItem>

        <!-- Some other code -->
    </controls:Panorama>
</Grid>

MainViewModel:
public class MainViewModel: Screen
{
    public SubViewModel SubViewModel { get; private set; }

    public MainViewModel(SubViewModel subViewModel)
    {
        SubViewModel = subViewModel;
    }

    // some other code
}

SubViewModel:
public class SearchViewModel : Screen
{
    private ObservableCollection<DateModeItem> _dataModeList =
        new ObservableCollection<DateModeItem>()
            {
                new DataItem
                { PopupText = "Item 1" },
                new DataItem
                { PopupText = "Item 2" },
                new DataItem
                { PopupText = "Item 3" },
                new DataItem
                { PopupText = "Item 4" }
            };

    public ObservableCollection<DateModeItem> DataModeList
    {
        get
        {
            return _dataModeList;
        }

        private set { _dataModeList = value; }
    }

    public void Tap(object dataContext)
    {
        var item = dataContext as DataItem;
        if (item != null)
        {
            var r = new Random();
            switch (item.PopupText)
            {
                case "Item 1":
                    item.Tag = r.Next(5);
                    break;
                case "Item 2":
                    item.Tag = r.Next(5, 10);
                    break;
                case "Item 3":
                    item.Tag = r.Next(10, 15);
                    break;
                case "Item 4":
                    item.Tag = r.Next(15, 20);
                    break;
            }
        }
    }
}

DataItem:
public class DataItem
{
    public string PopupText { get; set; }
    public int Tag { get; set; }
}

As you can see I've attached Action to each StackPanel of DataTemplate in ListPicker. When tap occurs on the item in the list then new random tag must be generated. This tag is inserted into ListPicker's textbox.
And this actions behave very strangely. When I tap on 1, 2 and 4 item, nothing happens at all. When I tap 3 item the app throws exception - "No target found for method Tap". And this what happens when I'm using ListPicker from Silverlight Toolkit.
I've also triend RadListPicker from Telerik's RadConrols library. When I've used it, invocation of action method was unpredictable. Sometimes action invokes method correct. Sometimes nothing happen at all. One I can say surely - with tap on the last item it works less often in the correct way.
What is going on? I can't understand.
Additional info:
I've made a cleaning of all unnecessary stuff from my app and left only code that I described above in the previous post.
Now when I'm using ListPicker - nothing happens at all. List doesn't responds on taps. Sometimes app throws "No target found for method Tap" exception. When I'm using RadListPicker - almost always action not invoked and sometimes (very rarely) invoked correctly.

A: When you are working with ListPicker you need to add some ElementConventions in Order to bind the Actions of your View to your ViewModel.
Adding a binding convention can be done in the AppBootstrapper class. The code could look something like:
    protected override void Configure()
    {
      ConventionManager.AddElementConvention<ListPicker>(ListPicker.ItemsSourceProperty, "SelectedItem", "SelectionChanged").ApplyBinding =
        (viewModelType, path, property, element, convention) => {
         if (ConventionManager.GetElementConvention(typeof(ItemsControl)).ApplyBinding(viewModelType, path, property, element, convention))
         {
             ConventionManager.ConfigureSelectedItem(element, ListPicker.SelectedItemProperty, viewModelType, path);
             return true;
         }
         return false;
     }; }


text:
Q: How do i know when my app is going to kill I am working on Gps based application which runs all the time in background. But in extreme low memory case(or when i open many apps) my app is killed by the android system.
I want to relaunch my app when it is killed by android system.I google it for this but don't get any solution.Any help would be appreciated.
Thanks

A: Have you done your GPS logic inside a service? The service is one of the last things that will be killed and mostly because it has to be killed to free needed memory.
Maybe your service should create a notification so the user is informed and can restart the app by hand by clicking the notification...

A: Have you looked at this Activity Lifecycle flowchart? In the case where other applications need memory, onPause() is the last guaranteed thing that happens before your app is stopped or killed. So that is where you would need a notification (as @WarrenFaith says) or another mechanism which could potentially revive your app or at least ping the user to revive it.

A: I think [startForeground()][1] is what you are looking for. Android won't kill your service, so you don't have to worry about restarting it.
Good luck
Tom
[1]: http://developer.android.com/reference/android/app/Service.html#startForeground(int, android.app.Notification)

A: You could try launching a new instance of the app when the onDestroy() function is called. For example:
@Override
public void onDestroy() {
    Intent intent = new Intent(Thisclass.this, Thisclass.class);
    Thisclass.this.startActivity(intent);
    super.onDestroy();
}

A: Maybe you can make use of intents, send a token out to another listener when this application is being killed by android, so that the other serivce can initiate this activity.
Though I cannot see how this will not be a loop. The way you end your app is very similar to the way android ends your app! so I am pretty sure it will be looping infinitely when you try to end the app, behaving very much like a malware!


text:
Q: How can I use laravel 5.1 middleware parameter for multiple auth and protected routes? I'm new to laravel 5.1.
How can I use middleware parameter to protect my admin routes from users ?
something like this:
Route::group(['middleware' => 'auth:admin'], function()
/* Admin only Routes*/
{
   //////
});

I have a field "role" in my "users" table that get two values:

*

*1 for admin

*2 for users

In my application, users, have their protected route.
I don't want to use packages.

A: You can do something like this. Inject the Guard class, then use it to check the user. You dont need to pass the parameter really. Just name your middleware 'admin' or something. The following middleware will check if the current user's role is admin, and if not, redirect to another route. You can do whatever you prefer on failure.
<?php

namespace Portal\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Admin
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($this->auth->user()->role != 'admin') {
            return redirect()->route('not-an-admin');
        }
        return $next($request);
    }
}

In case you do want to pass the parameter, you can do this:
    public function handle($request, Closure $next, $role)
    {
        if($this->auth->user()->role != $role) {
            return redirect()->route('roles-dont-match');
        }
        return $next($request);
    }


text:
Q: Как заставить ботов Яндекса парсить spa на React.js Есть сайт написанный на React.js, весь рендеринг происходит на клиенте.
Серверная часть написана на Koa.js.
Как я понял, яндекс не индексирует spa приложения, судя из статей в интернете наиболее простой способ - это настроить перерендер страниц.
Но я так до конца четко не смог осознать принцип работы перерендера и как его вообще нужно настраивать.
Помогите пожалуйста


text:
Q: PHP Adding 2 decimal points numbers (money) gives wrong results in total amount I have an customer invoice table in my MySQL database with a DECIMAL(10,2) field called price.
When fetching these values in php and calculating a sum amount,
ex: in the script
$totalAmount = 0; // initialised them to

   while(records){

       $amount = $inv_amount - ($pay_amount + $onamount); //float i guess. 2.22, 14.22
       $totalAmount = $totalAmount + $amount; //float i guess. 2.22, 14.22 ..etc

    }

when echo $totalAmount; it has a slight error in the final amount 0.01 however when dealing which large datasets around 20,000 this error becomes very considerable such as 200+
what is the safest way to do this when dealing with prices and such with these numbers in PHP? Or will I end up with potential rounding errors and things like that which are common when working with floating point data types?
is using
round
number_format

is the most suitable solution for this type of a financial application ?

A: Try this:
$totalAmount = number_format($totalAmount, 2, '.', '');

A: If you need accuracy of 2 decimal points:

*

*multiply value by 100

*do your operations

*divide by 100 and use number_format where appropriate

A: Indeed, floating point numbers are not precise.
Either calculate in cent (multiply by 100 and calculate in integers), or calculate in strings using BC Math.

A: have you tried to
round(totalAmount, 2, PHP_ROUND_HALF_ODD);

it should see last decimal number - if it's odd - rounds down, if even - up

A: Well, to begin with, why sum in a php loop when you can do that in mysql? Moreover, just use integer multiplied by 100 and then divide by 100 once you need the final result.

A: I recommend doing calculations on SQL Level with queries or views.
Firstly, using 64 bit integers on PHP is risky because; on overflow, it switches to float and you lose precision. When it's money, the problem is more serious. You should acually calculate a column with sql and just get the value from there. Money is a long type and it will often convert to float on php and your people will lose or win some cents depending on the mood of php engine. You can't work with decimal type on php, even if you multiply by 100 and keep it as an integer, long numbers with overflow will be converted to float automatically. Calculate your values on MYSQL if you want to use decimal numbers or convert your field into int.
If your server has an 32 bit cpu, the WORD length is 32 bit so integers in php engine are 32 bit integers. This makes the likelihood of overflow higher. On an 64 bit system, you can work more comfortably.
Using a round function on a money value is ridiculous and unprofessional in this case. Don't do it.
Reading this document will help you a lot.
php documentation of integers says

Integer overflow
If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

Calculation on SQL level will ensure precision for money type. Getting the money type to php will result in a float value, and you can multiply it by 100 and divide by 100 later BUT it increases the rish of overflow again because php will use an 32 bit float number for storage. If you are using 32 bit float why is the data field decimal? So it's inconsistent if you do that. an 32 bit number i already not so big, and an 32 bit float loses some of its capacity on  floating point, so it's more likely to reach over capacity when you multiply by 100.
USE SQL

A: You could use number_format
Ex:(for two decimal points)
$number = 12345.5667;
echo $result = number_format($number, 2);

Or you could use round function in MySql:
ROUND(number,2)


text:
Q: Create new repo from Github template I have created a repo designated as a template on Github that I'm trying to use as the basis for a new project so that I can reduce initial project startup time for projects with the same functionality.
Every time I clone that template to my local machine under a new project name, it is still associated with that original template and any commits will go there.
I've tried different variations of clone, meteor-boilerplate is what I'm trying to use as to begin an application called notes.
git clone https://github.com/ajsingh4/meteor-boilerplate.git notes
Would appreciate any advice as to how I can use that template as the basis for a new project in a separate repository.

A: If you have created a GitHub template repository, then you don't clone it directly.
You create a new one from template, directly on the GitHub site.
Then you clone that new repository: you won't have to change its remote URL, it will already be the correct one.

A: Solved this via
1) Creating a new repo on Github using the template
2) Clone new repo locally
3) Change the remote URL to the new repo


text:
Q: newrelic-1.10.2.38/newrelic/api/web_transaction.py self.generator.close() kicking up IOError Using uwsgi 1.4.2 (gevent = 100) with newrelic, I am encountering repeated errors
[pid: 24340|app: 0|req: 1335/4305] 199.27.128.147 () {54 vars in 722 bytes} [Fri Mar 22 16:49:41 2013] HEAD / => generated 0 bytes in 158 msecs (HTTP/1.1 200) 5 headers in 269 bytes (4 switches on core 99)
IOError: write error
Traceback (most recent call last):
  File "/home/web/.virtualenvs/myproject/lib/python2.7/site-packages/newrelic-1.10.2.38/newrelic/api/web_transaction.py", line 539, in close
    self.generator.close()
  File "/home/web/.virtualenvs/myproject/src/django/django/http/response.py", line 227, in close
    for closable in self._closable_objects:
IOError: write error
Exception AssertionError: AssertionError() in <generator object __iter__ at 0x4ed2e10> ignored

Where can I fix this problem?

A: Solved by use of uwsgi 1.9 which handles gevent properly.


text:
Q: Does adding a "." to a name make it unreconizable? I want to hide some files because they just add clutter to my home folder.  I have a folder in there that is called "bin" and is for running startup scripts.  I want to have this folder and I'm not sure if adding a . before it will make the scripts not start.

A: If you add a . , you are changing the name of your ~/bin so it will no longer be in the path. Scripts may or may not work depending on how you call them, and since it isn't in your path anymore, you cannot just type scriptname.sh and expect it to work. You can do it if you change your path to include /home/myusername/.bin

A: Add (or edit) this to ~/.bashrc
if [ -d $HOME/.bin ]; then
PATH=$PATH:$HOME/.bin
fi

A: As a convention, filenames beginning with a dot are hidden in many, but not all, contexts.  This is done exactly for the same purpose you want - to hide away clutter that isn't intended to be normally viewed or edited by users.
However, adding a dot to the start of a filename (or directory) changes the filename.  It's not like Windows where the filesystem has a built-in "hidden" flag; on Linux adding the dot is actually modifying the filename.  Any existing links you had to that filename, or directory, will be broken.  If you refer to the directory in a configuration script somewhere, that script will need to be modified.  If an application is hard-coded to refer to that directory, it won't find it.  If the directory is in your PATH, the new directory won't be unless you add it in again.

A: create a text files, write bin inside it, and name it .hidden
your bin file path wont change but it is hidden in file manager


text:
Q: Ensemble average and law of large numbers In order to calculate the average of a macroscopic quantity such as energy, we need to average over all microstates of the system:
$$\langle E \rangle = \sum_{i=1}^n p_i E_i$$
where $n$ is the number of microstates. Each microstate has a probability associated with it, that is we have a probability distribution over microstates.
Law of large numbers states that as an experiment is repeated over and over, the empirical probability of the outcome approaches the theoretical (actual) probability of the outcome. In other words as we repeat the experiment over and over, the obtained distribution approaches the actual distribution.
Given that microstates change very rapidly, if we record all the microstates that appear in a sufficient long time interval (say $10$ seconds), should the distribution look like the actual one?


text:
Q: Recursively call an ajax function until the first ajax function is completed I have a python file which appends a result into log file and I need to print this log synchronously in UI.
Following is my code
var flag = 0;
function write_log_in_file(){
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "http://localhost/build5/builds/test.py",
    "method": "POST",
    "headers": {
      "cache-control": "no-cache"
    }
  }
  $.ajax(settings).done(function (response) {
    flag =1;
    console.log(response);
  });
};

function get_log_from_file(){
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "http://localhost/build5/builds/build.log",
    "method": "GET",
    "headers": {
      "cache-control": "no-cache"
    }
  }
  $.ajax(settings).done(function (response) {
    console.log(response);
  });
};

//Write build log in build.log file
write_log_in_file();

//Get log until python call is completed
while(!flag){
  get_log_from_file();
}

Here, I have used flag variable, which is set to 1 after my first ajax call is completed. Until then my second ajax call is being called recursively.
Since I have used while, flag variable never becomes 1 and while goes in infinite loop.
Is there any other method, where I can recursively call my ajax function, while other ajax function is completed?

A: $.ajax returns a promise you could chain.
function write_log_in_file(){
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "http://localhost/build5/builds/test.py",
    "method": "POST",
    "headers": {
      "cache-control": "no-cache"
    }
  }
  return $.ajax(settings) // return a promise
};

function get_log_from_file(){
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "http://localhost/build5/builds/build.log",
    "method": "GET",
    "headers": {
      "cache-control": "no-cache"
    }
  }
  return $.ajax(settings) // return a promise
};

//Write build log in build.log file
write_log_in_file()
  .then(function(result) {
    console.log(result) // log write result

    return get_log_from_file() // launch read
  })
  .then(function(result) {
    console.log(result) // log read result
  })
  .catch(function(error) {
    console.error(error);
  });

A: Yury's answer is fine approach to using promises (you should look into it)
But the problem with your code is that there is no documented .done method in JQuery's ajax. You must use .success.
  $.ajax(settings)
  .success(function (response) {
    flag = 1;
    console.log(response);
  })
  .error(function(err) {
    flag = -1; // End your while loop?
  });


text:
Q: how to store back the cropped image in folder php? I have the following code to move file to folder and then with that path I am cropping the image on submitting the form.
<?php
if(isset($_POST['submit']))
{
    header('Content-type: image/jpeg');
    move_uploaded_file($_FILES['image_file'] \
    ['tmp_name'],'media/'.$_FILES['image_file']['name']);
    $path='media/'.$_FILES['image_file']['name'];
    $maxsize=200;
    $sourcefile=$path;
    $imgcomp=0;
    $g_imgcomp=100-$imgcomp;
    if(file_exists($sourcefile))
    {
        $g_is=getimagesize($sourcefile);
        if($g_is[0] <= $maxsize && $g_is[1] <= $maxsize)
        {
            $new_width=$g_is[0];
            $new_height=$g_is[1];
        }
        else
        {
            $w_adjust = ($maxsize / $g_is[0]);
            $h_adjust = ($maxsize / $g_is[1]);
            if($w_adjust <= $h_adjust)
            {
                $new_width=($g_is[0]*$w_adjust);
                $new_height=($g_is[1]*$w_adjust);
            }
            else
            {
            $new_width=($g_is[0]*$h_adjust);
            $new_height=($g_is[1]*$h_adjust);
            }
        }
        $image_type = strtolower(strrchr($sourcefile, "."));
        switch($image_type)
        {
          case '.jpg':
             $img_src = imagecreatefromjpeg($sourcefile);
             break;
          case '.jpeg':
             $img_src = imagecreatefromjpeg($sourcefile);
             break;
          case '.png':
             $img_src = imagecreatefrompng($sourcefile);
             break;
          case '.gif':
             $img_src = imagecreatefromgif($sourcefile);
             break;
          default:
             echo("Error Invalid Image Type");
             die;
             break;
        }
        $img_dst=imagecreatetruecolor($new_width,$new_height);
        imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $new_width,
        $new_height, $g_is[0], $g_is[1]);
        imagejpeg($img_dst);
        imagedestroy($img_dst);
         $src_img = $image_create($sourcefile);
         rename('$src_img', 'media1/$src_img');
         ?>
         <img src="$src_img">// image is desplaying
    <?php }
    else
    {
        return false;
    }
}
?>

Now how can I save the cropped image back to the folder(new/old) and save the path in data base?

A: For saving an image to a file in php, you can use the imagejpeg() function, with the filename(=path) as second parameter. Similar for imagepng() and imagegif().
imagejpeg($img_dist,"some_file.jpeg")

If you want to store something in a database, that depends on the database. E.g. if you use some form of SQL, then the http://www.w3schools.com/sql/sql_insert.asp would be needed.

A: finally i got the answer here//upload img first
move_uploaded_file($_FILES['file2']['tmp_name'],
'upimg/'.$_FILES['file2']['name']);
$add='upimg/'.$_FILES['file2']['name'];
//Start the thumbnail generation
$n_width=200;          // Fix the width of the thumb nail images
$n_height=200;         // Fix the height of the thumb nail imaage
////////////////////////////////////////////
$tsrc="thimg/".$_FILES['file2']['name'];
// Path where thumb nail image will be stored
if (@$_FILES['file2']['type']=="image/gif")
{
$im=ImageCreateFromGIF($add);
$width=ImageSx($im);              // Original picture width is stored
$height=ImageSy($im);                  // Original picture height is stored
$n_height=($n_width/$width) * $height;
// Add this line to maintain aspect ratio
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
if (function_exists("imagegif"))
{
    Header("Content-type: image/gif");
    ImageGIF($newimage,$tsrc);
}
elseif (function_exists("imagejpeg"))
{
    Header("Content-type: image/jpeg");
    ImageJPEG($newimage,$tsrc);
}
    chmod("$tsrc",0777);
}

Same code for JPEG/PNG


text:
Q: Examples of Kuratowski closure axioms translation into the language of interior operators? I read here

The abstract theory of closure operators and the Kuratowski closure axioms can be easily translated into the language of interior operators, by replacing sets with their complements.

I wish to see some examples.
Ok, I understand that
${\bar {S}}=X\backslash (X\backslash S)^{\circ }$
where X is the topological space containing S, and the backslash refers to the set-theoretic difference.but this 'conversion' does not tell me much. For example, why use the interior operator theory rather than Kuratowski closure axioms ?What do you gain?

A: The axioms for an interior operator $f$ on the family of subsets of $X$, are the dual ones to the closure axioms, so we have $f: \mathscr{P}(X) \to \mathscr{P}(X)$ with:

*

*$f(X)=X$.

*$\forall A \subseteq X: f(f(A))=f(A)$.

*$\forall A,B \subseteq X: f(A \cap B)=f(A) \cap f(B)$.

*$\forall A \subseteq X: f(A) \subseteq A$.

and such an $f$ is called an interior operator. There is no real advantage to using this vs using a closure operator. Here also, the translation is simple: for such an $f$, setting $c(A)=X\setminus f(X\setminus A)$ means that $c$ is a closure operator. Having one (an interior operator) means having the other (a closure operator) too, and vice versa. In practice there is more theory on closure (like) spaces, this has grown historically, and so the closure approach is most often seen in books. This is mostly a matter of choice and tradition.


text:
Q: EditText soft numeric keyboard sometimes does not allow digits The following code produces an EditText (target version 23). I've been working on this for about 8 hours, and have received some suggestions, but I don't think anyone has ever seen this before, so I remain stuck.

*

*Click on the field.

*The A/N soft keyboard opens up.

*Click the 123? button at bottom left.  The numeric soft keyboard opens up.

*Press any digit.  Nothing happens.

*Long press 5, "5/8" gets added into the text field.

*Press any special character, such as @.  It might add to the field.

*Clear the field.  Type "for", press 123?, now it will take digits.

*Clear the field.  Type "for?", press 123?, it will not take digits.

I added a TextWatcher.  If the digits didn't post, the TextWatcher didn't see them either.
EditText bottomT = new EditText(model);
bottomT.setTextSize(14);
bottomT.setHint("ZIP");
bottomT.setHintTextColor(Color.BLACK);
bottomT.setBackgroundColor(Color.WHITE);
bottomT.setTextColor(Color.BLACK);
// bottomT.setInputType(InputType.TYPE_CLASS_NUMBER)  Didn't make any difference.
// bottomT.setRawInputType(InputType.TYPE_CLASS_NUMBER)  Didn't make any difference.
// bottomT.setText("", TextView.BufferType.EDITABLE);  DIdn't make a difference
bottomT.setText("");

A: EditText is misbehaving because in my custom ViewGroup I had
 protected void onLayout(boolean changed, int l, int t, int r, int b)
{
....
     child.layout(child.getLeft(), child.getTop(),
                    child.getLeft() + child.getMeasuredWidth(),
                    child.getTop() + child.getMeasuredHeight());

     child.setRight(somevalue);   // CAUSES EDITTEXT PROBLEMS
     child.setBottom(somevalue);  // CAUSES EDITTEXT PROBLEMS

It's clear now that I can't setRight() and setBottom(), but it's also clear that EditText should not get weird.
Ignore the backspace key.
Randomly ignore numeric keys, but accept the decimal point.
Ignore the newLine(Enter) key
Which keys are ignored, or not, depends on the device.  Samsung Tab 4 or the Nexus 5 API 23 X86 emulator are good places to see this.

A: You have to add this line in your java code.
bottomT.setInputType(EditorInfo.TYPE_CLASS_NUMBER);

A: Try this line of code .
bottomT.setInputType(InputType.TYPE_CLASS_NUMBER |InputType.TYPE_NUMBER_FLAG_DECIMAL);


text:
Q: Decreasing computation time for numerical plot My code is as follows:
M = 1.876;
m = 0.9389;
q = Sqrt[Q2 + ν^2];
E3[p3_] := Sqrt[p3^2 + m^2]
E4[p3_] := Sqrt[p3^2 + q^2 - 2*p3*q*Cos[θ] + m^2]
p3zero1 := p3 /.FullSimplify[Solve[M + ν - E3[p3] - E4[p3] == 0, p3]][[1]]
p3zero2 := p3 /.FullSimplify[Solve[M + ν - E3[p3] - E4[p3] == 0, p3]][[2]]
f[p3_] := M + ν - E3[p3] - E4[p3]
h[p3_] :=
  Abs[-(p3/Sqrt[m^2 + p3^2]) -
    (2 p3 - 2 Sqrt[Q2 + ν^2] Cos[θ]) /
      (2 Sqrt[m^2 + p3^2 + Q2 + ν^2 -2 p3 Sqrt[Q2 + ν^2] Cos[θ]])]
AngularIntegrand[p1_, p2_] :=
  Piecewise[{
    {p1^2/(M^2 (M - 2*E3[p1])^2) 1/(E3[p1] E4[p1])
       HeavisideTheta[p3zero1]/h[p3zero1] +
     p2^2/(M^2 (M - 2*E3[p2])^2) 1/(E3[p2] E4[p2])
       HeavisideTheta[p3zero2]/h[p3zero2],
    Im[p3zero1] == 0 && Im[p3zero2] == 0},
    {0, Im[p3zero1] != 0 || Im[p3zero2] != 0 }}]
Plot3D[
  NIntegrate[AngularIntegrand[p3zero1, p3zero2]*Sin[θ], {θ, 0, π}],
  {ν, 0, 3}, {Q2, 0, 6}]

The computation time on my laptop is approximately 4 hours, but I was hoping to decrease this to less than an hour.

A: I am able to gain ~25% speedup compared to the method suggested by @BobHanlon by slightly modifying two things

*

*make AngularIntegrand remember its values (see point 5 of this tutorial) so that they are not unnecessarily recomputed for same input values

*Pass the option Method->{Automatic,"SymbolicProcessing->0} to the NIntegrate in Plot3D to prevent it from preprocess the integrand symbolically

That is, the last part of the code now looks like this:
AngularIntegrand[p1_?NumericQ, p2_?NumericQ] :=
  AngularIntegrand[p1, p2] =
   Piecewise[{{p1^2/(M^2 (M - 2*E3[p1])^2) 1/(E3[p1] E4[p1])HeavisideTheta[p3zero1]/h[p3zero1] + p2^2/(M^2 (M - 2*E3[p2])^2) 1/(E3[p2] E4[p2]) HeavisideTheta[
      p3zero2]/h[p3zero2], Im[p3zero1] == 0 && Im[p3zero2] == 0}, {0, Im[p3zero1] != 0 || Im[p3zero2] != 0}}];

Plot3D[NIntegrate[AngularIntegrand[p3zero1, p3zero2]*Sin[\[Theta]], {\[Theta],0, \[Pi]}, MinRecursion -> 4, Method -> {Automatic, "SymbolicProcessing" -> 0}], {\[Nu], 0, 3}, {Q2, 0, 6}, ClippingStyle -> None, ImageSize -> 360] //AbsoluteTiming //Column

which also results in the warning given by BobHanlon. However compared to his method (~166s on my machine), my modifications let it finish after ~125s. So an improvement by ~25%.

A: M = 1.876 // Rationalize
m = 0.9389 // Rationalize;
q = Sqrt[Q2 + ν^2];
E3[p3_] = Sqrt[p3^2 + m^2];
E4[p3_] = Sqrt[p3^2 + q^2 - 2*p3*q*Cos[θ] + m^2];

For p3zero1 and p3zero2 use Set rather than SetDelayed so that the Solve and FullSimplify are done just once and not for each call.
p3zero1 = FullSimplify[
   p3 /. Solve[M + ν - E3[p3] - E4[p3] == 0, p3][[1]]];

p3zero2 = FullSimplify[
   p3 /. Solve[M + ν - E3[p3] - E4[p3] == 0, p3][[2]]];

f[p3_] = M + ν - E3[p3] - E4[p3];

h[p3_] = Abs[-(p3/Sqrt[m^2 + p3^2]) - (2 p3 -
       2 Sqrt[Q2 + ν^2] Cos[θ])/(2 Sqrt[
        m^2 + p3^2 + Q2 + ν^2 - 2 p3 Sqrt[Q2 + ν^2] Cos[θ]])];

Since AngularIntegrand is called by NIntegrate its definition should be restricted to numeric arguments.
AngularIntegrand[p1_?NumericQ, p2_?NumericQ] :=
 Piecewise[{{p1^2/(M^2 (M - 2*E3[p1])^2) 1/(E3[p1] E4[p1]) HeavisideTheta[
        p3zero1]/h[p3zero1] +
     p2^2/(M^2 (M - 2*E3[p2])^2) 1/(E3[p2] E4[p2]) HeavisideTheta[p3zero2]/
       h[p3zero2], Im[p3zero1] == 0 && Im[p3zero2] == 0}, {0,
    Im[p3zero1] != 0 || Im[p3zero2] != 0}}]

Plot3D[
   NIntegrate[
    AngularIntegrand[p3zero1, p3zero2]*Sin[θ],
    {θ, 0, π},
    MinRecursion -> 4],
   {ν, 0, 3}, {Q2, 0, 6},
   ClippingStyle -> None,
   ImageSize -> 360] //
  AbsoluteTiming // Column

NIntegrate::izero: Integral and error estimates are 0 on all
  integration subregions. Try increasing the value of the MinRecursion
  option. If value of integral may be 0, specify a finite value for the
  AccuracyGoal option. >>

The Plot3D took less than three minutes on my MacBook Pro.


text:
Q: RelativeLayout children not aligning to a centered ImageView Kind of embarrassing, but I'm having some basic issues aligning some views in a RelativeLayout. My XML is Below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".MyActivity">

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/background"
    android:scaleType="centerCrop"
    android:src="@drawable/background"/>

<ImageView
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:layout_centerInParent="true"
    android:id="@+id/imageview"
    android:src="@drawable/text" />

<Button
    android:layout_width="200dp"
    android:layout_height="60dp"
    android:enabled="false"
    android:id="@+id/button"
    android:background="@drawable/buttonxml"
    android:layout_below="@+id/imageview"
    android:layout_alignLeft="@id/imageview"/>

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/coin"
    android:src="@drawable/coin"
    android:layout_below="@id/imageview"
    android:layout_alignRight="@id/imageview"/>

</RelativeLayout>

I have a centered ImageView (id/imageview) and I want two views aligned below - one to the left and one to the right. However, with the xml above, it seems that the two smaller views are being aligned to id/imageview without taking into account the fact that it has been centered:

Before I center id/imageview, it looks like the following (note that the smaller views are now aligned as expected though they haven't moved):

Any ideas here other than using a collection of LinearLayouts? I feel like this is simple enough of a case to be handled with a RelativeLayout and I am probably just doing something stupid. Thanks in advance!

A: Is there a reason you want your RelativeLayout layout_width and height to wrap content? Setting them to match_parent may help you with center alignment.
By the way, your Button sets android:layout_below="@+id/imageview" instead of android:layout_below="@id/imageview".

A: Replace align_left by to_left and align_right by to_right


text:
Q: I am writing test script for mobile number validation, where i have to verify that all characters in mobile field should not be zero. I am writing test script for mobile number validation, where i have to verify that all characters in mobile field should not be zero. Can someone help me solve this out.

A: Like so,
String mobileNumber = "1234567890";

if(mobileNumber.matches("(.*?0.*?){5}"))
{
    // Number does not pass validation
}


text:
Q: how to create log file and to log data upto level of max 2mb next to generate new file by using c# trying to create log file in my window service application,to log information,error's as well,so each file has to log the data up to 2 mb max soon after it was finished it should create new log file in the same path,by over writing a file name of appending timestamp and start log into new file,can any one please suggest on the same

A: I would recommend to use any existing logging framework like NLOG for logging rather than rolling out your own, it has all the features you have mentioned.

A: Use log4net and you can achieve this using the rolling file appender.
You configure it through your config file (app.config or web.config) as follows:
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="log.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="2MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
</appender>


text:
Q: How to set patience as default git diff algorithm In .git/config I tried:
[diff]
    patience = true

But no luck
Do I have to do:
git diff --patience
git show --patience HEAD

etc., every time?

A: In lieu of a config-based answer, you could set an alias in your .gitconfig like so:
[alias]
dp = diff --patience
Which will allow you to do git dp [optional refspec]

A: Since Git 1.8.2, Git will use diff.algorithm:
git config --global diff.algorithm patience

It took a few iterations:

[PATCH v3 0/3] Rework git-diff algorithm selection
[PATCH v2 0/3] Rework git-diff algorithm selection
[PATCH 0/3] Rework git-diff algorithm selection
[PATCH] diff: Introduce diff.algorithm variable.
[PATCH] config: Introduce --patience config variable


text:
Q: I'm trying to recreate a specific plot in R (ggplot2) Despite having tried many types of lines, I just cannot get the same result.
Here is how I need the lines to look:

And this is how I got it so far (and am stuck at):

Here is my code:
myData <- read.csv(file.choose(), header = TRUE)
require(ggplot2)
g <- ggplot(myData, aes(speed, resp))
g + geom_point(aes(color = padlen, shape = padlen)) +
geom_smooth(method = "lm", formula = y ~ splines::bs(x, df = 4, degree = 2), se = FALSE, aes(color = padlen), linetype = "solid", size = 1) +
scale_color_manual(values = c("red", "black")) +
scale_shape_manual(values = c(2, 1))

And here is the database (dput):
myData <- structure(list(resp = c(0, 0.125, 0.583333333, 1, 0.958333333,
1, 0, 0.041666667, 0.25, 0.916666667, 1, 1), padlen = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("big",
"small"), class = "factor"), speed = c(2L, 3L, 4L, 5L, 6L, 7L,
2L, 3L, 4L, 5L, 6L, 7L)), .Names = c("resp", "padlen", "speed"
), class = "data.frame", row.names = c(NA, -12L))

I have also tried all these polynomial models (and others), but none works:
## Quadratic model
lmQuadratic <- lm(formula = y ~ x + I(x^2),
                  data    = fpeg)
## Cubit model
lmCubic <- lm(formula = y ~ x + I(x^2) + I(x^3),
              data    = fpeg)
## Fractional polynomial model
lmFractional <- lm(formula = y ~ x + I(x^2) + I(x^(1/2)),
                   data    = fpeg)

So, what should I do/not do to get my lines the same as the original ones? Thanks.

A: Instead of using method = "lm" in the geom_smooth-function use the glm with the binomial family. The glm-smooth gives you only values between 0 and 1 (what you want to have, because you're dealing with proportion).
library(ggplot2)

ggplot(myData, aes(speed, resp)) +
  geom_point(aes(color = padlen, shape = padlen)) +
  geom_smooth(method = "glm", method.args = list(family = "binomial"),
              se = FALSE, aes(color = padlen), linetype = "solid", size = 1) +
  scale_color_manual(values = c("red", "black")) +
  scale_shape_manual(values = c(2, 1)) +
  theme_classic()

Data
myData <-
  structure(list(resp = c(0, 0.125, 0.583333333, 1, 0.958333333, 1, 0,
                          0.041666667, 0.25, 0.916666667, 1, 1),
                 padlen = c("small", "small", "small", "small", "small",
                            "small", "big", "big", "big", "big", "big", "big"),
                 speed = c(2L, 3L, 4L, 5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 7L)),
            .Names = c("resp", "padlen", "speed"), class = "data.frame",
            row.names = c(NA, -12L))


text:
Q: Excel/ OpenFileDialog: Save to string last browsed file even after application exit I'm almost finished with my program, the only thing left missing is when I don't have to browse my excel file all over again. It's either I'll code it but can never change it or OpenFileDialog again and again everytime I run the program.
Is there a way to save the file location to string after browsing for the file even after application exit? So I won't have to browse for the file again and if ever the file is moved or missing, I can browse for the file only once.

A: As an option you can use Setting file as following:

*

*Add a setting file to your project.

*Add a property to your setting file.

*Set the value of this property when you need Properties.Settings.Default.MyProperty="path"

*Get the value of this property when you need Properties.Settings.Default.MyProperty

*Save settings when form closing

Save settings when formclosing:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    Properties.Settings.Default.Save();
}

The settings loads automatically and you don't need load settings at startup.


text:
Q: I have recently started learning hibernate and I got the following doubts I have recently started learning hibernate and I got the following doubts
Correct me if I am wrong.

*

*If hbm2ddl.auto is set to create, every time hibernate tries to interact with any table, that table will be dropped first.

*Because hibernate drops a table every time it interacts with it, if I want to update a record I cannot configure hbm2ddl value as create.

A: The table is not dropped and recreated every time hibernate interacts with it -- it's dropped and recreated when the SessionFactory is initialized.  This usually means when your application starts up.  So if you are doing some tests where you want to start with a clean database each time the application runs, setting hbm2ddl.auto to "create" would be reasonable.
For more, see the community documentation and this previous question.

A: If you will configure value as create you can update a record , but when your application is down , and you will restart it all changes will disappear.
So actually in this case its better to use update.
In case of update it only updates schema , you can define some schema sql file and use it on database side , and simply configure hbm2ddlauto as update.
Here are possible values of hbm2.ddlauto:

*

*validate: validate the schema, makes no changes to the database.

*update: update the schema.

*create: creates the schema, destroying previous data.

*create-drop: drop the schema when the SessionFactory is closed
   explicitly, typically when the application is stopped.


text:
Q: Running an Android phone as a stable webserver (for a Python CGI script) I'm new to Android. I have a Python program that is both a CGI script as well as an SMS-based interaction system for a small database. It is an extremely low demand system (a handful of users) being run by a grassroots organisation.  But it requires stability, in the sense of not having random crashes or down time. For various reasons, running this on an Android phone would resolve some problems with the existing setup. However, before I dive in, I wanted to check regarding the feasibility of such a system. It would have to:

*

*Run a web server that could execute CGI scripts (vanilla CGI)

*Respond to SMSs

*Handle an SQlite database

*Do so in Python (as porting it to Java is not feasible due to time constraints)

Interfacing with phone users is not required at this stage.
I am aware that the pieces that would be needed exist - web servers with CGI, SL4A, etc. But the webservers mostly seem intended for personal use and SL4A clearly states that it "is alpha quality software".  The various questions on SO relating to SL4A also don't seem to say much on this kind of use case.   They are focused on application development for phones (such as this one).
In short, would such a system be stable? Assuming the core program is sound, could I rely on it?

A: TLDR: CherryPy is a dependable server, and Android may be dependable enough to build servers on these days.

I used to maintain a project that used CherryPy and SL4A (with ws4py for websockets).
CherryPy 3.2.2 worked perfectly on Python 2.6 and Python 3.2.
The application was often running for a day or two. It seemed like it would have been fine if it ran longer, but it got restarted a lot as it was being developed.
CherryPy was always fine, but Android devices do sometimes just crash, so SL4A will exit from time to time, and need to be restarted. This may not be an issue on a device that was only used as a server. For me, it was always stable when the device was left running overnight, but would occasionally crash when I was using the device normally (it was my actual phone). All of this was on a Galaxy SII, back when Android was still pretty buggy like that.
Setting up CherryPy is easy. It's pure Python, so you can just drop a copy onto your path some place and import it (you do not need an emulator either).
You may struggle to keep the device awake. If it is left alone, it will go to sleep. You can tell it to stay awake in the developer options, but I am pretty sure that only works if the device is charging.
UPDATE: Android is much more stable now days, but work on the SL4A project has pretty much ended. There's a project called QPython that maintains SL4A as part of a bigger app, so this stuff can still be done.

A: For running Python CGI scripts in Android. Basically you needed a web server capable of running CGI scripts in Android platform but, I found none. You need toy CGI script to suit the Cherrypy web server and it could run on Android.
Are steps are here :

*

*First thing we need is to download the SL4A (r4) software in the
Android (2.3) emulator. It can be done from your Android browser by
going to the SL4A site. Now install the software in emulator.

*Then install Python for Android from the same SL4A site. It'll
download an apk of version r4.

*Launch SL4A application and check that HelloWorld python script is
running. It will make sure that your installation is fine.

*Now is the time to install Cherrypy library module. It can be found
at http://www.cherrypy.org/wiki/CherryPyDownload. I have taken 3.2.0
version. Download the egg for python 2.6.

*Now we need to transfer the egg file to Android emulator. Use adb
push command to transfer the egg file to /mnt/sdcard/Download.

*Launch Python for Android from emulator and click on Import modules.
It will list the newly uploaded egg file. Select it and install.

*Now we can write a Cherrypy script to be run as CGI. Below is a
HelloWorld example  taken from Cherrypy tutorial (modified a bit)

 # Import CherryPy global namespace
import cherrypy

class HelloWorld:
    """ Sample request handler class. """

    def index(self, **params):
        # CherryPy will call this method for the root URI ("/") and send
        # its return value to the client.
        for key in params:
            print key, '=', params[key]
        return "Hello world!"

    # Expose the index method through the web. CherryPy will never
    # publish methods that don't have the exposed attribute set to True.
    index.exposed = True

# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.config.update({'server.socket_host': '127.0.0.1'})
cherrypy.config.update({'server.socket_port': 8080})
cherrypy.quickstart(HelloWorld(), '/')

8> The script needs to be transferred to /mnt/sdcard/sl4a/scripts    directory in emulator. Then you can launch SL4A and tap the script to    run. Debug outputs are visible if you run in SL4A console.
9> From the Android browser, check the URL http://localhost:8080/. It will say "Hello world".
This the web server set we can place python scripts to access Android phone data and other stuff which can be exposed to the outside clients.
Credits to: see the screen shots here
Other Info:
micro-httpd (GET / POST / CGI support) cross-compiled to Android
python-for-android
Running "Hello, world!" as a CGI Script
What I recommend:
I suggest to go for any lightweight web servers (like node.js) in raspberry pi
Ref:

*

*Raspberrry pi python

*lightweight web servers

*web application framework for Node.js

A: Here is a link to one of my blog posts describing how to turn your android phone in a basic CGI webserver using Py4A / SL4A in around 10 minutes http://matbaker.wordpress.com/2013/01/29/android-webserver-in-10-minutes/

A: Your application requires running a server, which presumes constant availability, connectivity and unrestricted processing power. A mobile phone provides none of these.
Mobile phones are designed to conserve battery life by minimising processing and power demands. These two points are directly at odds with running a server.

But it requires stability, in the sense of not having random crashes or down time.

Assuming your software is correctly written, you may not have to worry about crashes, but the OS will be constantly trying to put the system to sleep.

*

*Run a web server that could execute CGI scripts (vanilla CGI)

*Respond to SMSs

*Handle an SQlite database

*Do so in Python (as porting it to Java is not feasible due to time constraints)

Why not just use a small virtual server?  You can easily purchase a server for as little as $5 a month (e.g. DigitalOcean) and use Twilio as an SMS gateway (a few cents per SMS).  Cheap, available, reliable and highly available.  You get a preinstalled Ubuntu image, install a few extra packages on there and away you go with Python and SQLite. And you don't have to worry at all about the mobile/SMS side of things (signal strength, network availability, etc).  All these points above would be satisfied by this solution.
If you don't want to operate a server externally (ie. "in the cloud") then you could use an old PC and install Linux. Or even use a plug computer and have an almost invisible server. There are so many hardware options that are more suitable than a mobile phone.

For various reasons, running this on an Android phone would resolve some problems with the existing setup.

How? What is it about Android that makes it preferable? If you're referring to the laptop battery problem, the phone would suffer a similar (if not worse) fate.

In short, would such a system be stable? Assuming the core program is sound, could I rely on it?

You will probably be fighting the OS and the hardware the whole time. A server wants to be running constantly, a mobile phone wants to be running as little as possible. The entire stack of hardware and software is optimised for power conservation. A mobile is designed to run from a battery with intermittent charging, and its thermal management systems are designed to wake the CPU as infrequently as possible. If you try to run a mobile as a server, you will likely wear out the hardware very quickly. They are simply not designed to run 24/7. You could run such a system, and it would probably work for a while, but I expect you would have to replace the hardware before too long.
Use hardware suited to the task of running a server. Old PCs are so easy to come by these days, it should be possible to get one for free that would be up to the task.
Also, is CGI really a requirement? You should really look at WSGI; it is far more efficient. CherryPi is a nice Python server, and Flask is definitely worth a look too.


text:
Q: Cloning a django project from hg using buildout and using it for development I have a django project sitting in a bitbucket repository. Is it possible to automate using buildout, the following process:
1. Install django
2. clone the django project from hg repository
3. install the dependency modules of the django project
Update: I have achieved what I wanted to, with the help of mr.developer extension as suggested by Ross.
While doing that I had another question popping up. Which is the best place to specify the dependencies - in the buildout.cfg or in the setup.py of the 'develop' modules? For now I have duplicated the specification.

A: Generally, you make your checkout the buildout itself, so you'd place buildout.cfg and bootstrap.py in your project root. That way when someone checks out/clones your project, they just do the bootstrap/buildout dannce and they're up and running.
If you have multiple checkouts, then look into mr.developer.


text:
Q: Open/Activate an closed Application on a remote machine through pssh in Mac os10.12.6 I was trying to open an application remotely using below command, but I get an error
pssh -h node.txt -O StrictHostKeyChecking=no -l mapsadmin -i "open /Applications/FusionX.app"

Below is error:
Stderr: LSOpenURLsWithRole() failed with error -10810 for the file /Applications/FusionX.app

mapsadmin is the user with root privileges, still couldn't get luck. Please help me in solving this.
I have tried with AppleScript also, but no luck
pssh -h node.txt -O StrictHostKeyChecking=no -l mapsadmin -i "osascript -e 'tell application \"FusionX\" to activate'"
[1] 16:07:31 [FAILURE] <IP address> Exited with error code 1
Stderr: 30:38: execution error: An error of type -10810 has occurred. (-10810)

Help me in solving this. Is there anything else to be enabled on remote machine to let this happen?

A: I would have preferred to leave this as a comment, but it was too long.  However, I fear this may not be a complete answer, as the causes of the error are myriad, but I hope this might help.
First, ssh into your remote machine using the standard ssh command (or go to the machine physically and open Terminal).  Now see if are you able to run the application from there using open /Applications/FusionX.app.  If this throws the same error, then see if you can run the actual binary file located in /Applications/FusionX.app/Contents/MacOS
cd /Applications/FusionX.app/Contents/MacOS
./FusionX

(Assuming the binary file located in that folder is called FusionX.  If not, adjust the line above accordingly.)
If that doesn't run the application, run this command:
chmod +x ./FusionX

then attempt to run the binary again.  If that works, exit from secure shell or return to your local machine and attempt to run your pssh command again.  I'm hoping this might solve your issue.
Also, you could try pure AppleScript to launch the application remotely using a command like
tell application "FusionX" of machine "eppc://remote_ip_or_hostname" to activate

(This requires Remote Apple Events turned On on the remote machine (under System Preferences > Sharing) and assumes FusionX is Apple-scriptable.)
Obviously, the limitation here is having to specify this command for each remote machine individually rather than through a single parallel command targetting multiple hosts.


text:
Q: When using React Navigation, opening the app with notifications causes the headers to grow Using React-Native 0.59.8
NativeBase 2.13.7
react-navigation 3.11.1
android 9
When open an app by clicking on it

when open an app by notification

In addition, the statusBar changes color.
I can't guess the cause of this problem.
Below is the code of the screenshot.
import ExtraDimensions from 'react-native-extra-dimensions-android';
import {
  Container, Header, Left, Body, Right, Button, Text, View, Content,
} from 'native-base';

const headerHeight = ExtraDimensions.getStatusBarHeight() + 40;

<Container style={{ backgroundColor: Colors.GRAY_LV0 }}>
  <Header
    transparent
    style={{
      height: headerHeight,
      borderBottomWidth: 0.5,
      borderBottomColor: Colors.GRAY_LV4,
    }}
  >
    <Left style={{ flex: 1 }}>
      <TouchableOpacity
        transparent
        onPress={close}
      >
        <Image
          style={{ height: 25, width: 25, tintColor: Colors.GRAY_LV7 }}
          source={{ uri: images.back }}
        />
      </TouchableOpacity>
    </Left>
    <Body style={{ flex: 3, flexDirection: 'row', justifyContent: 'center' }}>
      <Image
        style={{
          height: 22, width: 22, tintColor: Colors.GRAY_LV4, marginRight: 5,
        }}
        source={{ uri: images.settingLight }}
      />
      <Text style={styles.headerTitle}>
        설정
      </Text>
    </Body>
    <Right style={{ flex: 1, flexDirection: 'row' }} />
  </Header>
</Container>

const MyStackNavigator = createStackNavigator({
  Setting:SettingContainer,
}, {
  mode: 'card',
  headerMode: 'none',
});


text:
Q: Solve A Linear Congruence Using Euclid's Algorithm Solve a Linear Congruence using Euclid's Algorithm
I'm just a bit confused by how to plug in the remainders and such.
$179x\cong355\pmod{937}$
$937=179\cdot5+42 \implies 42=937-179\cdot5$
$179=42\cdot4+11\implies11=179-42\cdot4$
$42=11\cdot3+9\implies9=42-11\cdot3$
$11=9\cdot1+2\implies2=11-9\cdot1$
$9=2\cdot4+1\implies1=9-4\cdot2$
Starting from the last remainder:
$1=9-4\cdot2$
Plugging in the $2$:
$=9-4(11-9\cdot1)$
$=9-4\cdot11+4\cdot9$
Somehow this simplifies to $5\cdot9-4\cdot11$?
I'm a bit confused on this all, it would be appreciated if someone could lend me a hand.

A:
\begin{align}
1 &= 5(42-11(3))-4(11)\\
&=5(42)-19(11) \\
&= 5(42)-19(179-42(4)) \\
&= 81(42)-19(179) \\
&= 81(937-179(5))-19(179) \\
&= 81(937) - 424(179)
\end{align}

You did it right. If you go all the way up, you can obtain
$$1=81(937)-424(179)$$
$$1 \equiv (-424)(179) \mod 937$$
Hence, I would multiply the linear congruent equation by $-424$.


text:
Q: Can the sample size from a pilot study be substracted from the full sample required as estimated from the first's data? (I am aware of a similar question here but I feel the answer on it is too open-ended)
Assuming that the population is unchanged between both sampling stages and that we're using sampling without replacement, we would have the following probabilities for selection at each stage:
$$P(x_i \in S_{pilot}) = \frac{n_{pilot}}{N}$$
$$P(x_i \in S_{full}) = \frac{n_{full}-n_{pilot}}{N}$$
Because the events are mutually exclusive,
$$P(x_i \in S_{full} \cup x_i \in S_{pilot} ) = \frac{n_{full}-n_{pilot}}{N} + \frac{n_{pilot}}{N} = \frac{n_{full}}{N}$$
and so the probability of selection is the same as it would be if a sample of size $n_{full}$ had been taken from the population.
Is this correct or am I overlooking something?


text:
Q: Extend existing category inside MUI Theme I'm trying to add a few properties to the existing options inside of MUI's theme palette. Below is an example:
declare module @material-ui/core/styles/createMuiTheme {
  interface CustomOptions extends SimplePaletteColorOptions {
    lightest?: string
    darkest?: string
  }

  interface InfoPalette {
    info: CustomOptions
  }

  interface PaletteOptions {
    info: CustomOptions
  }

  interface Palette {
    info: InfoPalette
  }
}

The desired outcome is to add lightest and darkest as properties to the main color categories in the theme such as info, success, etc. I can add new categories for custom styles successfully but I cannot extend existing ones. Typescript still complains these properties don't exist.
Here is another thread with essentially the same question but the answer does not actually address the situation: Can't customize color palette types on Material UI theme in TypeScript

A: Don't extend interface, change it to:
declare module @material-ui/core/styles/createMuiTheme {
  interface SimplePaletteColorOptions {
    lightest?: string
    darkest?: string
  }

  interface InfoPalette {
    info: SimplePaletteColorOptions
  }

  interface PaletteOptions {
    info: SimplePaletteColorOptions
  }

  interface Palette {
    info: InfoPalette
  }
}


text:
Q: How to append json in Python List I want to create a JSON Python List shown as below using without repeated codes(Python functions).
Expected Output:
        Steps=[
        {
            'Name': 'Download Config File',
            'ActionOnFailure': 'CONTINUE',
            'HadoopJarStep': {
                'Jar': 'command-runner.jar',
                'Args': [
                    'aws',
                    's3',
                    'cp',
                    's3://sample-qa/jars/Loads/',
                    '/home/hadoop/',
                    '--recursive'
                ]
            }
        },
        {
            'Name': 'Spark Job',
            'ActionOnFailure': 'CONTINUE',
            'HadoopJarStep': {
                'Jar': 'command-runner.jar',
                'Args': [
                    'spark-submit',
                    '--deploy-mode', 'cluster',
                    '--executor-memory', '10g',
                    '--conf', 'spark.serializer=org.apache.spark.serializer.KryoSerializer',
                    '--conf', 'spark.sql.hive.convertMetastoreParquet=false',
                    '--master', 'yarn',
                    '--class', 'com.general.Loads',
                    '/home/hadoop/Loads-assembly-0.1.jar',
                    '20120304',
                    'sample-qa'
                ]
            }
        }
        {
            'Name': 'Spark Job',
            'ActionOnFailure': 'CONTINUE',
            'HadoopJarStep': {
                'Jar': 'command-runner.jar',
                'Args': [
                    'spark-submit',
                    '--deploy-mode', 'cluster',
                    '--executor-memory', '10g',
                    '--conf', 'spark.serializer=org.apache.spark.serializer.KryoSerializer',
                    '--conf', 'spark.sql.hive.convertMetastoreParquet=false',
                    '--master', 'yarn',
                    '--class', 'com.general.Loads',
                    '/home/hadoop/Loads-assembly-0.1.jar',
                    '20220130',
                    'sample-qa'
                ]
            }
        },
        {
            'Name': 'Spark Job',
            'ActionOnFailure': 'CONTINUE',
            'HadoopJarStep': {
                'Jar': 'command-runner.jar',
                'Args': [
                    'spark-submit',
                    '--deploy-mode', 'cluster',
                    '--executor-memory', '10g',
                    '--conf', 'spark.serializer=org.apache.spark.serializer.KryoSerializer',
                    '--conf', 'spark.sql.hive.convertMetastoreParquet=false',
                    '--master', 'yarn',
                    '--class', 'com.general.Loads',
                    '/home/hadoop/Loads-assembly-0.1.jar',
                    '20220214',
                    'sample-qa'
                ]
            }
        }
    ]

Attempted:
def lambda_handler(event, context):

steps = [
    {
        "Name": "Download Config File",
        "ActionOnFailure": "CONTINUE",
        "HadoopJarStep": {
            "Jar": "command-runner.jar",
            "Args": [
                "aws",
                "s3",
                "cp",
                "s3://sample-qa/jars/Loads/",
                "/home/hadoop/",
                "--recursive",
            ],
        },
    },
]

def addSteps(date):
    step = {
        "Name": "Spark Job",
        "ActionOnFailure": "CONTINUE",
        "HadoopJarStep": {
            "Jar": "command-runner.jar",
            "Args": [
                'spark-submit',
                '--deploy-mode', 'cluster',
                '--executor-memory', '10g',
                '--conf', 'spark.serializer=org.apache.spark.serializer.KryoSerializer',
                '--conf', 'spark.sql.hive.convertMetastoreParquet=false',
                '--master', 'yarn',
                '--class', 'com.general.Loads',
                '/home/hadoop/Loads-assembly-0.1.jar',
                date,
                'sample-qa'
            ],
        },
    }
    return step

for date in ['20210801','20210807','20210814']:
    addingstep = addSteps(date)
    steps.append(addingstep)
    steps =json.dumps(steps)

print(steps)

I have attempted this implementation, but getting error please find below.
Error:
AttributeError: 'str' object has no attribute 'append'
Any other possibility to create this list? How to achieve this ?

A: There is an issue with the indentation here:
for date in ['20210801','20210807','20210814']:
    addingstep = addSteps(date)
    steps.append(addingstep)
    steps =json.dumps(steps)

Fix:
for date in ['20210801','20210807','20210814']:
    addingstep = addSteps(date)
    steps.append(addingstep)

steps = json.dumps(steps)


text:
Q: requirejs-config, requirejs errors Does anyone know where these errors come from and how to solve them !

Failed to load for  element whose source is
  http://...pub/static/version1521024130/frontend.../fr_FR/text.js

I also see this in logs:

main.INFO: Broken reference: the 'requirejs-config' element cannot be
  added as child to 'head', because the latter doesn't exist [] []
main.INFO: Broken reference: the 'requirejs' element cannot be added
  as child to 'head', because the latter doesn't exist [] []
main.INFO: Broken reference: the 'requirejs-config' tries to reorder
  itself towards 'requirejs', but their parents are different: 'head'
  and '' respectively. [] []
main.CRITICAL: Unable to resolve the source file for
  'frontend/Smt/theme/fr_FR/text.js' [] []

Info: Im in developer mode, I deployed the static-content, clean cache, pub/static, var/view_preprocessed, generated but always the same thing.

A: *

*Did you make any changes to the <head> section of the theme?

*How did you delare the text.js file?

*Don't use setup:static-content:deploy in Developer mode, in Developer mode you have symlinks for the files in your theme


text:
Q: What books/websites should i read to learn to write readable and maintainable C code?
Possible Duplicate:
The Definitive C Book Guide and List
Good open source code for C++

I started learning C++ over 2 years ago.  Since then, i went back and learned C, among other programming languages, but C is my favorite.  While looking at open-source projects recently, i quickly realized that my code is ugly, barely readable, and the opposite of extendable.  I want this to change.  Any references/links to any books, websites, or other resources that would better help me program in C more professionally would be greatly appreciated.
thanks

A: Hmm you say you know C but it's not bad to mention the definite guide which is Dennis Ritchie's own book The C Programming Language.  Another book I have heard good things about is Programming in C by Stephen G Kochan, even though I have not read it myself.
But in my opinion the best way to actually learn to write optimal code is to try it. Make many projects, and fail at doing so. Then be forced to search the net for what made you fail or what a bug might be, realize that you wasted 2 days over a bug that could have been avoided if you had followed some programming standards and then learn from that experience


text:
Q: to understand the phytree object in matlab I asked the similar question here: what exactly is the phytree object in matlab?.
Now this is what I did to try to get it.
clear;
d=[4,2,5,4,5,5];
z=seqneighjoin(d);
view(z)
get(z, 'Pointers')

This  is the output:
ans =
     1     2
     3     5
     4     6

And the phytree figure in the following. For my understanding, this matrix is the same as the tree field of the phytree object. What is  the relation between this matrix and the figure?

A: You should interpret the array in the following way.
Firstly, you have the four nodes 1, 2, 3 and 4. In the graph you attach, node 1 is labelled Leaf 1; node 2 is labelled Leaf 3; node 3 is labelled Leaf 2; and node 4 is labelled Leaf 4.
Then take each row of the array in turn.
The first row indicates that we first join nodes 1 and 2 - we now call this node 5, as it's the smallest number greater than the four nodes we already have. On the graph, this is the node connecting Leaf 1 and Leaf 3.
Then the second row indicates that we next join nodes 3 and 5 - we now call this node 6, as again it's the smallest number after node 5. On the graph, this is the node connecting the previous join to Leaf 2.
Then the third row indicates that we lastly join nodes 4 and 6 - we don't need to call it anything as it's the final root node, but it would be node 7. On the graph, this is the node connecting the previous join to Leaf 4.
Does that make more sense?


text:
Q: Extract rows from CSV based on column data I have a report that is generated at the beginning of each month, in .csv format.  Currently, the report contains a series of columns with assorted data; one of the columns is an 'add_date' field containing data in "YYYY-mm-dd HH:MM:SS" format.
My end goal is to parse this source CSV so that only rows containing 'add_date' cells with dates from the previous month remain.  So for example, if the script were run on February 1st 2021, only the rows containing dates from January 2021 would remain in the output CSV file.
This is an example of the source CSV contents:
Name,Data1,add_date
jasmine,stuff ,2021-01-26 17:29:46
ariel,things,2021-01-26 17:48:04
ursula,foo,2016-11-02 19:32:09
belle,bar,2016-01-21 18:47:33

and this is the python script I have so far:
#!/usr/bin/env python3

import csv
filtered_rows = []

with open('test123.csv', newline='') as csvfile:
    rowreader = csv.reader(csvfile, delimiter=',')
    for row in rowreader:
        if row["2021-01"] in csvfile.add_date:
            filtered_rows.append(row)
        print(filtered_rows)

which I call with the following command:
./testscript.py > testfile.csv

Currently, when I run the above command I am greeted with the following error message:
Traceback (most recent call last):
  File "./testscript.py", line 9, in <module>
    if row["2021-01"] in csvfile.add_date:
TypeError: list indices must be integers or slices, not str

My current Python version is Python 3.6.4, running in CentOS Linux release 7.6.1810 (Core).

A: If I undestood well, you can do  something like this:
import pandas as pd
from datetime import datetime
df= pd.read_csv('test.csv',sep=',',header=0)
df['add_date']= pd.to_datetime(df['add_date'])
filtered=df[(df.add_date >= datetime.strptime('2021-01-01','%Y-%m-%d')) & (df.add_date <= datetime.strptime('2021-01-31','%Y-%m-%d')) ]

A: To do this properly you need to determine the previous month and year, then compare that to add_date field of each row. The year is important to handle December →
January (as well as the possibility of multi-year) transitions.
Here's what I mean.
import csv
import datetime

filename = 'test123.csv'
ADD_DATE_COL = 2

# Determine previous month and year.
first = datetime.date.today().replace(day=1)
last = first - datetime.timedelta(days=1)
previous_month, previous_year = last.month, last.year

# Extract rows for previous month.
filtered_rows = []
with open(filename, newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    next(reader)  # Ignore  header row.
    for row in reader:
        add_date = datetime.datetime.strptime(row[ADD_DATE_COL], '%Y-%m-%d %H:%M:%S')
        if add_date.month == previous_month and add_date.year == previous_year:
            filtered_rows.append(row)

print(filtered_rows)

I got the basic idea of how to determine the date of the previous month from @bgporter's answer to the question How to determine date of the previous month?.


text:
Q: Is it possible to receive notifications when a comment is added to a TFS Git pull request? My team uses a Git team project with TFS 2013 Update 4. Email notifications are sent out as expected when a pull request is created or a branch under review is updated. However, notifications aren't sent when a comment is added to the pull request - is it possible to enable that?

A: I don't believe that is currently possible, but it is a good idea. You should head over to http://visualstudio.uservoice.com and add it.

A: As of the 5/11/2017 release, users now get notifications for comments on PRs they create or have participated in.
https://learn.microsoft.com/en-us/vsts/release-notes/2017/may-11-team-services#default-notifications-for-pr-comments


text:
Q: Replace relative urls in html by absolute urls I'm scraping a external webpage to save in file, but sometimes this file contains relative urls that i can't view because this files not will be found. I want replace by absolute urls. I'm insterested in some module or function that replace all relative urls in html string to absolute. Any idea?
var request = require('request');
var WEBSITE = 'http://somewebsite.com/';
request.get(WEBSITE, function(error, response, body){
    body = replace_all_relative_by_absolute(body);
    console.log(body);
});

A: You can iterate over the links and add the domain yourself.
Using jQuery, install with:
npm install -S 'jquery@>=2.1'
npm install -S 'jsdom@latest'

Example implementation (barely tested):
var env = require('jsdom').env;

function addDomainToLinks(domain, html, callback) {
  env(html, function (err, window) {
    var $ = require('jquery')(window);
    $.each($('a'), function(i, v) {
      var href = $(v).attr('href');
      // Match links starting with /, but not //
      // You probably want to do handle './', and do the same for images, etc.
      if (href.match(/^\/[^\/]/)) {
        $(v).attr('href', domain + href);
      }
    });
    callback($('html')[0].outerHTML);
  });
}

Usage:
addDomainToLinks('http://example.com', html, function(html) {
  console.log(html);
});

A: import this
    from urlparse import urljoin

and then
    urljoin(base_url, file_url)


text:
Q: How to get data from two table in sqlite in android I am unable to getting data from two table in android using left join.
Here is the my query:
public Cursor getrespondentDataNew(String loc_id) {
        Cursor cur = null;

final String MY_QUERY = "SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r INNER JOIN respondentType rt ON r.type_code = rt.rtype_code WHERE r.site_code='" + loc_id + "'";

        cur = db.rawQuery(MY_QUERY, null);
 Log.i("sql:", "SQL Test=" + MY_QUERY);
 Log.i("cur:", "cur Test=" + cur.getCount());

and
final String MY_QUERY = "SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r INNER JOIN respondentType rt ON r.type_code = rt.rtype_code WHERE r.site_code=?";
cur = db.rawQuery(MY_QUERY, new String[]{loc_id});

....
04-04 11:45:28.212: I/sql:(11017): SQL Test=SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r,respondentType rt where r.type_code = rt.rtype_code and r.site_code='4'
04-04 11:45:28.224: I/cur:(11017): cur Test=0

EDIT: If i run this Query: why i am getting last value of rt.rtype_name:
SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r,respondentType rt where r.type_code = rt.rtype_code   or r.site_code='4' group by  r.code

In both case i did not get value, what is the wrong with this query.
My tables:
respondentTable

respondentType

I am testing site_code 4.

A: You can try it another way by following query style,
final String MY_QUERY = "SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r,respondentType rt where r.type_code = rt.rtype_code and r.site_code='" + loc_id + "'";

A: I Solve Problem using left outer join.
SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r LEFT OUTER JOIN respondentType rt ON r.type_code = rt.rtype_code    where r.site_code='4'


text:
Q: How to properly use useLocalStorage I have this custom hook useLocalStorage
import { useState } from 'react'

export function useLocalStorage (key, initialValue) {
  const [storedValue, setValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key)
      return item !== null ? JSON.parse(item) : initialValue
    } catch (e) {
      return initialValue
    }
  })

  const setLocalStorage = value => {
    try {
      window.localStorage.setItem(key, JSON.stringify(value))
      setValue(value)
    } catch (e) {
      console.log(e)
    }
  }

  return [storedValue, setLocalStorage]
}

and then I have this code in a component
const FavsProductList = () => {
  const data = useGetProducts(`${API}?limit=5&offset=1`)
  const [toggleRefresh, setToggleRefresh] = useState(false)

  return (

        {data.products && data.products
          .filter((item) => (
            JSON.parse(window.localStorage.getItem(`like-${item.id}`)) ? item : null
          ))
          .map(product => (

              <ProductItem product={product} favProduct={true} setToggleRefresh={setToggleRefresh}/>
              <Link to={`/product/${product.id}`}>ver detalle</Link>

))
        }

  )
}

I can't use the useLocalStorage custom hook inside the array filter function.
Will it be possible to use the useLocalStorage hook instead of window.localStorage.getItem ?


text:
Q: Importing Altium schematics to a PCB is placing some components on a forbidden and an unaccessible area I was using Altium 16 and generating PCB from schematics with no room generation. I have created my components library by mostly using "ultra librarian" files. I do these steps as many other times with no problems.
After this, I first run "design/update PCB doc.." from schematic view and when the process has ended my pcb components generation has this view:

As you can see, some components have fallen out of allowed display and I can not achieve the most of them in order to drop up them into an allowed area.
I have noticed that there are some components that are put under origin coordinates, so it is the maximum that display can achieve. It can not go down origini coordinates.
I have also noticed that some components has the designator is placed so far from its component footprint.
I removed the pcb document and restart the traslation, but no changes happened.
I build a new project using the libs and schematic and start the traslation, but it results with the same way.

*

*Have this happened to someone else?

*Why can it be happening? Is it a sw bug?

*How can it be solved in order to move and place the components from there?
Giving me some hints could be helpful for me.

A: This is a combination of multiple errors, some user-based and some bugs in the SW.
The reason your components are imported quite far from their designator is a problem with your libraries. This is due to where the origin-point of your component is located. It should usually be in the center of the component (or on Pin 1). If it instead is somewhere in a corner, you'll see this effect.
In earlier versions of Altium, there was a maximum leftmost and downmost point it was not possible to view beyond. This is not the origin-point, however. What I'd do then, is before importing any components I'd move the origin point to somewhere up and to the right.
This will mean that any components imported with an offset like this can be reached, as they'll be placed beyond the origin-point, but not beyond the maximum view-point.

A: The component with the designator at the end of the world made me to suspect from it.
So, I tried one more thing: to recompile the project without this component at schematic. The result was fine!
Then I removed the "suspicious" footprint from my library and load it again, with the same name (but you can even change it). I put again the component on the same schematic and it works!
I don't know how the designators has moved this way before. I saw the origin in the center of the component; but strangely it was seen so small at preview when I opened it.
Once I reloaded the footprint, this strange zoom out effect was disappeared and schematic updating was fixed.
Thanks for your attention.
I hope this problem and solution will be useful for someone at  future. I spent too many time dealing with this.


text:
Q: For loops are working separately, but not together I'm new to coding and I'm currently trying to solve this question: https://leetcode.com/problems/set-matrix-zeroes/
Code:
class Solution {
    public void setZeroes(int[][] matrix) {
        int [][] arr = matrix;
        for(int m=0;m<matrix.length;m++) {
            for(int n = 0;n<matrix[m].length;n++) {
                if(matrix[m][n] == 0) {
                    //loop 1
                    for(int i = 0; i<matrix.length;i++) {
                        arr[i][n] = 0;
                    }

                    //loop 2
                    for(int i = 0; i<matrix[m].length;i++) {
                        arr[m][i] = 0;
                    }
                }
            }
        }
        matrix = arr;
    }
}

Working code:
class Solution {
    public void setZeroes(int[][] matrix) {
        //declaring new 2D array
        int[][] arr = new int[matrix.length][matrix[0].length];

        //giving values to new 2D array (copying matrix)
        for(int i = 0; i<matrix.length;i++) {
            for(int j = 0; j<matrix[i].length;j++) {
                arr[i][j] = matrix[i][j];
            }
        }

        for(int m=0;m<matrix.length;m++) {
            for(int n = 0;n<matrix[m].length;n++) {
                if(matrix[m][n] == 0) {
                    for(int i = 0; i<matrix.length;i++) {
                        arr[i][n] = 0;
                    }

                    for(int i = 0; i<matrix[m].length;i++) {
                        arr[m][i] = 0;
                    }
                }
            }
        }
        for(int i = 0; i<matrix.length;i++) {
            for(int j = 0; j<matrix[i].length;j++) {
                matrix[i][j] = arr[i][j];
            }
        }
    }
}

The problem I'm having is that the for loops are working fine separately, but when I run them together, they aren't working. If you remove loop 1, the loop 2 works fine.
The first for loop (loop 1) adds '0' vertically wherever they belong, and the second for loop (loop 2) adds '0' horizontally like its supposed to. But together, they don't work. What's the issue that I'm having?

A: The issue has to do with this:
int [][] arr = matrix;

this does NOT make a new matrix, but instead makes arr reference matrix.
If I am not mistaken you always need to declare the new matrix like this:
int [][] arr = new ....

check out this thread for more information as top how to duplicate a matrix.
The reason it worked when it was only one loop, was because you did not need to duplicate the matrix if you were running only one loop.


text:
Q: Read a Word XML file using PHP Does anyone have any recommendations for how to read a Word (2007-2013) file using PHP?  I'm using the build in styles to mark up a word document, and would like to read it with PHP ideally in order to analyze the contents.  I've tried searching google and this site, but no luck.  If anyone has any experience with this or ideas on where I would get started, it would be appreciated.

A: If you are just interested in the content of the Word Document and for example turning it into an HTML page. I would not recommend PHPWord as its internal structure is quite complex. The following code uses only PHP native functionalities to read all Paragraphs of an docx Document.
 /*DOCX is actually a ZIP file containing other files, document.xml
holds the text of you document, sadly not the styles, you need to drill
further into other files to extract the styles*/

    $result = file_get_contents('zip://word.docx#word/document.xml');

    //Load the document XML into PHP's SimpleXML
    $xml = simplexml_load_string($result,null, 0, 'w', true);
    $body = $xml->body;
    foreach($body[0] as $key => $value){
        echo "<p>";
        if($key == "p"){
            foreach ($value->r as $kkey => $vvalue) {
                echo (string)$vvalue->t;
            }
        }
        echo "</p>";
    }

A: Here you go :)
$zip = new ZipArchive;
$zip->open("MyFile.docx");
if (($index = $zip->locateName("word/document.xml")) !== false) {
    $text = $zip->getFromIndex($index);
    $xml = DOMDocument::loadXML($text, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
    echo $xml->saveXML();
}
$zip->close();

if you need to install the zip ext you can find it here: http://php.net/manual/en/zip.installation.php
hope it helps you along!

A: You can use PHPWord! I believe that has a function to read docs.

A: I know it's not quite what you were looking for, but could you get them to re-save the Word documents in .odt?
This article could help if you get to that stage:
reading odt files in php

A: I don't have a direct answer, but my preference is to break a complex problem like this into simpler pieces.
The approach I would use is to open it in Word (or in OpenOffice or LibreOffice) and save as HTML. Then I would prepend a  instruction and read it with one of the many XML classes/extensions available in PHP.
[I found this question because I was Googling for a framework that would let me go through the HTML that Word generates and clean it up -- turn it into legal XHTML1.0, remove the useless style information that Word creates, while preserving my user-generated styles, etc. That second will require some experimentation to determine what I want to keep and what I want to discard, but I think that is well within my hobbyist capabilities.]


text:
Q: Using prime "'" in Julia variables I have many variables and matrices that I would like to call with a prime, like:
xprime, yprime, rprime and so on.
I believe that I can't use x', y', r' etc. as it is for instance used for matrices transposed.
julia> x' = 5
ERROR: syntax: invalid assignment location "x'" around REPL[2]:1
Stacktrace:
 [1] top-level scope at REPL[2]:1

julia> x = [1,2]
2-element Array{Int64,1}:
 1
 2

julia> x'
1×2 LinearAlgebra.Adjoint{Int64,Array{Int64,1}}:
 1  2

I am opened to any suggestion of a more convenient way than xprime, yprime etc. which is pretty long and ugly I think.

A: You can use prime:
julia> x′ = 1
1

julia> x′
1

help?> ′
"′" can be typed by \prime<tab>

Notice the difference that I use the ′ (prime), while you tried to use ' (single quote). Using single quote is not allowed in variable name as it invokes adjoint operation on a value preceding it (which you can see in your example).
As explained in help for ′ you can type it in in Julia REPL and in most editors configured to support Julia by typing \prime and pressing Tab.


text:
Q: Trying to get non repeating numbers by using nested loop..(2-D array) I am trying to figure out a way that I can insert random numbers into a 2-d array that is 5x5. I am working on a bingo game so it anyone could help me I would be greatly appreciative. I am fairly new to Java, so any help would be good. Thanks.
Consider:
boolean matchFound;  // used to track when a repeat is found
int rand; // temporarily store the random number before putting it into the array to check if it's a repeat

Random rn = new Random();
for (int i = 0; i < 25 ; i++) {
    rand = rn.nextInt(15) + 1;
    matchFound = false;  // assume that the number generated is not a repeat
    for (int x = 0; x <= 5; x++) {
        for (int j = 0; j <= 5 ; ++j){
            if (rand == b[x][j]) {  // check if the number just generated is a repeat
                matchFound = true;  // if it is, set the boolean to True and use that after the loop
            }
            if (matchFound == true) { // if the last number is a repeat, then
                i = i - 1;  // reduce the loop counter by 1 to go back to that place for the new number
            } else {
                b[i][j] = rand;  // the number was not repeated so insert it.
            }
        }
    }
}

A: I would recommend treating it like a bingo game - where you have a set of numbers, randomize them, and the 'pick' numbers for the board. I believe bingo ranges from 1-75? but you could change that. And then just pick the first 25 numbers from your ArrayList, they are sure to be random and not repeated this way.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class Test {
    public static void main(String[] args){
        ArrayList<Integer> bingo = new ArrayList<Integer>();
        int[][] b = new int[5][5];

        // create a list in order
        for (int i = 1; i <= 75; i++) {
          bingo.add(i);
        }

        Collections.shuffle(bingo); // randomize

        // Add to the board
        for (int i = 0; i < 5; i++) {
          for (int j = 0; j < 5; j++) {
            b[i][j] = bingo.remove(0); // remove the first item in the shuffled list
          }
        }

        System.out.print(Arrays.deepToString(b));
    }
}

A: As in bingo game, You need to track the column number to get the right range boundary of each column (min & max values in below code).
and for each iteration in the outer loop of column values these values will change accordingly
public static void main(String[] args) {

    int[][] b = new int[5][5]; // 5x5 grid

    for (int i = 0; i < 5; i++) { // loop for columns

        int min = i * 15 + 1;
        int max = (i + 1) * 15;

        for (int j = 0; j < 5; j++) { // loop for rows
            int rand;

            do {
                rand = getRandom(min, max); // generate random int between min & max values
            } while (isMatch(rand, b));

            b[j][i] = rand;
        }
    }
    /* print array values */
    for (int[] x : b)
        System.out.println(Arrays.toString(x));

}

/* return true if num is in the array b */
private static boolean isMatch(int num, int b[][]) {
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            if (num == b[i][j]) {
                return true;
            }
        }
    }
    return false;
}

/* return integer number between min & max inclusive */
public static int getRandom(int min, int max) {
    return (int) ((Math.random() * (max + 1 - min)) + min);
}

Output
[14, 22, 37, 57, 62]
[15, 20, 45, 55, 63]
[6, 29, 38, 52, 69]
[11, 30, 34, 59, 74]
[4, 16, 36, 54, 67]


text:
Q: Using R Shell to Run Unix Installation Commands on Windows I want to to install bibutils using R on my pc. With unix/ubuntu, I can use "sudo apt-get install bibutils" which works great. I tried using R shell to do the same:
shell('sudo apt-get install bibutils')

and got the following errors:
'sudo' is not recognized as an internal or external command,
operable program or batch file.
Warning messages:
1: running command 'C:\WINDOWS\system32\cmd.exe /c sudo apt-get install
bibutils' had status 1
2: In shell("sudo apt-get install bibutils") :
'sudo apt-get install bibutils' execution failed with error code 1

Is there a better way to do this? Thanks.


text:
Q: BigQuery GENERATE_UUID() and CTE's This behavior surprised me a little bit.
When you generate a uuid in a CTE (to make a row id, etc) and reference it in the future you'll find that it changes. It seems that generate_uuid() is being called twice instead of once. Anyone know why this is the case w/ BigQuery and what this is called?
I was using generate_uuid() to create a row_id and was finding that in my eventual joins that no matches were occurring because of this. Best way to get around it I've found is by just creating a table from the first CTE which cements the uuid in place for future use.
Still curious to know more about the why and what behind this.
with _first as (

  select generate_uuid() as row_id

)
,_second as (

  select * from _first

)

select row_id from _first
union all
select row_id from _second

A:
curious to know more about the why and what behind this

This is by design:
WITH clauses are not materialized. Placing all your queries in WITH clauses and then running UNION ALL is a misuse of the WITH clause.
If a query appears in more than one WITH clause, it executes in each clause.
You can see in documentation - Do not treat WITH clauses as prepared statements