text:
Q: get order status from order id, email and customer's last name I'm currently looking for a method from which I can get the order status based on the order id, customer email and customer last name.
I'd written this code so far
public function orderHistoryAction(){
    $req = $this->getRequest();
    $oid = $req->getParam('oid', '');
    $lnm = $req->getParam('lnm', '');
    $eml = $req->getParam('eml', '');

    $order = Mage::getModel('sales/order')->loadByIncrementId($oid);
    if ($order->getId()) {
        if ((strcasecmp($lnm, $order->getCustomerLastname()) == 0) && (strcasecmp($eml, $order->getCustomerEmail()) == 0)) {
            echo $order->getStatusLabel();
        } else {
            echo 'invalid';
        }
    } else {
        echo 'invalid';
    }
}

and is working well for both customer and guest. But this doesn't seems to me the right approach. I supposed to used something like written in this blog or here too. If anybody could make me correct?

A: If you would like to use collections, the code you need will look like:
$order_collection = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('increment_id', array('eq' => $oid))
->addFieldToFilter('customer_lastname', array('eq' => $lnm))
->addFieldToFilter('customer_email', array('eq' => $eml));

if ($order_collection->getSize() > 0) {
    $order = $order_collection->getFirstItem();
    ....
} else {
    ....
}

You can find another answer here: Filter magento order collection


text:
Q: using 2 Java classes to display information on 1 XML file I am new to programing and I am trying to clean up my main class.
There is just too much going on there.
I was wondering if it is possible to set up a way that 2 classes were to control 1 xml file.
For now I started doing this, but it didnt work:
public class MainActivity extends AppCompatActivity{
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   ....SOME CODE....
    getParsha();

  }
}

public void getParsha() {
  new Parsha();
}

In new Parsha I had this code:
public class Parsha extends AppCompatActivity {

  Parsha() {
    setContentView(R.layout.activity_main);

....SOME CODE.....

  }

}

I also tried doing this in onCreate() and it didnt work.
I am not sure why, is this even allowed to do in Android.
Please Note: I didnt get any error, it simply just didnt process the code, no Log or anything.
Thank you.

A: When you call the Activiy shoud use Intent
Like this
intent = new Intent(MainActivity.this, Parsha.class);
startActivity(intent);
finish();//if use need to stop use first activity.

And then, In your second activity namely Parsha, why you are set content view in inside constructor
You should give this in onCreate block only
setContentView(R.layout.activity_main);

Your two activity should be in following structure
    public class MainActivity extends AppCompatActivity{
        @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
        ....SOME CODE....
getParsha();
         }

        public void getParsha() {
        intent = new Intent(MainActivity.this, Parsha.class);
    startActivity(intent);
         }
    }

Second Activity
    public class Parsha extends AppCompatActivity{
        @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
        ....SOME CODE....
         }
        }

A: Rather than using xml file in both java files why dont you just make the common variables static and keep the code in Parsha.java, use the class wherever inside onCreate(). The following example might give you a clear idea.
MainActivity.java
public class MainActivity extends AppCompatActivity {

ListView list;
ArrayAdapter<String> adap;
static ArrayList<String> arr;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    list = (ListView) findViewById(R.id.list);
    arr = new ArrayList<String>();
    new Parsha();
    arr.add("Hello");
    arr.add("There");
    adap = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arr);
    list.setAdapter(adap);
}
}

Parsha.java
public class Parsha extends AppCompatActivity{

Parsha(){
    arr.add("This");
    arr.add("Works");
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

redpajama_set_name: RedPajamaStackExchange


text:
Q: как измерить время выполнения кода в python? ...есть ли в PyCharm встроенная возможность отслеживать время выполнения?

A: import time

start = time.time() ## точка отсчета времени

##код программы

end = time.time() - start ## собственно время работы программы

print(end) ## вывод времени

A: import timeit
code_to_test = """
a = range(100000)
b = []
for i in a:
    b.append(i*2)
"""

elapsed_time =  timeit.timeit(code_to_test, number=100)/100
print(elapsed_time)

#все что внутри тройных ковычек проверяется


text:
Q: Why does Caliburn.Micro.Start use the name "Shell"? The Caliburn.Micro.Start package provides the files IShell.cs, ShellView.xaml, and ShellViewModel.cs. I understand how these files operate and how they are wired into the provided AppBootstrapper. What I'm not so clear on is the name "Shell," in particular why is it called that. Is the word meant to connote:

*

*These files are a template/sample/skeleton window; a "shell" of a window.

*These files are intended to contain the "launching" point of the app. The command line (if any) could be parsed here and then the appropriate "main" window could be displayed from here.

*These files are meant to be used as the "main" window of the app, or the app's "shell." I've actually renamed these files to IMainWindow, MainWindowView, and MainWindowViewModel and run with that.

I'm feeling pretty dense asking this question. I know that IShell is a view model and ShellView is the view for that view model, the name just seems curious to me and maybe I'm reading too much into the name?


text:
Q: Proper way to redirect to an action from within a class? Background
I have a project split between Web Forms & MVC (moving towards MVC, thankfully).
I have a LoginManager class that takes in an IRedirectionManager class, and based on user properties (is authenticated, password expired, hasn't accepted terms) calls different methods on the Redirection manager (RedirectToLogin, RedirectToAcceptTerms, etc.)
I'm working to build and implement the "Redirect Manager" for our MVC controllers.
Questions

*

*Should this be an ActionFilter or a Base Class? It appears that I could use either, but am not sure if that's actually the case.

*What is the appropriate way to redirect to an action or route in MVC? For the web forms RedirectManager, I was passing in the response object and using Response.Redirect to get to the page. I'd love to be able to use something like RedirectToAction, etc. to make this work.

Code
In case it helps to clarify. The LoginManager:
public class LoginManager
{
    private IRedirectManager _redirectManager;
    private string _returnUrl;
    private ClaimsIdentity _currentUser;

    public LoginManager(string attemptingToAccessUrl, ClaimsIdentity identity, IRedirectManager redirectManager)
    {
        if (redirectManager == null) { throw new ArgumentNullException("redirectManager"); }
        if (identity == null) { throw new ArgumentNullException("identity"); }

        _redirectManager = redirectManager;
        _currentUser = identity;
        _returnUrl = attemptingToAccessUrl;
    }

    public void CheckLoginAndRedirect()
    {
        if (!_currentUser.IsAuthenticated)
        {
            if (string.IsNullOrWhiteSpace(_returnUrl)) { _redirectManager.RedirectToLogin(); }
            else { _redirectManager.RedirectToLogin(_returnUrl); }
        }

        if (_currentUser.IsDisabled()) { _redirectManager.RedirectToDisabled(); }

        if (UserRequiresPasswordReset()) { _redirectManager.RedirectToResetPassword(_returnUrl); }

        if (!_currentUser.HasAcceptedTerms()) {
            if (_currentUser.IsExternalUser()){ _redirectManager.RedirectToTermsAcceptance(_returnUrl); }
        }

        if (PasswordIsAboutToExpire())
        {
            if (!_currentUser.HasDeclinedToChangePassword()) { _redirectManager.RedirectToPasswordExpiringSoon(_returnUrl); }
        }
    }
}

Here's an example of the WebFormsRedirectManager:
public class WebFormsRedirectManager : IRedirectManager
{
    private HttpContext _httpContext;

    public WebFormsRedirectManager(HttpContext currentHttpContext)
    {
        if (currentHttpContext == null) { throw new ArgumentNullException("currentHttpContext");}

        _httpContext = currentHttpContext;
    }

    public void RedirectToLogin()
    {
        _httpContext.Response.Redirect("~/AccountManagement/Login");

    }
}

And an example of how I use it in my ProtectedPage class, which other web forms pages inherit from:
public class ProtectedPage : BasePage
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        var redirector = new WebFormsRedirectManager(Context);
        new LoginManager(null, ClaimsPrincipal.Current.Identity as ClaimsIdentity, redirector).CheckLoginAndRedirect();
    }
}

A: If you have a look at the MVC source code RedirectToAction() returns a RedirectoToRouteResult object. This class is effectively doing what you are doing - calling Response.Redirect().
public override void ExecuteResult(ControllerContext context)
{
    ...

    string destinationUrl = UrlHelper.GenerateUrl(
        RouteName, null /* actionName */, null /* controllerName */,
        RouteValues, Routes, context.RequestContext,
        false /* includeImplicitMvcValues */);

    ...

    context.HttpContext.Response.Redirect(destinationUrl, endResponse: false);
}


text: Q: Is there terminology around a bivariate function that is dependent on only one of its two arguments? For example, if $f$ can be defined by $f(x, y) = g(x)$ for some $g$ and all $x$, are there any special adjectives that are applicable to $f$?


text:
Q: How to mount an expression for "contain" in QGIS 2.18.14 Atlas/Print Composer? EDITED: I did a refinement of the question.
Can I ask for your help? Can you download and try to help find the solution? In the link is a simplified project zip file. It has only two layers; one for roads and another for territories.- filterroads20180107.zip
I need to see in the existing Atlas / Print Composer table, filtered roads, not those that are visible on the map, but only those that belong to the current feature.
The attribute table in the 'territory' field can store more than one number. A street can belong to more than one territory.
The expression "territory" = @atlas_featurenumber ", shows the streets that have only one value, the same value of the feature, but leaves out the streets that have other numbers. e.g., show value 09, but don´t show the rows that have 09, 05, ...
1 - The expression should use a "contain" or "like", but I can not find the correct syntax. The expression "territory" like %@atlas_featurenumber%, does not work.
2- Should a "CASE" or "CASE WHEN" be used instead? How?

A: Like should be the right operator to use i think but why do u use  @atlas_featurenumber ?
its purpose is not what u seem to expect...
u should rather retrieve the "territorios" property of the current atlas feature :
attribute (@atlas_feature, 'territorios')

and then build a string to use with the like operator, that should be something like :
"territorios" like concat('%',attribute (@atlas_feature, 'territorios'),'%')

but i haven't tried it ...


text:
Q: how to divide table contents into second page on thujohn pdf using laravel I have a large single pdf document which consists of multiple records.I need to break or split the table records into second pages in the pdf using laravel.
Using the below codings in the controller the table records are not fully displayed.Some table records are missing in that pdf file.so I need to show the missing table records into second pafe of the pdf file.
    private function generatePdf($customerstatement, $content) {

    if (!is_dir(RECEIPTS_DIR)){
        mkdir(RECEIPTS_DIR, 0755, true);
    }
    $outputName = $customerstatement->card_id . '-' . strtoupper(date("MY"))   .'.pdf';
    $pdfFileName = RECEIPTS_DIR.'/' . $outputName;
    $view =  View::make("admin.document.statement", compact('customerstatement', 'content'))->render();
    $pdf = new \Thujohn\Pdf\Pdf();
    $bytes_written = File::put($pdfFileName, $pdf->load($view, 'A4', 'portrait')->output());
    if ($bytes_written === false) {
        throw new \Exception("Unable to produce pdf statement");
    }
    $customerstatement->pdffile = $outputName;
    $customerstatement->save();
    return $outputName;
}

The below codings are written in the blade file for showing the records in the pdf.

       {{ $customerstatement->customer->card_id }} - {{ $customerstatement->customer->fullName }}

       Beginning Balance : {{ $customerstatement->beginning_balance }}

   @foreach ($customerstatement->statements as $statement)

                    {{{ $statement->date }}}
                    {{{ $statement->memo }}}
                    {{{ $statement->debit }}}
                    {{{ $statement->credit}}}
                    {{{ $statement->closing_balance}}}

    @endforeach

A:

            {{ $customerstatement->customer->card_id }} - {{ $customerstatement->customer->fullName }}

Beginning Balance : {{ $customerstatement->beginning_balance }}

               <?php $i=0 ?>
                @foreach ($customerstatement->statements as $statement)
                <?php $i++ ?>

                   {{{ date("d-m-Y", strtotime($statement->date) )}}}
                   {{{ $statement->memo }}}
                   {{{ $statement->debit }}}
                   {{{ $statement->credit}}}
                   {{{ $statement->closing_balance}}}
                   <?php
                           if($i==25){ ?>
                           <?php $i=0 ?>

                        <?php   }
                    ?>


text:
Q: RSpec LoadError I'm trying to practice writing tests for challenges on CodeEval. Each challenge I'm creating a folder, inside the project folder I create  'lib' & 'spec' folder. From the command line I run:
rspec --init

it tells me that 'spec/spec_helper.rb' & '.rspec' are created. I put the source file in the 'lib' folder & the spec file in the 'spec/lib' folder & name them accordingly. Here's an example of a spec:
require 'spec_helper'
require 'file_name'

describe '#swap_elements' do
  it 'should swap 1 pair of numbers' do
    swap_elements('1 2 3 4 5 6 7 8 9',0,8).should == '9 2 3 4 5 6 7 8 1'
  end
end

from the project's root directory I run:
rspec /spec/lib/file_name_spec.rb

and the result is the following:
/Users/username/.rvm/gems/ruby-2.0.0-p195/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `load': cannot load such file -- /spec/lib/swap_elements_spec.rb (LoadError)
from /Users/username/.rvm/gems/ruby-2.0.0-p195/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `block in load_spec_files'
from /Users/username/.rvm/gems/ruby-2.0.0-p195/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `each'
from /Users/username/.rvm/gems/ruby-2.0.0-p195/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `load_spec_files'
from /Users/username/.rvm/gems/ruby-2.0.0-p195/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:22:in `run'
from /Users/username/.rvm/gems/ruby-2.0.0-p195/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in `run'
from /Users/username/.rvm/gems/ruby-2.0.0-p195/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'

This is a recent problem & I haven't installed any updated rspec gems. Any idea why this is happening?

A: Using a slash at the start of a path means the root.
You want to do
rspec spec/lib/file_name_spec.rb

So  it will search on the current directory


text:
Q: Make an element in array explode How to make an element array inside an array explode again.
I have an array like this
echo "<pre>";
print_r($pks);

The Result.
Array
(
    [0] => 2017-04-15||KMTC_HOCHIMINH
    [1] => 2017-04-15||OOCL_NAGOYA
)

I expected like this,
Array
(
    [record] =>
       [1] 2017-04-15
       [2] KMTC_HOCHIMINH
    [record] =>
       [1] 2017-04-15
       [2] OOCL_NAGOYA
)

What keys on php to process array like this.
Please advise.
UPDATE
How about this .
Array
(
[0] => Array
    (
        [date] => 2017-04-15
        [vessel] => KMTC_HOCHIMINH
    )

[1] => Array
    (
        [date] => 2017-04-15
        [vessel] => OOCL_NAGOYA
    )

)

A: You can use array_walk() (or just foreach if you want):
array_walk($pks, function(&$a) {
    $a = array_combine(['date', 'vessel'], explode('||', $a));
});

Foreach method:
foreach($pks as $k => $v) {
    $pks[$k] = array_combine(['date', 'vessel'], explode('||', $v));
}

However, the key of each array won't be record, since it's impossible to have the same key multiple times.
Output:
Array
(
    [0] => Array
        (
            [date] => 2017-04-15
            [vessel] => KMTC_HOCHIMINH
        )

    [1] => Array
        (
            [date] => 2017-04-15
            [vessel] => OOCL_NAGOYA
        )

)

Bonus method because I like messing with arrays:
$pks = array_map('explode', array_fill(0, count($pks), '||'), $pks);

A: Try this, check the live demo
foreach($pks as $k => $v) {
    $values = explode('||', $v);
    $result[] = array_combine(range(1, count($values)), $values);

    //added
    $res[] = array_combine(['date', 'vessel'], $values) ;

}

result
Array
(
    [0] => Array
        (
            [1] => 2017-04-15
            [2] => KMTC_HOCHIMINH
        )

    [1] => Array
        (
            [1] => 2017-04-15
            [2] => OOCL_NAGOYA
        )

)


text:
Q: Upgrade from Rails 3.2, sunspot_rails and sunspot_solr 1.3.3, to Rails 4.x and gems version 2.1.x I'm trying to upgrade my Rails app to rails v 4.x and therefore using gems v > 2.x .
I tried to use gems version 1.3.3, but it looks like they are not compatible with new rails version...
I now start solr in development and test doing: sunspot-solr start , leaving default options.
Anyway, I have most of the things working, apart from a strange behavior.
I have a model defined pretty much like this:
class AAA < ActiveRecord::Base
searchable do
text    :code

text    :name

end
end
Let's say I have a database entry with those values:

code: 'ABC'
name 'testy searchy'

If I try to do:

AAA.search do
   fulltext('abc')
end

I get proper result
If I try to do:

AAA.search do
   fulltext('ab')
end

I get proper result
If I try to do:

AAA.search do
   fulltext('testy')
end

I get proper result.
But if I try:

AAA.search do
   fulltext('tes')
end

I don't get any results, whereas in version 1.3.3 everything used to work fine.
What am I missing?


text:
Q: Unrecognized expression when using special ID I have the following code in my jQuery Mobile 1.2 project. It was working fine until I upgraded from jQuery 1.7.2 to jQuery 1.8.3.
<input type="text" id="a['val']" name="a['val']" />

When the page is loaded, it throws
Syntax error, unrecognized expression: label[for='a['val']']
and the page refuse to load. Although there's no label in my code, the error thrown is asking for a label. This problem only occurs specifically in jQuery 1.8 and it's working fine for 1.9 and versions prior to 1.8.
Here's the Fiddle with problem on 1.8.3 + JQM 1.2
Here's the Fiddle without problem on 1.9.1 + JQM 1.2

A: I think it is a bug or feature in jQuery 1.8 + jqm 1.2, it occurs when you have an id containing '
JQuery can't transfer it to a selector of the label correctly and throw the error, you can modify the id to "a[val]" or 'a["val"]', then it's ok.
<input type="text" id='a["val"]' name="a['val']" />

see fiddle


text:
Q: Python- Quicksort program in-place I have a quicksort program here, but there seems to be a problem with the result. I think there must have been some issue in the areas highlighted below when referencing some values. Any suggestions?
#where l represents low, h represents high
def quick(arr,l,h):
    #is this the correct array for quicksorting?
    if len(x[l:h]) > 1:
        #r is pivot POSITION
        r = h
        #R is pivot ELEMENT
        R = arr[r]
        i = l-1
        for a in range(l,r+1):
            if arr[a] <= arr[r]:
                i+=1
                arr[i], arr[a] = arr[a], arr[i]
        #should I take these values? Note that I have repeated elements below, which is what I want to deal with
        quick(arr,l,arr.index(R)-1)
        quick(arr,arr.index(R)+arr.count(R),h)

x = [6,4,2,1,7,8,5,3]

quick(x,0,len(x)-1)

print(x)

A: Please check this. I think you find your answer.
def partition(array, begin, end):
    pivot = begin
    for i in xrange(begin+1, end+1):
        if array[i] <= array[begin]:
            pivot += 1
            array[i], array[pivot] = array[pivot], array[i]
    array[pivot], array[begin] = array[begin], array[pivot]
    return pivot

def quicksort(array, begin=0, end=None):
    if end is None:
        end = len(array) - 1
    if begin >= end:
        return
    pivot = partition(array, begin, end)
    quicksort(array, begin, pivot-1)
    quicksort(array, pivot+1, end)

array = [6,4,2,1,7,8,5,3]
quicksort(array)
print (array)

A:
        #should I take these values? Note that I have repeated elements below, which is what I want to deal with
        quick(arr,l,arr.index(R)-1)
        quick(arr,arr.index(R)+arr.count(R),h)

You seem to be assuming that the values equal to the pivot element are already consecutive. This assumption is probably wrong for your current implementation. Test it e.g. by outputting the full list before recursing.
To make the assumption true, partition into three instead of just two groups, as described at Wikipedia.


text:
Q: CenterX Constraint animation issue I am trying to implement following animation for my application onboarding and it needs to be play forever and reverse back every time it finishes.

I designed following image to accomplish that animation.

The image size is 880x335. So I wrote following code to animate the image.
func startAnimation(with duration: TimeInterval, afterDelay time: TimeInterval, horizontalConstantFirstPosition: CGFloat, horizontalConstantSecondPosition: CGFloat) {
    switch animationOrder {
    case .first:
        self.animatedImageViewAnimatableConstraint.constant = 110
        UIView.animate(withDuration: duration, delay: time, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [.curveEaseOut], animations: {
            self.view.layoutIfNeeded()
            self.animationOrder = .second
        })
    case .second:
        self.animatedImageViewAnimatableConstraint.constant = -110
        UIView.animate(withDuration: duration, delay: time, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [.curveEaseOut], animations: {
            self.view.layoutIfNeeded()
            self.animationOrder = .third
        })
    case .third:
        self.animatedImageViewAnimatableConstraint.constant = -330
        UIView.animate(withDuration: duration, delay: time, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [.curveEaseOut], animations: {
            self.view.layoutIfNeeded()
            self.animationOrder = .fourth
        })
    case .fourth:
        self.animatedImageViewAnimatableConstraint.constant = 110
        UIView.animate(withDuration: duration, delay: time, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [.curveEaseOut], animations: {
            self.view.layoutIfNeeded()
            self.animationOrder = .second
        })
    }
}

Basically, animatedImageViewAnimatableConstraint is the center X constraint that is initialized with 330 which is the position of first image I designed. Every time my animation method is called I changed center x anchor to the positions of value 330, 110, -110, -330 and so on.

However, when I applied it is not animating as expected. It returns back from fourth portion of the image to first one, it is excepted to go from fourth position to second one as shown above.

What should I do for the correct one, or which part is looking like wrong? Thanks in advance.

A:     @IBOutlet weak var imageView: UIImageView!

    let images = [#imageLiteral(resourceName: "img1"), #imageLiteral(resourceName: "img2"), #imageLiteral(resourceName: "img3")]
    imageView.animationImages = images
    imageView.animationDuration = 3.0  //1 sec for each image
    imageView.animationRepeatCount = 0 //Set 0 for infinite
    imageView.startAnimating()

To stop just call
imageView.stopAnimating()


text:
Q: DataGridView doesn't refresh properly I have been having some trouble with a DataGridView in a windows form app. I have it preset with the columns and every so often I need to update the data in the rows. Instead of trying to update each row manually, I just wanted to clear out all the existing rows and add new ones with the new data. My code is as below:
private void RefreshPlayerStatus()
{
    gridPlayers.Rows.Clear();
    List<object[]> playerInfo = game.GetPlayerInfo();
    foreach (object[] info in playerInfo)
       gridPlayers.Rows.Add(info);
    gridPlayers.Refresh();
}

For some reason, the grid is cleared but the new rows do not appear. I've looked at other answers, resetting the dataBindings and sources but that didn't help, guessing because I never use a data source. If anyone has any advice it would be greatly appreciated.
EDIT:
Made the dataGridView bound to the new PlayerInfo class which has all the properties for my view. When running the modified method below, the grid still empties but does not display the new information.
private void RefreshPlayerStatus()
{
    List<PlayerInfo> playerInfo = mafiaGame.GetPlayerInfo();
    gridPlayers.DataSource = playerInfo;
    gridPlayers.Refresh();
}


text:
Q: How to verify that email from own server to google relay SMTP service is using TLS I have a server which only sends mail out, as follows:
django/python --> postfix  ----->  smtp-relay.gmail.com  ----->  destination
When I open a gmail client that received the email, and check the details it says: security:    Standard encryption (TLS) Learn more
Now I suspect its saying from smtp-relay.gmail.com --> gmail destination was TLS, but I am concerned I am sending email in plain text from postfix to smtp-relay.gmail.com.
My postfix configuration file has:
relayhost = smtp-relay.gmail.com:587
However if I set it to:
relayhost = smtp-relay.gmail.com:25
It also works.
This is the tutorial I followed
If I set django settings to EMAIL_USE_TLS = True and try to send an email, it fails with:
 File "/usr/lib/python3.8/smtplib.py", line 755, in starttls
    raise SMTPNotSupportedError(
smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server.

This makes me think its not using TLS, but I don't know how to verify.

A: You want to look at the Received: header of your mail as it was received, the line where Google traces your message being transmitted from your Postfix server to the first Google server. That header should specify the protocol as ESMTPS - the (second) S signalling a secure channel.
There will be another Received: header where your Postfix server notes the receipt of the message from django/python, but if that submission is guaranteed to never leave your machine (connection from ::1 to ::1), it should be of little concern whether that connection employed any transport security.
It is customary to have such trace headers additionally contain information about specific protocol versions and ciphers used (Google appears to do that most of the time).
If you know your mail server is not supposed to send out mail unencrypted - because you exclusively send mail to modern providers, or you are relaying all your mail to Google - consider enforcing that via smtp_tls_security_level in your postfix configuration. Looking at one message only tells you that in this particular instance, everything worked. You may not want it to silently fallback to unencrypted submission in the future.


text:
Q: I am getting a segmentation fault error on my C program I am getting a segmentation fault in one of the following blocks of code, but I suspect it to be this one, xbits.c:
#include <stdio.h>
#include <math.h>

void itox(int n, char hexstring[]);
int xtoi(char hexstring[]);

void itox(int n, char hexstring[]) {
    hexstring[2*sizeof(n) + 1];
    int ratio, remainder;
    int i = 0;
    while(ratio  != 0)
    {

        ratio = n / 16;
        remainder = n % 16;
        if (remainder == 10){
            hexstring[i] = 'A';
            i++;
        }
        else if (remainder == 11){
            hexstring[i] = 'B';
            i++;
        }
        else if (remainder == 12){
            hexstring[i] = 'C';
            i++;
        }
        else if (remainder == 13){
            hexstring[i] = 'D';
            i++;
        }
        else if (remainder == 14){
            hexstring[i] = 'E';
            i++;
        }
        else if (remainder == 15){
            hexstring[i] = 'F';
            i++;
        }
        else
            hexstring[i] = remainder;

    }
    i++;
    hexstring[i] = '\0';
}

int xtoi(char hexstring[]) {
    int i, integer;
    int length = getLength(hexstring);
    for (i = length-2 ; i >= 0 ; i--)
    {
         integer += (int) pow((float) hexstring[i] , (float) i);
    }

    return integer;
}

int getLength (char line[])
{
    int i;

    i=0;
    while (line[i])
        ++i;
    return i;
}

The above relies on a main method, showxbits.c that I have not debugged yet, but when I used a test main method I got a segmentation fault error, and when I use gdb I get the following error.
Program received signal SIGSEGV, Segmentation fault.
0x00000000004007ad in itox ()

Which leads me to believe that the problem is in itox in the above .c file. The program is supposed to convert an int to hex and a hex back to int.

A: You have many errors in your code. You can catch some of them with compiler warnings. Some of them are logical errors, though.

*

*ratio is uninitialised and will contain garbage when you first use it in the while condition. It should probably be initialised to n.

*Your while loop condition will never change (the initial value aside), because ratio will always be n / 16 and n never changes. You probably don't need ratio and can work on n directly.

*When you say hexstring[i] = remainder you don't do what you think you do. You want to assign a digit, but you assign the character with an ASCII code of zero to 9, which are mostly unprintable characters. (Zero even terminates the string.) You want
hexstring[i] = '0' + remainder;

here. You can do the same for letters with 'A'. Note that in the case of a digit you don't increment i, thus overwriting the digit in the next iteration through the loop.

*The lone line
hexstring[2 * sizeof(n) + 1];

doesn't do anything. You must allocate enough memory in the function that calls itox.

*You are writing the letters to the string in the wrong order.

*When you decode, you shouldn't take the hex digits by their ASCII values. You must convert them to their values from 0 to 15.

*don't use the pow function for simple integer arithmetic. Instead, follow the pattern of itox, only the other way round: Muliply the result with 16 and add the value of the next hex digit.

*You can, of course, roll your own strlen and call it getLength, but make sure to provide a prototype before you call it.

*This is a minor issue, but your numbers should proably be unsigned, because there is no hex representation of negative ints.


text:
Q: When I open some websites its being displayed WW2 instead of WWW. Why?
Possible Duplicate:
What does wwws mean?

When I open some websites its being displayed WW2 instead of WWW. What it means and why?

A: www and ww2 are subdomains. They have no special meaning to a browser, other than the fact that they are part of a larger domain. These days, the above subdomains are used mostly on the basis of tradition. Quoting this question on StackOverflow:

People running large(-ish) sites used to do this when they needed to
  break up the load between more than one server. One machine would be
  called www then the next one would be called www2, etc.
Today, much better load balancing solutions are available that don't
  require you to expose your internal machine naming conventions to the
  browser clients.


text:
Q: Filter "either" "or" with dplyr I have a data.frame that looks like this.
dat1=data.frame(time=c(1,2,1,2,1,2,1,2), team=c("A","A","A","A","B","B","C","C"), name=c("LT","LT","CH","CH","CH","CH","AT","AT"))

time team name
 1    A     LT
 2    A     LT
 1    A     CH
 2    A     CH
 1    B     CH
 2    B     CH
 1    C     AT
 2    C     AT

I would like to say to dplyr, please, group_by "team" and filter the rows of each team that contains the name "LT". If a team does not contain the name "LT", then filter in the name "CH."
I would like my data.frame to look like this.
time team name
 1    A     LT
 2    A     LT
 1    B     CH
 2    B     CH

Any help is highly appreciated

A: One dplyr option could be:
dat1 %>%
 group_by(team) %>%
 filter(if(any(name == "LT")) name == "LT" else name == "CH")

   time team  name
  <dbl> <fct> <fct>
1     1 A     LT
2     2 A     LT
3     1 B     CH
4     2 B     CH

A: We can arrange first and then filter based on the first value in 'name' after grouping by 'team'
library(dplyr)
dat1 %>%
     filter(name %in% c("LT", "CH")) %>%
     arrange(team, ordered(name, levels = c('LT', 'CH'))) %>%
     group_by(team) %>%
     filter(name %in% first(name))


text:
Q: CSV Reader Not reading entire file (python) TL;DR - Pulled tweets into a CSV file.  Some contain random invisible escape characters.  CSV reader is "improperly" reading the end of line incorrectly because of this.  What can I do to stop this?
Here is an image of what the line looks like in Notepad++.  The line is much longer than this, but the program treats that black/white "SUB" as End of File, and moves onto the next file in my directory.  http://imgur.com/HfBzS6D

Trying to read in a file thats ~300,000 lines.
I suspected some stuff was missing (only keeping track of a few things, so it was hard to notice at first) so I decided to count the lines as it was reading one of my files.
The program stops after the THIRD of these lines.  This is line 2969, 2970  The last line of the 300,000 processed is 2970.
Processing Row : 2968
['@HillaryClinton', '16196000', 'NA', 'Brian', 'brianwatkins74', '44', '25', 'Virgina Beach, VA', '0', '0', 'Sun Nov 01 02:17:53 +0000 2015', '@HillaryClinton Trump has MORE followers now!!!! :) Sweet!!!!!!!!!!!!!!!!!!', '6.61E+17', '6.60642E+17', 'Twitter Web Client', 'NA', 'NA', 'NA', '1339835893', 'NA']
Processing Row : 2969
['@HillaryClinton', '617660000', 'NA', 'Logan Jackson', 'mischivishlj', '989', '1379', '', '0', '0', 'Sun Nov 01 02:17:46 +0000 2015', 'RT @BookOfTamara: @HillaryClinton @CBSNews this tweet about an article your intern read really shows your dedication to the issue', '6.61E+17', '6.60642E+17', 'Twitter for Android', 'NA', 'NA', 'NA', '1339835893', 'NA']
Processing Row : 2970
['@HillaryClinton', '1224300000', 'NA', '\x80\xb3\xda\x18', 'gingasenki', '5', '1', '', '0', '0', 'Sun Nov 01 02:17:43 +0000 2015', '.@HillaryClinton No TPP for Japan nor the World! #\xfd']

I've examined the whole file in Excel / Notepad++ and don't see anything really out of place.
The code for processing the file is below :
with open(curFile, 'r') as csvFile :
    fileReader = csv.reader(csvFile, delimiter=',')

    header = fileReader.next()

    rowCount = 0

    for row in fileReader :

        ## Get the index of the UserID_str

        userID_str_index = header.index("userID_str")

        ## Obtain the userID_str

        userID_str = row[userID_str_index]

        listOfIDs[candidateCount].append(userID_str)

Only thing I removed was some if/then's that were for error testing which line was causing the stop.
All this is supposed to do is go through all 300,000 lines, and store into a list-of-lists the userID of the current line.
Edit1 : Had python print out the last line it processed, so you can see how python itself printed it, rather than how it looked in my CSV file.
Processing Row : 2970
['@HillaryClinton', '1224300000', 'NA', '\x80\xb3\xda\x18', 'gingasenki', '5', '1', '', '0', '0', 'Sun Nov 01 02:17:43 +0000 2015', '.@HillaryClinton No TPP for Japan nor the World! #\xfd']

EDIT2: To clarify, this did not error out. It just stopped processing the file, as if it had reached the end! I had it print out each row / the number of the row as it processed through it.  It hits this row (the 2nd one printed above) #2970 according to it, and then no more.  Confirmed theres around 298,000 more for it to go through.


text:
Q: Google Analytics filter to combine /home.aspx and / the following urls are the same page, I'd like it to be recognized as the same page in Google Analytics. What filter do I create so it's not replicated?
/contact/home.aspx
&
/contact/

A: A simple search and replace filter should do that for you:

*

*create a new filter > search and replace

*select the filter field Request URI

*in the search string field /contact/home\.aspx

*in the replace string field add /contact/
Screenshot:


text:
Q: columns not found by java mariadb connection i'm using java to insert some data into a mariadb database, but when i execute the statement, i receive an error
Unknown column 'SCHEDETYPE' in 'field list'
java.sql.SQLSyntaxErrorException: (conn=84) Unknown column 'SCHEDETYPE' in 'field list'

but in my db the columns exists.
i tried to extract the column names through this code:
            ResultSetMetaData rsMetaData = rs.getMetaData();
            int numberOfColumns = rsMetaData.getColumnCount();

            // get the column names; column indexes start from 1
            for (int i = 1; i < numberOfColumns + 1; i++) {
              String columnName = rsMetaData.getColumnName(i);
              // Get the name of the column's table name
              String tableName = rsMetaData.getTableName(i);
              System.out.println("column name=" + columnName + " table=" + tableName + "");
            }

but i'm returning only 6 columns from db
column name=id
column name=label
column name=user_id
column name=submitted
column name=created_at
column name=updated_at

where is the problem??
thank you
my query
final String query = "INSERT INTO test.sc_test "
                    + "(LABEL, SCHEDETYPE,SCHEDECURRENT,user_id,submitted,is_hibernated,bad_formed,is_valid,"
                    + "start_hibernation,namespaces,created_at,updated_at) "
                    + "VALUES(?,?,?,?,null,0,?,?,365,?,?,null)";

            java.sql.PreparedStatement prest = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);

            prest.setString(1, cst.getLabel());
            prest.setString(2, cst.getSchedeType());
            prest.setString(3, cst.getSchedeCurrent());
            prest.setInt(4, cst.getUser_id());
            prest.setInt(5, cst.getBad_formed());
            prest.setInt(6, cst.getIs_valid());
            prest.setString(7, namespaces);
            prest.setTimestamp(8, ts);
            prest.executeUpdate();

from db
field,type,null,key,default,extra
'id', 'int(11) unsigned', 'NO', 'PRI', NULL, 'auto_increment'
'label', 'varchar(100)', 'NO', '', NULL, ''
'SchedeType', 'varchar(45)', 'YES', '', NULL, ''
'SchedeCurrent', 'varchar(100)', 'YES', '', NULL, ''
'user_id', 'int(11)', 'YES', '', NULL, ''
'submitted', 'timestamp', 'YES', '', NULL, ''
'is_hibernated', 'int(1)', 'NO', '', '0', ''
'bad_formed', 'int(1)', 'NO', '', '0', ''
'is_valid', 'int(1)', 'NO', '', '0', ''
'start_hibernation', 'int(4)', 'NO', '', '365', ''
'namespaces', 'varchar(100)', 'NO', '', 'gml,xsi,xlink', ''
'created_at', 'timestamp', 'YES', '', 'current_timestamp()', ''
'updated_at', 'timestamp', 'YES', '', NULL, ''


text:
Q: jQuery autocomplete multivalue field like the Google search field I want to implement a jQuery suggestion multivalue field for the search functionality of my site without comma separated values, but values separated by spaces as Google does.
The field will get a suggestion to complete the word that the user is writing: a search multivalue field.
Any idea?

A: Do you mean something like this: http://aehlke.github.com/tag-it/


text:
Q: CRON isn't working in Amazon EC2? Another article describes that a way to test if cron is running is to create a crontab -e with this script:
* * * * * /usr/bin/uptime > /tmp/uptime

When i go check on the cron cat /tmp/uptime there is no result. The same goes with a test script with a direct path to php.
I'm running AWS running Amazon Linux.
I checked to see if cron was even running with chkconfig --list crond
result:
crond           0:off   1:off   2:on    3:on    4:on    5:on    6:off

UPDATE (based on comments)
[ec2-user@ip-xxx-xxx ~]$ service crond status
crond (pid  2844) is running...
[ec2-user@ip-xxx-xxx ~]$ ps aux | grep crond
root      2844  0.0  0.2 121636  2572 ?        Ss   Sep04   0:01 crond
ec2-user  7904  0.0  0.2 110468  2096 pts/0    S+   22:46   0:00 grep --color=auto crond

Just to be safe I manually started cron with this command:
sudo service crond start

I've also tried sudo su and created instances both in ec2-user and root. Nothing seems to actually run the cron.
Does anyone have any suggestions? It seems that the docs on Cron elsewhere are several years old. Thanks in advance.
Reference:
Setting Up Cron in Amazon Linux AMI

A: have you check the cron daemon status ?
$ service crond status
crond (pid xxx) is running...
$ ps aux | grep crond
root      2533  0.0  0.1 119552  1784 ?        Ss   Apr04   1:57 crond
ec2-user 22203  0.0  0.2 110460  2084 pts/0    S+   09:37   0:00 grep --color=auto crond

then, if cron daemon seems not running you can start it
$ service crond start

A: Verify that procps package is installed (that package provides uptime command)
sudo yum install procps

Also verify that your cron job is saved
crontab -l

A: Do the following:
sudo service crond reload
or
sudo service crond restart
This could happen to VPS server, after you do the crontab modification, you might need to reload it in order for the modification to take place. In the worse case scenario, the crond restart will stop the service and start it again. Hope that helps.

A:      [ec2-user@ip-172-31-47-191 ~]$ sudo crontab -l
no crontab for root
[ec2-user@ip-172-31-47-191 ~]$ sudo crontab -e
no crontab for root - using an empty one
crontab: installing new crontab
[ec2-user@ip-172-31-47-191 ~]$ sudo crontab -l
* * * * * /usr/bin/uptime > /tmp/uptime

[ec2-user@ip-172-31-47-191 ~]$ /usr/bin/uptime
 23:05:09 up 284 days, 12:52,  1 user,  load average: 0.01, 0.02, 0.05
 [ec2-user@ip-172-31-47-191 ~]$ ls -l /tmp
total 4
drwx------. 2 oracle dba   6 Sep  7 11:03 mc-oracle
drwx------. 2 root   root  6 Sep  7 11:01 mc-root
-rw-r--r--. 1 root   root 71 Sep 14 23:05 uptime
 [ec2-user@ip-172-31-47-191 ~]$ more /tmp/uptime
 23:05:01 up 284 days, 12:52,  1 user,  load average: 0.01, 0.02, 0.05
 [ec2-user@ip-172-31-47-191 ~]$  service crond status
Redirecting to /bin/systemctl status  crond.service
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2017-04-20 03:07:03 EDT; 4 months 26 days ago
 Main PID: 16998 (crond)
   CGroup: /system.slice/crond.service
           └─16998 /usr/sbin/crond -n

Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.
[ec2-user@ip-172-31-47-191 ~]$ 191 ~]$

A: Check /var/log/cron logfile to verify if your command in running.


text:
Q: rbenv irb history is not saving I install ruby via rbenv-installer.
When I use irb console, I can use history by pressing up and down on keyboard. And when I exited from console and start it again, I can't use prewious history. When I press up-arrow-button, nothing was happened.
When I used rvm this option was working. How can I switch on it in rbenv?

A: I found this way for solving my problem. In file ~/.irbrc write:
require 'irb/ext/save-history'
#History configuration
IRB.conf[:SAVE_HISTORY] = 100
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"

Found in this question: irb history not working

A: Create ~/.irbrc if it does not exist, and add the following line to it:
IRB.conf[:SAVE_HISTORY] = 1000


text:
Q: JQuery is not working on input tag if Angularjs ng-repeat is used I'm using angularjs with asp.net core 2.2. The jQuery in the theme which i am using is conflicting with the angularjs. when angular removed, jQuery works fine. I am placing bootstrap select in ng-repeat, it does not work.
When angularjs ng-repeat on table is removed, all jQuery elements work properly otherwise not.
This is my HTML Code

                Suit Information

                                    <input type="checkbox"
                                           ng-model="selectedAll"
                                           ng-click="CheckAll()">

                            Suit Type
                            Quantity
                            Stitching Price
                            Receiving Date
                            Delivery Date

                                    <input type="checkbox" ng-model="item.selected">

                                    <select class="form-control kt-selectpicker" title="Brand" data-style="btn-brand">
                                        <option>Mustard</option>
                                        <option>Ketchup</option>
                                        <option>Relish</option>
                                    </select>
                                    Please select Suit Type

                                <input id="" type="number" min="0" class="form-control" value="0" name="demo1" placeholder="Price">
                                Please enter Quantity

                                <input id="" type="number" min="0" class="form-control" value="0"
                                       name="demo1" placeholder="Price">
                                Please enter stitching price

                                    <input type="date" class="form-control" placeholder="Select date" id="" />

                                    <input type="date" class="form-control" placeholder="Select date" id="" />

                <input ng-hide="!SuitList.length" type="button" class="btn btn-danger pull-right" ng-click="Remove()" value="Remove Selected">
                <input type="button" class="btn btn-primary addnew pull-right" value="Add New" ng-click="AddNew()" style="margin-right:3px">

This is jQuery code
var KTBootstrapSelect = function () {
    var demos = function () {
        // minimum setup
        $('.kt-selectpicker').selectpicker();
    }

    return {
        // public functions
        init: function() {
            demos();
        }
    };
}();

jQuery(document).ready(function() {
    KTBootstrapSelect.init();
});

This is Angular JS code
$scope.AllowAddNewRow = true;
$scope.selectedAll = false;

$scope.AddNew = function () {
    if ($scope.SuitList.length == 0) {
        $scope.SuitList.push({
            'Suit_Id': 0,
            'SuitType_Id': 0,
            'Suit_Quntity': 0,
            'Suit_Stiching': 0,
            'Order_Receiving_Date': "",
            'Order_Delivery_Date': "",
        });
    }
    for (var i = 0; i < $scope.SuitList.length; i++)
    {
        if ($scope.SuitList[i].Suit_Quntity == 0 || $scope.SuitList[i].Suit_Stiching == 0 || $scope.SuitList[i].Order_Receiving_Date == "" || $scope.SuitList[i].Order_Delivery_Date == "")
        {
            $scope.AllowAddNewRow = false;
            return;
        }
        else
            $scope.AllowAddNewRow = true;
    }
    if ($scope.AllowAddNewRow == true) {
        $scope.SuitList.push({
            'Suit_Id': 0,
            'SuitType_Id': 0,
            'Suit_Quntity': 0,
            'Suit_Stiching': 0,
            'Order_Receiving_Date': "",
            'Order_Delivery_Date': "",
        });
    }
};

I expected multiple rows with jQuery functionality but can't get.

A: you need to create a angularjs directive to initialize the selectpicker like this
angular.module('app').directive("ktSelectpicker", [
        () => {
            return {
                restrict: "C",
                link: ($scope, element) => {
                    $(element).selectpicker();
                }
            }
        }
    ])

replace 'app' with your module name


text:
Q: Django Braces' "JSONResponseMixin" shows weird behavior I'm trying to use the "JSONResponseMixin" from the Django-braces package.
The mixin:
class JSONResponseMixin(object):
    """
    A mixin that allows you to easily serialize simple data such as a dict or
    Django models.
    """
    content_type = u"application/json"
    json_dumps_kwargs = None

    def get_content_type(self):
        if self.content_type is None:
            raise ImproperlyConfigured(
                u"%(cls)s is missing a content type. "
                u"Define %(cls)s.content_type, or override "
                u"%(cls)s.get_content_type()." % {
                u"cls": self.__class__.__name__}
            )
        return self.content_type

    def get_json_dumps_kwargs(self):
        if self.json_dumps_kwargs is None:
            self.json_dumps_kwargs = {}
        self.json_dumps_kwargs.setdefault(u'ensure_ascii', False)
        return self.json_dumps_kwargs

    def render_json_response(self, context_dict, status=200):
        """
        Limited serialization for shipping plain data. Do not use for models
        or other complex or custom objects.
        """
        json_context = json.dumps(context_dict, cls=DjangoJSONEncoder,
                                  **self.get_json_dumps_kwargs())
        return HttpResponse(json_context,
                            content_type=self.get_content_type(),
                            status=status)

    def render_json_object_response(self, objects, **kwargs):
        """
        Serializes objects using Django's builtin JSON serializer. Additional
        kwargs can be used the same way for django.core.serializers.serialize.
        """
        json_data = serializers.serialize(u"json", objects, **kwargs)
        return HttpResponse(json_data, content_type=self.get_content_type())

I am basically inheriting this mixin into my own view to return a JSON response to javascript call back function.
Here is my view:
views.py
class PostDetail(JSONResponseMixin, DetailView):
    model = Post
    template_name = 'post_detail_page.html'

So this is a really really simple view... yet when I open this view, weird thing happens. The page shows plain html source code instead of rendering the source into html page. Of course, this doesn't happen once I remove the JSONResponseMixin inheritance in my view. I have no idea why this is happening, since JSONResponseMixin doesn't directly override the "render_to_response" method or anything important....
Can someone tell me why this is happening..? Thanks!!!
Btw, this is the resulting html page:
<html>
    <head>
        <link title="Wrap Long Lines" href="resource://gre-resources/plaintext.css" type="text/css" rel="alternate stylesheet">
        #HAVE NO IDEA WHERE THIS CAME FROM...
    </head>

    <body>
        #ALL MY HTML SOURCE CODE APPEARS HERE WITHOUT BEING RENDERED!!!
    </body>
</html>

A: content_type = u"application/json"

This line is actually used by DetailView. My best guess is that this messed up your template's rendering; either by using "application/json" or by not supplying a charset.
I would leave the default content_type alone (use content_type = None) and override get_content_type to supply the content type you need when using Ajax.
To fully incorporate JSON into your view, you should probably overwrite render_to_response on your PostDetail view:
class PostDetail(JSONResponseMixin, DetailView):
    model = Post
    template_name = 'post_detail_page.html'
    content_type = None

    def render_to_response(self, **kwargs):
        if self.request.is_ajax():
            # Don't really know if objects will take a list, a queryset, any iterable or even a single object
            return self.render_json_object_response(objects=[self.object]):
        else:
            return super(PostDetail, self).render_to_response(**kwargs)

    def get_content_type(self):
        if self.request.is_ajax():
            return u'application/json'
        else:
            return None


text:
Q: Iterate over several lists with different conditions in python Task: A moving object measures some parameters per second, which should be compared with measurements from ten stationary objects that measures every 10 min.
Conditions: The moving object should be in the range of 100 meters from one of the stationary objects, and in time a +-5 min difference between the moving and stationary measurement, to be able to compare the parameters.
Lists: time_m, time_s, lon_m, lat_m, lon_s, lat_s, param1_m, param1_s, param2_m, param2_s, etc.   (m for moving and s for stationary (all measurements from the ten stationary objects are in the same list))
Problem: Since the lists have about 10^5 measurements each my solution with two for loops and two if statements takes way too long time. Please, can you help me solve this in a better way?
My solution:
dt_m = [datetime.datetime.strptime(item, '%Y-%m-%dT%H:%M:%S') for item in time_m]
dt_s = [datetime.datetime.strptime(item, '%Y-%m-%dT%H:%M:%S') for item in time_s]
d = datetime.timedelta(minutes=5)
lon_hundred_m = 0.00180 #lon degrees for 100 m at lat 60
lat_hundred_m = 0.00090 #lat degrees for 100 m

for i in range(len(lon_m)):
    for j in range(len(lon_s)):
        if lon_m[i] >= (lon_s[j]-lon_hundred) and lon_m[i] <= (lon_s[j]+lon_hundred) and lat_m[i] >= (lat_s[j]-lon_hundred) and lat_m[i] <= (lat_s[j]+lon_hundred):
            if dt_s[j] >= dt_m[i]-d and dt_s[j] <= dt_m[i]+d:
                time_m_2.append(time_m[i])
                param1_m_2.append(param1_m[i])
                param2_m_2.append(param2_m[i])
                lon_m_2.append(lon_m[i])
                lat_m_2.append(lat_m[i])
                time_s_2.append(time_s[j])
                param1_s_2.append(param1_s[j])
                param2_s_2.append(param2_s[j])
                lon_s_2.append(lon_s[j])
                lat_s_2.append(lat_s[j])

Thanks!

A: One solution could to keep lists sorted and use bisect to find lon_m items for element in lon_s. That will reduce n^2 to n*logn. More sophisticated version would to use r-trees (there is some Python implementation here).
A side comment: x >= A and x <= B is usually written as A <= x <= B in Python).


text:
Q: how to get other column when we use distinct in mysql query When I use Distinct function in mysql query then I can get only one column from the table.  This is example query that I am using:
SELECT DISTINCT (subcategory.title), common_cat. * FROM `subcategory`
LEFT JOIN common_cat ON ( subcategory.title = common_cat.ctitle )

It returns records as below :
      title     mid     wid     ctitle
      Tops           17       5     Tops
      Dresses   NULL    NULL    NULL
      Pants/Shorts  18  6   Pants/Shorts
      Skirts    NULL    NULL    NULL
      Swimwear  24  8   Swimwear
      Outerwear     21  9   Outerwear

In above data  "Title" field coming from subcategory table.Now I also want to get id column
from subcategory table. How I can get this.

A: DISTINCT works by getting all the data of the columns you mentioned in a table row and then filtering out the duplicate rows and showing the unique rows with same values in ALL columns.
As such you can simply add the column subcategory.id to the column list and it will work.
SELECT DISTINCT subcategory.title, subcategory.id, common_cat.* FROM `subcategory`
JOIN common_cat ON ( subcategory.title = common_cat.ctitle )

Please note, in a distinct command it is not recommended to use * to pickup all columns as the more the number of columns in the query the more the load on the database server and hence a slower output. You may want to mention only the column names required in the distinct list and remove the common_cat.* from the query.


text:
Q: Comparison between current and voltage sensitivity Current sensitivity of a galvanometer is defined as deflection per unit current, $$\frac{\phi}{I}=\frac{NAB}{k}$$
Here, $\phi$ is the angular deflection, k is the torsional constant of the spring, and NAB is the magnetic torque per unit current produced in the galvanometer (MCG).
According to my book: A convenient way for the manufacturer to increase the current sensitivity is to increase the number of turns, N.
My problem: I can't understand the practicality of the current sensitivity. Suppose if we increase N two times the original value of a given galvanometer. It is likely that the resistance will also get doubled, thus the current would also get halved just like in the case of galvanometer turned voltmeter.
So, if I were to measure current using the galvanometer turned ammeter, for a normal current, say 1 A, it would have no significant effect on its angular deflection for if we double the number of turns the resistance would also get doubled and the normal current flowing through the galvanometer  will also get halved giving the same value of angular deflection.

A: When an ammeter is used we usually try to ensure that the resistance of the ammeter is small compared to the resistances of the other elements in the circuit. We try to do this so that including the ammeter in the circuit changes the behaviour of the circuit as little as possible.
So if the resistance of the ammeter is negligible it remains negligible when doubled. However you are correct that there is a limit. If we raise the resistance of the ammeter too far it will start to significantly affect the circuit we are using the ammeter to examine.
Response to comment:
Suppose the ammeter resistance is $r$ and the full scale deflection current is $i$. I won't go through the working, but with a shunt resistor $R$ the full scale deflection current is given by:
$$ I_{fs} = i\left(1 + \frac{r}{R}\right) $$
If we're interested in measuring small currents then we don't use a shunt resistor so we get:
$$ I_{fs} = i $$
and the only way to make our meter more sensitive is to reduce $i$ by using more windings on the coil. I assume this is the point of increasing the windings.
If we're measuring large currents then $r/R \gg 1$ and our equation becomes approximately:
$$ I_{fs} \approx \frac{ir}{R} $$
As you say, $ir$ will be constant because increasing the number of windings decreases $i$ but increases $r$. In this case you're quite correct that there is no point in changing the number of windings.

A: The current sensitivity is simply the deflection per unit current, so if we double the number of the turns, it will also double the resistance. But not half the current still we not connect it to a battery (or apply any constant potential difference). Suppose we connect the given galvanometer turned ammeter in the circuit ($I=\frac{V}{R}$) the current becomes $I=\frac{V}{R}+r$. Here $r$ is negligible, so no change whether be doubled or halved not change the current appreciably but change the deflection angle.


text:
Q: Is using assign() to deal with a scoping problem a problem? When contained inside a custom function, RVAideMemoire::Anova.clm
does not find the 'df1' data object that was passed to ordinal::clm (It would seem
because it searches for 'df1' in the global environment):
library(ordinal)
library(RVAideMemoire)

set.seed(1)
df <- data.frame(x = factor(sample(1:2, 100, replace=TRUE)),
                 y = factor(sample(1:5, 100, replace=TRUE), ordered=TRUE))

clm_function <- function(dv, gv, df1){
  model <- ordinal::clm(as.formula(paste0(dv, " ~ ", gv)), data = df1)
  result <- RVAideMemoire::Anova.clm(model, type = "II")
  return(result)
}

clm_function(dv = "y", gv = "x", df1 = df)

Error in is.data.frame(data) : object 'df1' not found

One can sidestep this error by using assign to put 'df1' in the global
environment temporarily:
clm_function_alt <- function(dv, gv, df1){
  assign("df1", df1, envir=globalenv()) # ASSIGN HERE
  model <- ordinal::clm(as.formula(paste0(dv, " ~ ", gv)), data = df1)
  result <- RVAideMemoire::Anova.clm(model, type = "II")
  rm(df1, pos = 1) # REMOVE HERE
  return(result)
}

clm_function_alt(dv = "y", gv = "x", df1 = df)

LyzandeR's answer in this post implies that assigning 'df1' to the global environment outside the function is the way to go.
But I am wondering if there something potentially problematic with using assign from inside a function, like I have shown?
If so, is there a way to instruct  RVAideMemoire::Anova.clm to search for 'df1' in the execution environment?


text:
Q: Some classes could not be instantiated in AndroidStudio I am new to the Android Language but i am familiar with the other programming languages.Today when i wanted to start building my first app from here,when i created the project with the Android Studio i get this error massage:
Rendering Problems The following classes could not be instantiated:
- android.support.design.widget.CoordinatorLayout (Open Class, Show Exception, Clear Cache)
- android.support.design.widget.AppBarLayout (Open Class, Show Exception, Clear Cache)
Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE  Exception Details java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.
at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:34)
at android.support.design.widget.CoordinatorLayout.<init>(CoordinatorLayout.java:184)
at android.support.design.widget.CoordinatorLayout.<init>(CoordinatorLayout.java:178)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.android.layoutlib.bridge.android.BridgeInflater.loadCustomView(BridgeInflater.java:205)
at com.android.layoutlib.bridge.android.BridgeInflater.createViewFromTag(BridgeInflater.java:133)
at android.view.LayoutInflater.inflate(LayoutInflater.java:385)   at android.view.LayoutInflater.inflate(LayoutInflater.java:296) Copy stack to clipboard

i try some of the solutions in the other stack questions but the problem does not solved.what should i do?

A: Looks like the answer is right there in your stack trace:
You need to use a Theme.AppCompat theme (or descendant) with the design library.
Try following the instructions in here:
You need to use a Theme.AppCompat theme (or descendant) with this activity


text:
Q: How to get the maximum safest integer of a Double in Java Having in mind that Java's doubles are
double-precision floating-point numbers.
And the maximum integer without loosing precision is 9007199254740991 or 253-1
Is there any clean way of getting this value?
For instance, like a constant as in JavaScript's MAX_SAFE_INTEGER

A: There is an internal JDK class named sun.misc.DoubleConsts which has some constants that you could use to generate the value you're looking for using the "accpetable" magic numbers of 1 and 2, but it doesn't have the number defined itself.
public static long MAX_SAFE_VALUE =
        sun.misc.DoubleConsts.SIGNIF_BIT_MASK * 2 + 1;

// alternatively
public static long MAX_SAFE_VALUE =
        Math.pow(2, sun.misc.DoubleConsts.SIGNIFICAND_WIDTH) - 1;

However, relying on a class in the sun.misc package is not a very "clean" approach, so I'd just create my own constant.


text:
Q: newid() as column default value I have a table with a uniqueidentifier column.
What is the Default Value or Binding i should set in order for each new row to generate a new uniqueidentifier?
Setting the default to newid() always returns 00000000-0000-0000-0000-000000000000
EDIT:
Apparently i got it all wrong, the insert was done from Entity Framework, and it doesn't handle this scenario.
Entity Framework - default values doesn't set in sql server table

A: newid() should work.
See images below:

You have another issue there.


text:
Q: How to append an uploaded file name? I have a problem appending the imageNameArray where it is suppose to display file names which have been uploaded.
The problem is that lets say I previously uploaded 3 files (cat.png, dog.png and pig.png), when I refresh page and upload another file (panda.png), then when I upload the file, it should display 'panda.png'. But instead it is just appending the name of the previously uploaded file (pig.png) and it does not append panda.png.
IT DISPLAYS:
pig.png

IT SHOULD BE:
panda.png

If I upload another file (not refreshing page) such as monkey.png, then again it appends pig.png. No monkey.png.
IT DISPLAYS:
pig.png
pig.png

IT SHOULD BE:
 panda.png
 monkey.png

How can the code below be fixed so that it appends the file names as it should do above?
Below is the javascript code where the appending occurs:
    <?php
    session_start();

    $idx = count($_POST ['fileImage']) -1 ;
    $output = isset($_POST ['fileImage'][$idx]) ? $_SESSION ['fileImage'][$idx]['name'] : "";

    ?>

              function stopImageUpload(success){

              var imageNameArray = ['<?php echo $output ?>'];
              var result = '';

              if (success == 1){
                 result = 'The file was uploaded successfully!

';

                    for(var i=0;i<imageNameArray.length;i++)
            {
                 $('.listImage').append(imageNameArray[i]+ '
');

             }

              }
              else {
                 result = 'There was an error during file upload!

';
              }

        return true;

        }

Below is the php script where it uploads a file which is on another page from the javascript function above:
        <?php

            session_start();

            $result = 0;
            $errors = array ();
            $dirImage = "ImageFiles/";

        if (isset ( $_FILES ['fileImage'] ) && $_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {

        $fileName = $_FILES ['fileImage'] ['name'];

        $fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
        $fileExt = strtolower ( $fileExt );

        $fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;

                if (count ( $errors ) == 0) {
                    if (move_uploaded_file ( $fileTemp, $fileDst )) {
                        $result = 1;

                    }
                }

            }

    $_POST ['fileImage'][] = array('name' => $_FILES ['fileImage']['name']);

            ?>

A: why you useing Session?
try to add session_destroy(); in the end of the second script and the first one.
I think its should delete all the previos data and then you know more whats the problem.


text:
Q: How can I create tables on aws dynamodb https://www.npmjs.com/package/dynamodb
I tried to implement something like this URL. But it's not working.
There is no response.
Who can help me?
This is my code.
var dynamo = require('dynamodb');
var Joi = require('joi');

dynamo.AWS.config.update({
  accessKeyId: AWS_ACCESS_KEYID,
  secretAccessKey: AWS_SECRET_ACCESS_KEY,
  region: AWS_REGION,
  endpoint: AWS_DYNAMODB_ENDPOINT
});

var Account = dynamo.define('Account', {
  hashKey : 'email',

  // add the timestamp attributes (updatedAt, createdAt)
  timestamps : true,

  schema : {
    email   : Joi.string().email(),
    name    : Joi.string(),
    age     : Joi.number(),
    roles   : dynamo.types.stringSet(),
    settings : {
      nickname      : Joi.string(),
      acceptedTerms : Joi.boolean().default(false)
    }
  }
});

dynamo.createTables(function(err) {
  if (err) {
    console.log('Error creating tables: ', err);
    res.json({message: 'Create table error'});
  } else {
    console.log('Tables has been created');
    res.json({message: 'Create table success'});
  }
});

A: You are referencing a non AWS site. This JavaScript use case, along with many more, is available in the Official AWS Github repo here:
https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/dynamodb/ddb_createtable.js


text:
Q: Three questions about intuitionistic logic If $A$ is a theorem of classical logic, is it the case that $\neg \neg A$ is a theorem of intuitionistic logic? And secondly, if $A  \to B$ is a theorem of classical logic, is $\neg B \to \neg A$ a theorem of intuitionistic logic. Third, is $\neg A \vee \neg \neg A$ a theorem schema of intuitionistic logic?

A: The answer to the first question,

If $A$ is a theorem of classical logic, is it the case that $\lnot \lnot A$ is a theorem of intuitionistic logic?

is "yes" when we are talking about propositional logic. This is a very classical result of Glivenko.
For first-order logic, it is not enough to merely preface the formula with two negations. However, there are a number of so-called negative translations that accomplish a similar thing in a more complicated way: to each first-order formula $\phi$ is associated another formula $\phi^*$ such that if $\phi$ is provable in classical first-order logic then $\phi^*$ is provable in intuitionistic first-order logic.
This use of negative translations is very well studied in proof theory, and is a standard method that has become commonly used. However, there is no truly accessible literature on proof theory. The Wikipedia article linked above has some graduate-level references.

A: For an intuitionistically valid proof of $A \to B \vdash \lnot B \to \lnot A$ with Natural Deduction :
1) $A \to B$ --- premise
2) $\lnot B$ --- assumed [a]
3) $A$ --- assumed [b]
4) $B$ --- from 1) and 3) by $\to$-elimination
5) $\bot$ --- from 2) and 4) by $\to$-elimination : $\lnot B$ is an abbreviation for : $B \to \bot$
6) $\lnot A$ --- from 3) and 5) by $\to$-introduction, discharging [b]

7) $\lnot B \to \lnot A$ --- from 2) and 6) by $\to$-introduction, discharging [a].

Nowhere in the derivation we have used Exluded Middle, nor Double Negation; thus, the proof is intuitionistically valid.
Now the issue is :

if $\vdash_K A \to B$, then $\vdash_J ¬B \to ¬A$ or not ?

Whe can apply the Gödel–Gentzen translation to $⊢_K A \to B$ and we have that : $⊢_J ¬¬A \to ¬¬B$.
But this is simply a "double contraposition"; thus, it seems that $⊢_J ¬B \to ¬A$.

Regarding $\lnot A \lor \lnot \lnot A$, it is not intuitionistically provable.
The counter-example with Kripke semantics is a structure with three nodes : $0,1,2$ such that $0 \le 1$ and $0 \le 2$, where $A$ holds only in $1$ (i.e. $1 \Vdash A$).
We have that $2 \Vdash \lnot A$, and thence, by the semantical clause : $k \Vdash \lnot A$ iff for all $k' \ge k : (k' \nVdash A)$ :

$0 \nVdash \lnot \lnot A$.

But since $1 \Vdash A$, also $0 \nVdash \lnot A$, and thus :

$0 \nVdash \lnot A \lor \lnot \lnot A$.


text:
Q: OleDbDataReader inside a OleDbDataReader I have 2 Tables. I want to get all ID's from Table1, and while I am inside the frist OleDbCommand I want to check if the ID is in Table2 too.
I tried this:
using (OleDbCommand cmd = new OleDbCommand("SELECT ID FROM Table1 WHERE NAME=:NAME)
{
 ............
   decimal dId = (decimal)odr["ID"];
   using (OleDbCommand cmdE = new OleDbCommand("SELECT LOGID FROM Table2 WHERE ID:=ID", con))
   cmdE.CommandType = CommandType.Text;
   cmdE.Parameters.Add(new OleDbParameter("ID", dId));
   decimal cId=-1;
   using (OleDbDataReader odrE = cmdE.ExecuteReader())
   {
    while (odrE.Read())
    {
     cId = (decimal)odrE["ID"];
    }...............

The Problem is that
 cId = (decimal)odrE["ID"];

is never executed, even though if I do a manaul Select inside the Sql Developer i get results. What am I doing wrong?

A: That's the wrong syntax for parameters in OLEDB. Try
using (OleDbCommand cmdE = new OleDbCommand("SELECT LOGID FROM Table2 WHERE ID=@ID", con))

A: I think the problem is using a OleDbCommand inside a OleDbCommand. Using a OUTER JOIN solved the problem. Thank you


text:
Q: Firefox downloads text/plain instead of showing it I have a plain text page with some binary data (most data is text) in it like "\003" etc. I set the Content-Type header to text/plain and set the X-Content-Type-Options to nosniff. This stops Google Chrome and Internet Explorer from downloading the page and are instead showing it. But firefox for some reason decides that the page needs to be downloaded.
header("content-type: text/plain; charset=UTF-8");
header("X-Content-Type-Options: nosniff");
header("Content-Disposition: inline");

What header has to be added to stop firefox from downloading a page and instead showing it?
EDIT:
I've tried Content-Disposition: inline
An example: http://nnmm.nl/?5eT0D

A: I fixed it by setting the following headers:
header("content-type: text/plain; charset=UTF-8; imeanit=yes");
header("X-Content-Type-Options: nosniff");

A: Can you post a more complete test case?  I wasn't able to reproduce this problem in Firefox 29 using a sample PHP file with the same two headers and "\003" included in the output.
Update: Firefox does not support X-Content-Type-Options, though there is a long-standing request in bug 471020 and some work started on it last year.  As far as I know, until that bug is fixed there is no way to override Content-Type sniffing for text/plain files in Firefox.
What do you expect the browser to display for the non-printable characters in the document?  Can you get the results you want by stripping out the control characters on the server before sending the document to the browser?


text:
Q: Retaining string style on html page I am fetching a string from database side ,with proper line change and all .My string looks like given below when I see on debug both on java end as well as browser console . But when I print it on UI ,it is shown as a single line string like Email Request To: FedEx Legal; FedExEmailTeam Subject: Approval request to send email as transactional Attachment: <customer email creative> .Why and how can I resolve this .
My string -
  Email Request
    To: FedEx Legal; FedExEmailTeam
    Subject: Approval request to send email as transactional
    Attachment:customer email creative

My UI code-
<f:facet name="body">

                 <ice:panelGroup style="margin-top: 2%;">

                                <ice:panelGrid columns="1" border="0">
                                    <ice:outputText
                                        value="#{campaignTrackingCodesBean.emailTransPanel}"></ice:outputText>
                                </ice:panelGrid>

                </ice:panelGroup>

        </f:facet>

A: try using
 tag inside the place you wish to conserve the text format

    <ice:outputText value="#{campaignTrackingCodesBean.emailTransPanel}"> </ice:outputText>


text:
Q: Android - How to save highscore of double value? I have a double value which is in the range of 0-1. The new highscore value should be the lesser value of the two. Basically for example: if user A had a previous highscore of 0.6, and he just scored 0.4, the new highscore should be 0.4. Please be descriptive as I'm a beginner, thank you.
EDIT: Sorry I didn't make it descriptive enough, but I want the highscore to be saved and be able to be accessed again. So, if the user exits the app and revisits, it still shows the highscore.

A: It sounds like you'll want to use Shared Preferences to store the value for later: http://developer.android.com/training/basics/data-storage/shared-preferences.html, and then check this when you go to save it.
Here is sample code so you can call writeHighScore(score),  and it will save it if it is lower than the previously saved high score:
void writeHighScore(float score)
{
    if (score < getOldHighScore())
    {
        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putFloat("highscore", score);
        editor.commit();
    }
}

float getOldHighScore()
{
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    return sharedPref.getFloat("highscore", 1);
}

I used a float here instead of a double. If you want to store a double with shared preferences, you'll need to convert it to and from a Long, like here: Can't put double SharedPreferences


text:
Q: ExtJS DOM handling for XMLHTTPRequest.repsonseXML I'd like to use the Ext.Element object interface from ExtJS to traverse an XML response which I get from a AJAX request like this:
  loadModel: function() {
        console.log('Load Model....');
        var conn = new Ext.data.Connection;
        conn.request({
            url: 'partsV10.xml',
            callback: function(options, success, response) {
                if (success) {
                    var modelDom = response.responseXML.documentElement;
                    this.buildUi(modelDom)
                    this.getDasPanel().doLayout();
                }
            },
            scope: this
        });
    }

Which works pretty well. After getting the repsonse from the AJAX request, from my understanding, I have two possible ways to continue with my data:

*

*Use the standard JavaScript functions in a way like this:
buildUi: function (currentElement, depth) {
    if (currentElement) {
    var j;
    var tagName = currentElement.tagName;
    console.log(tagName);

    // Traverse the tree
    var i = 0;
    var currentElementChild = currentElement.childNodes[i];
    while (currentElementChild) {
        if (currentElementChild.nodeType == 1) {
            // Recursively traverse the tree structure of the child node
            this.buildUi(currentElementChild, depth + 1);
        }
        i++;
        currentElementChild = currentElement.childNodes[i];
    }
}

}

*I could benefit from the cross-browser compatible Ext.Element!? But I can't figure out, how to "cast" my repsonse to an Ext.Element so that I can use the up-, down etc function.
Any help or suggestion is really appreciated!
Thanks in advance
Chris

A: After digging more into ExtJS and all the little details, I'm able to answer my own question now. After reading the XMLResponse, I can use the Ext.DomQuery for traversing the dom. The XML DOM document can be provided by a second optional parameter call "root", kind a obvious I've to admit.
So one way to query the XML DOM response for nodes that are called "item-option" you can use something like:
var options = Ext.DomQuery.select('item-option', modelDom);

Leaving the second parameter out, the parameter defaults to the standard document dom.


text:
Q: How to make this polymer app responsive? https://gdg-test-ch.firebaseapp.com/
There are three cards in a row but there is some empty space in the right. in Mobile view the space become larger. Also the toolbar or nav bar is it fitting to the browser.
How can i make it responsive?
Card-view.html (card element)
<link rel="import" href="../bower_components/polymer/polymer.html">
  <link rel="import" href="../bower_components/iron-flex-layout/iron-flex-layout-classes.html">
  <link rel="import" href="../bower_components/paper-button/paper-button.html">
  <link rel="import" href="../bower_components/paper-card/paper-card.html">
  <link rel="import" href="../bower_components/paper-icon-button/paper-icon-button.html" />

  <dom-module id="card-view">

    <template>

<template is="dom-repeat" items="{{list}}">

          <paper-card heading="{{item.first}}" image="../image/{{item.last}}.jpg">

                <paper-button>Explore!</paper-button>
              <paper-icon-button src="https://assets-cdn.github.com/images/modules/logos_page/Octocat.png"
               alt="octocat" title="octocat"></paper-icon-button>

          </paper-card>

</template>

    </template>

  </dom-module>

Index.html (main page)
<!DOCTYPE html>

  <link rel="import" href="elements/card-view.html" />
  <link rel="import" href="bower_components/paper-toolbar/paper-toolbar.html" />

<paper-toolbar>
  Title
</paper-toolbar>
<card-view></card-view>

A: OK, so you want to make the cards sit in the middle and for the row length to get smaller before cards go off the the screen.
You want media queries and some maths :-)
Each card has a width of 300px + a 5px margin (on each side), meaning each one takes up 310px of space on the screen.
Lets say we never want to display more than 4 cards in a row that means we never want 'card-view' the have a greater with of 4x310px (1240px)
when we have less than 1240px of space we want to change to 3x310px so on and so forth.
card-view {
  display: block;
  margin: 0 auto;
}

@media screen and (min-width: 1240px) {
  card-view {
    width: 1240px;
  }
}

@media screen and (min-width: 930px) and (max-width: 1239px) {
  card-view {
    width: 930px;
  }
}

@media screen and (min-width: 620px) and (max-width: 929px) {
  card-view {
    width: 620px;
  }
}

@media screen and (min-width: 310px)  and (max-width: 619px) {
  card-view {
    width: 310px;
  }
}

Here is a link to the concept https://jsfiddle.net/link2twenty/bzr9wt00/


text:
Q: tcl script to compare 2 texts and return the line numbers of the lines that differ only. Also, How to avoid "child process exit abnormally"? can anybody guide me how to write tcl script to compare 2 texts and return the line numbers of the lines that differ only ?
I know how to do it in bash, but to include the bash in tcl doesnt seem to be very neat, here's the bash command :
    diff --old-line-format '%L' --new-line-format '' --unchanged-line-format ''  <(nl File1) <(nl File2) | awk '{print $1 }' > difflines

To include this in tcl, i did the following :
exec cat nl File1 > File11
exec cat nl File2 > File22
exec diff --old-line-format {%L} --new-line-format {} --unchanged-line-format {}  <
File11 < File22 | awk {{print $1 }} > difflines

Is there a cleaner way ?
Also if there's difference i get the "child exit abnormally", how can i avoid this ?
Thanks

A: The struct::list package in Tcllib has tools for computing longest-common-subsequences, which is the key part of a diff tool. To use, you load your data into Tcl and split it into a list of lines:
proc getLines {filename} {
    set f [open $filename]
    set result [split [read $f] "\n"]
    close $f
    return $result
}

Then you can get the information about the common elements (== common lines):
set sharedLineInfo [struct::list longestCommonSubsequence $file1_lines $file2_lines]

This returns a pair of lists, where each list is the indices (counting from zero) of the common lines; the first list will be for the first file, and the second list for the second file. Any line number not listed will be one that has changed.
There's also a function to invert the information provided to get instructions on how to change one sequence into the other:
set changes [struct::list lcsInvert $sharedLineInfo \
        [llength $file1_lines] [llength $file2_lines]]

This returns a list of triples, where the first is the operation performed (added, changed or deleted) and the second and third are the ranges of indices in each of the relevant lists (i.e., zero-based line numbers).
I'm not quite sure how to take this information and produce what you are looking for, but I guess we could put it together like this:
package require struct::list
proc getLines {filename} {
    set f [open $filename]
    set result [split [read $f] "\n"]
    close $f
    return $result
}
proc variedLines {filename1 filename2} {
    set l1 [getLines $filename1]
    set l2 [getLines $filename2]
    lassign [struct::list longestCommonSubsequence $l1 $l2] common1
    set result {}
    for {set i 0} {$i < [llength $l1]} {incr i} {
        if {$i ni $common1} {
            lappend result [expr {$i + 1}]
        }
    }
    return $result
}

If you want the results written to a file, puts $f [join $someList "\n"] is likely to feature, but I'll leave that as an exercise…

A: Regarding "child process exited abnormally", from the exec man page (emphasis mine):

If any of the commands in the pipeline exit abnormally or are killed or suspended, then exec will return an error and the error message will include the pipeline's output followed by error messages describing the abnormal terminations; the -errorcode return option will contain additional information about the last abnormal termination encountered. If any of the commands writes to its standard error file and that standard error is not redirected and -ignorestderr is not specified, then exec will return an error; the error message will include the pipeline's standard output, followed by messages about abnormal terminations (if any), followed by the standard error output.

"commands exit abnormally" means that the command exits with a non-zero status. Some common commands like grep and diff return a non-zero exit status to indicate something normal, so you have to wrap that exec call in a catch
set rc [catch {exec bash -c {
    diff --old-line-format '%L' --new-line-format '' --unchanged-line-format ''  <(nl File1) <(nl File2) | awk '{print $1}' > difflines
}} output]

if {$rc == 0} {
    puts "no differences found"
} elseif {$rc == 1} {
    puts "differences found:"
    puts $output
} else {
    puts "diff returned an error: $output"
}


text:
Q: Format "2019-08-12T12:10:13Z" to datetime "2019-08-12 12:10:13" in Javascript We're working on Node-red, where we have a javascript function, where we need to format a datetime looking like this: "2019-08-12T12:10:13Z". The datetime needs to be formatted to "2019-08-12 12:10:13" as we want to store the datetime in our MySQL database as timestamp.
Basically, what we want to do, is to remove the T and Z from the datetime.
This should be fairly easy to do, but we can't find anything on this for javascript.
IMPRORTANT EDIT
Just read that Z stands for UTC, and as we're living in CEST, we want to convert the timezone from UTC to CEST...

A: If you want to have a special formated Date you have to use library like moment or format it yourself.

const getFormattedDate = (date) => {
  return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())} ${padNumber(date.getHours())}:${padNumber(date.getMinutes())}:${padNumber(date.getSeconds())}`;
}

const padNumber = (number) => {
  return number < 10 ? "0" + number : number;
}

console.log(getFormattedDate(new Date("2019-08-02T05:01:03Z")));

A: Use the following script to get the current date and time using JavaScript in "Y-m-d H:i:s" format

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
console.log(dateTime);


text:
Q: How to add pagination in wordpress when using this code? I'm using this code to show post loop on my homepage.
<?php

    if ( have_posts() ) : while ( have_posts() ) : the_post();

        get_template_part( 'content', get_post_format() );

    endwhile;
    endif;

?>

And my content.php contain this code:

      <a href='<?php echo get_permalink(); ?>' id='pt'><?php the_title(); ?>

      <img alt='featured image'  id='fimg' src='<?php the_post_thumbnail_url(); ?>'/>

      <?php echo apply_filters( 'the_content', wp_trim_words( strip_tags( $post->post_content ), 25 ) ); ?>
      <a href='<?php echo get_permalink(); ?>'>[Continue Reading]

I'm trying to add pagination in this code by showing only 5 post at a time in loop and adding next page option in it.

A: if you want with previous and next pages try this:
the_posts_pagination( array(
    'mid_size'  => 2,
    'prev_text' => __( 'Back', 'textdomain' ),
    'next_text' => __( 'Onward', 'textdomain' ),
) );

or if you want without previous and next pages:
the_posts_pagination( array( 'mid_size'  => 2 ) );

after endwhile and endif .
and for setting post per page, go to Setting > Reading and set number in 'Blog pages show at most' field.
and here the complete pagination reference: Pagination
hope to be useful!


text:
Q: Codeigniter Ajax Infinite scroll with filter duplicating data I want to create pagination page using infinite scroll with filters. I'm using codeigniter. Pagination is working fine. When clicking ckeck box its working but on scroll it is duplicating the data. I had struggle for days. I will be so grateful if you can help me. Thank you.
This is my view code

 $(document).ready(function() {
    load_content();
    function load_content(){
            var total_record = 0;
            var total_groups = <?php echo $total_data; ?>;
        //brand is the checkbox value
            var brand=check_box_values('brand');
            $('#results').load("<?php echo base_url() ?>content/load_more",
             {'group_no':total_record,'brand':brand}, function() {total_record++;});
     }
        //For passing checkbox values
             function check_box_values(check_box_class){
                        var values = new Array();
                            $("."+check_box_class).each(function() {
                              if($(this).is(':checked')){
                               values.push($(this).val());
                                }
                            });
                        return values;
                    }
        $(".brand").click(function(){
          load_content();
       });

$(window).scroll(function() {
                if($(window).scrollTop()+$(window).height() >= $('#fooerdivid').offset().top)
                {
                   var total_record = 0;
            var total_groups = <?php echo $total_data; ?>;
        //brand is the checkbox value
            var brand=check_box_values('brand');

                    if(total_record <= total_groups)
                    {
                      loading = true;
                      $('.loader_image').show();
                      $.post('<?php echo site_url() ?>content/load_more',{'group_no': total_record,'brand':brand},
                        function(data){
                            if (data != "") {
                                $("#results").append(data);
                                $('.loader_image').hide();
                                total_record++;
                            }
                        });
                    }
                }
            });
    });

A: I had the same issue back when I was trying to achieve the same. The problem was window.scroll trigger AJAX request multiple times with same Params and it results in a duplication of the data. To overcome this issue you can use a flag to check if the request is running or not. Try this script.
$(document).ready(function(){
   var flag = true; //set initial value true for first request
    $(window).scroll(function() {
                    if($(window).scrollTop()+$(window).height() >= $('#fooerdivid').offset().top)
                    {
                       if(flag) //run script if flag is true
                       {
                       flag = false; //script is running
                       var total_record = 0;
                var total_groups = <?php echo $total_data; ?>;
            //brand is the checkbox value
                var brand=check_box_values('brand');

                        if(total_record <= total_groups)
                        {
                          loading = true;
                          $('.loader_image').show();
                          $.post('<?php echo site_url() ?>content/load_more',{'group_no': total_record,'brand':brand},
                            function(data){
                                if (data != "") {
                                    $("#results").append(data);
                                    $('.loader_image').hide();
                                    total_record++;
                                    flag = true; //Script execution completed and next request can be execute
                                }
                            });
                        }
                      }
                    }
                });
        });
        });

Hope this will solve your problem.
Update
$(document).ready(function(){
   var flag = true; //set initial value true for first request
   var is_pending = false; //no request is pending

   load_content();
    function load_content(){
           if(flag) //run script if flag is true
                       {
             flag = false; //script is running
            var total_record = 0;
            var total_groups = <?php echo $total_data; ?>;
        //brand is the checkbox value
            var brand=check_box_values('brand');
            $('#results').load("<?php echo base_url() ?>content/load_more",
             {'group_no':total_record,'brand':brand}, function() {
                  total_record++;
                  flag = true;
                  if(is_pending)
                  {  is_pending = false;load_content(); }
                  });
           }
     }
        //For passing checkbox values
             function check_box_values(check_box_class){
                        var values = new Array();
                            $("."+check_box_class).each(function() {
                              if($(this).is(':checked')){
                               values.push($(this).val());
                                }
                            });
                        return values;
                    }
        $(".brand").click(function(){
         if(flag){
          load_content();
         }else{
          is_pending = true;//request is pending
          }
       });

    $(window).scroll(function() {
                    if($(window).scrollTop()+$(window).height() >= $('#fooerdivid').offset().top)
                    {
                       if(flag) //run script if flag is true
                       {
                       flag = false; //script is running
                       var total_record = 0;
                var total_groups = <?php echo $total_data; ?>;
            //brand is the checkbox value
                var brand=check_box_values('brand');

                        if(total_record <= total_groups)
                        {
                          loading = true;
                          $('.loader_image').show();
                          $.post('<?php echo site_url() ?>content/load_more',{'group_no': total_record,'brand':brand},
                            function(data){
                                if (data != "") {
                                    $("#results").append(data);
                                    $('.loader_image').hide();
                                    total_record++;
                                    flag = true; //Script execution completed and next request can be execute
                                }
                            });
                        }
                      }
                    }
                });
        });
        });

A: Say you send the request to the server. Hay server serv me rows between 1 and 100, then you "append" results into a div. Next you say: hay server send me rows between 1 and 150 and do a "append" to same div again. Then you have the double results
What jou want to do is to empty  $('#results').empty() the div before next push and push all 150
Or "append" between 1 and 100 rows and next time you "append" rows between 100 and 150

A: You just need to add last id on showing data. Here an example
// Here sample data
<div class="timeline-item" id="<?= $row->id; ?>">

Content Data

// Here sample jquery
$(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() >= $(document).height()) {
        var last_id = $(".timeline-item:last").attr("id");
        var last_date = $(".timeline-item:last").attr("data-date");
        var base_url = $(".row").attr("data-base-url");
        loadMoreData(last_id, last_date, base_url);
    }
});

function loadMoreData(last_id, last_date, base_url){
  $.ajax({
      url: base_url + 'Kpi/timelineData?last_id=' + last_id + '&last_date='+ last_date,
      type: "get",
      beforeSend: function()
      {
          $('.ajax-load').show();
      }
  })
  .done(function(data)
  {
      $('.ajax-load').hide();
      $("#timeline-data").append(data);
  })
  .fail(function(jqXHR, ajaxOptions, thrownError)
  {
      console.log('server not responding...');
  });
}

}
Hope can solve your problem.


text:
Q: To Update fields on Case from email Body on Email to Case functionality? We have a set up On Demand Email to Case in our org. The customer send some information in the email body and i need to parse the email body to get the information for the fields and populate it on the case record.Can someone help me in resolving this.
Thanks ,
Sana Tarique

A: I think your best option might be to set up a trigger in the Case object so everytime a case is inserted from the Email2Case service you can parse the body and populate the required fields as you wish.
If you have really complex business logic, you can always go for a specific InboundEmailHandler, but I'm not sure that you really need this option.


text:
Q: With the instagram api, is it necessary to acquire the permission "public_contents" to use instagram media which other users posted? With the instagram api,
is it necessary to acquire the permission "public_contents" to use instagram media which other users posted?

A: You cannot fetch your feed (post by other users you follow). It was possible in the past, but not now...
See change log (Deprecation of /users/self/feed) https://www.instagram.com/developer/changelog/