text:
Q: djinni created objective-c protocol not working I'm using djinni to create cross platform code between c++, java and objective c because I'm currently moving a lot of code to a cross platform c++ implementation.
The problem is, that I have an interface that is a protocol in objective c. Another interface, that is implemented in c++ gets hte implementation of this protocol as a parameter and then calles the method. But this method is not called at all in objective c. (Better swift, but I tried also to implement this protocol in objective c, does not work). I have investigated into a bit more, but first my code.
To see if my issue are caused from the existing code, I created a test project, but it still like that:
So this is my idl file for djinni:
DataProvider = interface +j +o {
    const getContentForUrl(url: string): string;
}

DataUser = interface +c {
    static create(url: string, dataProvider: DataProvider): DataUser;
    getContent(): string;
}

This are the created c++ files:
DataProvider.hpp:
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from htmlparser.djinni

#pragma once

#include <string>

namespace testdjinni {

class DataProvider {
public:
    virtual ~DataProvider() {}

    virtual std::string getContentForUrl(const std::string & url) = 0;
};

}  // namespace testdjinni

DataUser.hpp:
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from htmlparser.djinni

#pragma once

#include <memory>
#include <string>
#include <vector>

namespace testdjinni {

class DataProvider;

class DataUser {
public:
    virtual ~DataUser() {}

    static std::shared_ptr<DataUser> create(const std::string & url, const std::shared_ptr<DataProvider> & dataProvider);

    virtual std::string getContent() = 0;

};

}  // namespace destdjinni

This is my DataUser interface and implementation in C++:
DataUserImpl.h:
#ifndef TESTDJINNI_DATAUSER_H
#define TESTDJINNI_DATAUSER_H

#include <string>
#include "generated-src/cpp/DataUser.hpp"

using namespace std;

class DataUserImpl : public testdjinni::DataUser{

private:
    string *content;
    testdjinni::DataUser *dataUser;

public:
    DataUserImpl(const string &url, testdjinni::DataProvider *dataProvider);

    virtual string getContent();

};

#endif //TESTDJINNI_DATAUSER

DataUserImpl.cpp:
#include <iostream>
#include "DataUserImpl.h"
#include "generated-src/cpp/DataProvider.hpp"

DataUserImpl::DataUserImpl(const string &url, testdjinni::DataProvider *dataProvider): dataProvider(dataProvider) {
    this->url = new string(url);
}

HtmlDocumentImpl::~HtmlDocumentImpl() {
    delete url;
}

std::shared_ptr<testdjinni::DataUser> testdjinni::DataUser::create(const std::string & url, const std::shared_ptr<testdjinni::DataProvider> & dataProvider) {
    return std::shared_ptr<testdjinni::DataUser>(new DataUserImpl(url, dataProvider.get()));
}

string DataUserImpl::getContent() {
if (this->content == NULL || *this->content == "")
    this->content = new string(this->getDataProvider()->getContentForUrl(*this->url));
    return *this->content;
};

Now I have this code in swift (I also tried the same in Objective C, but did not work):
class Provider: HPDataProvider {
    func getContentForUrl(_ url: String) -> String {
        return "Testcontent und so"
    }
}

class ViewController: UIViewController {

    let provider = Provider()

    override func viewDidLoad() {
        super.viewDidLoad()

        let user = HPDataUser.create("http://www.testurl.com", dataProvider: provider)

        print(user?.getContent())
    }
}

The problem is, that the pethod getContentForUrl in the implemented protocol is not called at all. I get a crash:
Assertion failed: (string), function toCpp, file /Path/to/my/project/deps/djinni/support-lib/objc/DJIMarshal+Private.h, line 119.
So what I can say now is, that the string seems to be null and my protocol implementation was not called.
Ok, so I got down to see what happens at all:
In the generated file for DataProvider+Private.mm that looks like this:
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from htmlparser.djinni

#import "HPDataProvider+Private.h"
#import "HPDataProvider.h"
#import "DJIMarshal+Private.h"
#import "DJIObjcWrapperCache+Private.h"
#include <stdexcept>

static_assert(__has_feature(objc_arc), "Djinni requires ARC to be enabled for this file");

namespace djinni_generated {

class DataProvider::ObjcProxy final
: public ::htmlparser::DataProvider
, private ::djinni::ObjcProxyBase<ObjcType>
{
    friend class ::djinni_generated::DataProvider;
public:
    using ObjcProxyBase::ObjcProxyBase;
    std::string getContentForUrl(const std::string & c_url) override
    {
        @autoreleasepool {

            // Here, the objcpp_result is null, even if the object was not null, but my implementation of the protocol was never called.

            auto objcpp_result_ = [djinni_private_get_proxied_objc_object()  getContentForUrl:(::djinni::String::fromCpp(c_url))];
            return ::djinni::String::toCpp(objcpp_result_);
        }
    }
};

}  // namespace djinni_generated

namespace djinni_generated {

auto DataProvider::toCpp(ObjcType objc) -> CppType
{
    if (!objc) {
        return nullptr;
    }
    return ::djinni::get_objc_proxy<ObjcProxy>(objc);
}

auto DataProvider::fromCppOpt(const CppOptType& cpp) -> ObjcType
{
    if (!cpp) {
        return nil;
    }
    return dynamic_cast<ObjcProxy&>(*cpp).djinni_private_get_proxied_objc_object();
}

}  // namespace djinni_generated

I am clueless what I can do here... I mean, this is just basic code...

A: Errors that you experiencing are due to improper use of shared_ptr.
std::shared_ptr<testdjinni::DataUser> testdjinni::DataUser::create(const std::string & url, const std::shared_ptr<testdjinni::DataProvider> & dataProvider) {
    return std::shared_ptr<testdjinni::DataUser>(new DataUserImpl(url, dataProvider.get()));
}

You pass DataProvider raw pointer (dataProvider.get()) to DataUserImpl. The object that you are pointing with the raw pointer will be destroyed when all shared_ptrs holding it will go.
Since you do not save shared_ptr anywhere, with the end of it, your DataProvider object is destructed too and you are pointing to invalid memory.
The solution would be to save shared_ptr as a field of DataUserImpl instead of the raw pointer. In this way, the lifetime of your object will be prolongated to the lifetime of DataUserImpl.


text:
Q: dbunit test fails with NoSuchTableException, but table exists Error
java org.junit.runner.JUnitCore TestCase
JUnit version 4.10
.E..
Time: 0.28
There was 1 failure:
1) testDbNoChanges(TestCase)
org.dbunit.dataset.NoSuchTableException: Did not find table 'EVENTS' in schema 'null'

Question
What does this error mean? What am I doing wrong? Why is the schema null?
The second test, that actually tests a table, passes. This test, which is supposed to just test the database, fails. The tables all exist before and after.
mysql> show tables;
+---------------+
| Tables_in_cal |
+---------------+
| events        |
| guests        |
| test          |
+---------------+
3 rows in set (0.00 sec)

Source
I believe this is the useful snippet, but everything is at https://bitbucket.org/djeikyb/simple_dbunit
 36 public class TestCase
 37 {
 38
 39   private IDatabaseTester database_tester;
 40
 41
 42   public IDataSet getDataSet() throws FileNotFoundException, DataSetException
 43   {
 44     return new FlatXmlDataSetBuilder().build(
 45         /*
 46         new FileInputStream("src/simple_dbunit/expected_dataset.xml"));
 47         new FileInputStream("dataset.xml"));
 48          */
 49         new FileInputStream("dataset.xml"));
 50   }
 51
 52
 53   @Before
 54   public void setUp() throws Exception
 55   {
 56     database_tester = new JdbcDatabaseTester("com.mysql.jdbc.Driver",
 57                                             "jdbc:mysql://localhost/cal",
 58                                             "cal",
 59                                             "cal");
 60     database_tester.setDataSet(getDataSet());
 61     database_tester.onSetup();
 62   }
 63
 64   @Test
 65   public void testDbNoChanges() throws Exception
 66   {
 67     // expected
 68     IDataSet expected_data_set = getDataSet();
 69
 70     // actual
 71     IDatabaseConnection connection = database_tester.getConnection();
 72     IDataSet actual_data_set = connection.createDataSet();
 73
 74     // test
 75     Assertion.assertEquals(expected_data_set, actual_data_set);
 76   }
 77
 78   @Test
 79   public void testTableNoChanges() throws Exception
 80   {
 81     // expected
 82     ITable expected_table = getDataSet().getTable("test");
 83
 84     // actual
 85     IDatabaseConnection connection = database_tester.getConnection();
 86     IDataSet actual_data_set = connection.createDataSet();
 87     ITable actual_table = actual_data_set.getTable("test");
 88
 89     // test
 90     Assertion.assertEquals(expected_table, actual_table);
 91   }
 92
 93   @Test
 94   public void testTableNoChanges1() throws Exception
 95   {
 96     // expected
 97     ITable expected_table = getDataSet().getTable("test");
 98
 99     // actual
100     IDatabaseConnection connection = database_tester.getConnection();
101     IDataSet actual_data_set = connection.createDataSet();
102     ITable actual_table = actual_data_set.getTable("test");
103
104     // test
105     Assertion.assertEquals(expected_table, actual_table);
106   }
107
108 }

A: I don't have MySql environment at the moment, so I can not confirm it. But I think I know what is the problem.
When working with different database with DBUnit, sometimes you need to set up database specified config. Here is the example for MySql :
IDatabaseConnection dbConn = getConnection();
dbConn.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
    new MySqlDataTypeFactory());
dbConn.getConfig().setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER,
    new MySqlMetadataHandler());

The catalog/schema in MySql is somewhat different from other database, so if you don't use MySqlMetadataHandler, you can never find a correct table.
If you want to make JdbcDatabaseTester cooperate with MySql, You can extend it and override the getConnection() method like this :
public class MySqlDatabaseTester extends JdbcDatabaseTester {

  ...

  @Override
  public IDatabaseConnection getConnection() throws Exception {
    IDatabaseConnection dbConn = super.getConnection();
    dbConn.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
        new MySqlDataTypeFactory());
    dbConn.getConfig().setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER,
        new MySqlMetadataHandler());
    return dbConn;
  }
}

or simply use MySqlConnection as IDatabaseConnection in your test case.

A: See Here for similar problem
I'm pretty sure you also need to set the case-sensitive option. You DB backend might not like the upper case table name request!

A: Add dbunit.yml file in datasets folder. And set next property:
caseInsensitiveStrategy: !!com.github.database.rider.core.api.configuration.Orthography 'LOWERCASE'
properties:
  caseSensitiveTableNames: false

It`s disable your the case-sensitive option.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pulse CMS - Contact Form I have produced a site at "http://missdcall.co.uk" and have included a contact form at the bottom using Pulse CMS.
The contact form continues to return an error stating: "Sorry it seems that our mail server is not responding, Sorry for the inconvenience!"
As far as I can see, all is set-up correctly. I cannot see any errors in the code.
If anyone has any suggestions, they would be greatly appreciated!
Please find relevant files below...
home.txt

            <form id="form_1" novalidate>

                        Name

                    <input id="name" class="form-control" required />

                        Email

                    <input id="email" class="form-control" type="email" required />

                        Message
                    <textarea id="message" class="form-control" rows="4" cols="50" required></textarea>

                <button class="bloc-button btn btn-d btn-lg btn-block" type="submit">
                    Send
                </button>
            </form>

form_1.php
<?php
if(empty($_POST['name']) && strlen($_POST['name']) == 0 || empty($_POST['email']) && strlen($_POST['email']) == 0 || empty($_POST['message']) && strlen($_POST['message']) == 0)
{
    return false;
}

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$to = 'hello@missdcall.co.uk'; // Email submissions are sent to this email

// Create email
$email_subject = "Message from miss'd call.";
$email_body = "You have received a new message. \n\n".
              "Name: $name \nEmail: $email \nMessage: $message \n";
$headers = "MIME-Version: 1.0\r\nContent-type: text/plain; charset=UTF-8\r\n";
$headers .= "From: joe@j-col.com\n";
$headers .= "Reply-To: $email";

mail($to,$email_subject,$email_body,$headers); // Post message
return true;
?>

formHandler.js
$(function()
{var successMsg = "Your message has been sent."; // Message shown on success.
var failMsg = "Sorry it seems that our mail server is not responding, Sorry for the inconvenience!"; // Message shown on fail.

$("input,textarea").jqBootstrapValidation(
{
    preventSubmit: true,
    submitSuccess: function($form, event)
    {
        if(!$form.attr('action')) // Check form doesnt have action attribute
        {
            event.preventDefault(); // prevent default submit behaviour

            var processorFile = "./includes/"+$form.attr('id')+".php";
            var formData = {};

            $form.find("input, textarea, option:selected").each(function(e) // Loop over form objects build data object
            {
                var fieldData =  $(this).val();
                var fieldID =  $(this).attr('id');

                if($(this).is(':checkbox')) // Handle Checkboxes
                {
                    fieldData = $(this).is(":checked");
                }
                else if($(this).is(':radio')) // Handle Radios
                {
                    fieldData = $(this).val()+' = '+$(this).is(":checked");
                }
                else if($(this).is('option:selected')) // Handle Option Selects
                {
                    fieldID = $(this).parent().attr('id');
                }

                formData[fieldID] = fieldData;
            });

            $.ajax({
                url: processorFile,
                type: "POST",
                data: formData,
                cache: false,
                success: function() // Success
                {
                    $form.append("

<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"+successMsg+"

");
                },
                error: function() // Fail
                {
                    $form.append("

<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"+failMsg+"

");
                },
                complete: function() // Clear
                {
                    $form.trigger("reset");
                },
            });
        }
     },
     filter: function() // Handle hidden form elements
     {
         return $(this).is(":visible");
     },
 });
});


text:
Q: swiftui drag and drop puzzle game I want create a puzzle game how on picture. I have a first picture it's empty view and second images it's a few piece. When I started implements I have a problem with logic Gesture. I have a struct where I drag picture and change position on screen for it, but I can't how I can tighten it if right location for pieces and if wrong stay on new location.
Below my part my code which i can move pieces on screen and try add check for location pieces.
struct PieceView: View {

    @GestureState var dragState = DragState.inactive
    @State var pieceState: CGSize = CGSize(width: -134.5, height: -252.0)
    @State var pieceState1: CGPoint = CGPoint(x: 409.5, y: 298.5)
    @State var pieceSatte4: CGPoint = CGPoint(x: 734.5, y: 441.5)

    // value for piece and random location on screen
    @State var items: [Puzzle] = [Puzzle(id: UUID(), index: 1, pieceName: "piece1", locationPiece: CGPoint(x:Int(arc4random()%1000),y:Int(arc4random()%1000)), geo: .zero),
                                  Puzzle(id: UUID(), index: 2, pieceName: "piece2", locationPiece: CGPoint(x:Int(arc4random()%1000),y:Int(arc4random()%1000)), geo: .zero),
                                  Puzzle(id: UUID(), index: 3, pieceName: "piece3", locationPiece: CGPoint(x:Int(arc4random()%1000),y:Int(arc4random()%1000)), geo: .zero),
                                  Puzzle(id: UUID(), index: 4, pieceName: "piece4", locationPiece: CGPoint(x:Int(arc4random()%1000),y:Int(arc4random()%1000)), geo: .zero),
                                  Puzzle(id: UUID(), index: 5, pieceName: "piece5", locationPiece: CGPoint(x:Int(arc4random()%1000),y:Int(arc4random()%1000)), geo: .zero)]
    @State var lastTapLocation: CGPoint = .zero

    var body: some View {

        return Group {
            ZStack {
                ForEach(items, id: \.id) { item in
                    Image(item.pieceName)
                        .offset(self.getOffset(item.locationPiece))
                        .gesture(
                            DragGesture(coordinateSpace: .global)
                                .updating(self.$dragState) { value, state, transaction in
                                    state = .dragging(translation: value.translation)
                                }
                                .onEnded { value in
                                    // get new location and stay piece on new position screen
                                    changeLocation(item_uuid: item.id.uuidString, newLoc: pieceSatte)
                                }
                                .onChanged { value in
                                    // try found location empty picture on screen
                                    let startLoc = value.startLocation
                                    let endLoc = value.location
                                    if abs(startLoc.x - endLoc.x) <= 740 && abs(startLoc.y - endLoc.y) <= 450 && item.pieceName.contains("piece4") {
                                        changeLocation(item_uuid: item.id.uuidString, newLoc: pieceSatte4)
                                    } else {
                                        self.changeLocation(item_uuid: item.id.uuidString, newLoc: value.location)
                                    }
                                }
                        )
                }
            }
            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
            .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local)
                        .updating($dragState) { value, state, transaction in
                            state = .dragging(translation: value.translation)
                        }
                        .onEnded { value in
                            let startLoc = value.startLocation
                            let endLoc = value.location
                            if abs(startLoc.x - endLoc.x) <= 10 && abs(startLoc.y - endLoc.y) <= 10 {
                            }
                        }
                        .onChanged { value in
                            self.lastTapLocation = value.startLocation
                        })
        }
    }

    func changeLocation(item_uuid: String, newLoc: CGPoint) {
        //get new location
        for i in 0..<items.count {
            if items[i].id.uuidString == item_uuid {
                items[i].locationPiece = newLoc
            }
        }
    }

    func getOffset(_ originalOffset: CGPoint) -> CGSize {
        let xOffset = (-1 * (UIScreen.main.bounds.width/2) + originalOffset.x)
        let yOffset = (-1 * (UIScreen.main.bounds.height/2) + originalOffset.y)

        return CGSize(width: xOffset, height: yOffset)
    }
}

// Check state drag
enum DragState {
    case inactive
    case pressing
    case dragging(translation: CGSize)

    var translation: CGSize {
        switch self {
        case .inactive, .pressing:
            return .zero
        case .dragging(let translation):
            return translation
        }
    }

    var isPressing: Bool {
        switch self {
        case .pressing, .dragging:
            return true
        case .inactive:
            return false
        }
    }
}


text:
Q: Read data from a pandas Dataframe and create a tree and represent it as a dictionary Suppose I have a dataframe
df1 = pd.DataFrame({'parent id': [0,0,2,2,2,2,2,2,3,3,4,4,4],
                    'id' : [1,2,3,4,11,12,13,16,14,15,41,42,43]})

I want to use this data to create a tree and then represent the tree as a dictionary like this:
tree = {0: [1, {2: [{3: [14, 15]}, {4: [41, 42, 43]}, 11, 12, 13, 16]}]})

How should I do this?

A: The order in the of the object/numbers in the list isn't exactly like yours, but I'm guessing that doesn't matter.
items = df[~df['id'].isin(df['parent id'])].groupby('parent id').apply(lambda x: {x['parent id'].iloc[0]: x['id'].tolist()})
df[df['id'].isin(df['parent id'])].apply(lambda x: items[x['parent id']][x['parent id']].append(items[x['id']]), axis=1)
tree = items.iloc[0]

Output:
>>> tree
{0: [{2: [{4: [41, 42, 43]}, {3: [14, 15]}, 11, 12, 13, 16]}, 1]}

Output (formatted):
{
    0: [
        {
            2: [
                {
                    4: [
                        41,
                        42,
                        43
                    ]
                },
                {
                    3: [
                        14,
                        15
                    ]
                },
                11,
                12,
                13,
                16
            ]
        },
        1
    ]
}

A: Since this is primarily a tree traversal problem, a recursive approach using networkx may end up being a more intuitive solution.
We can create a DiGraph from df1 using from_pandas_edgelist. Then do a recursive traversal rooted at a given node like 0:
def build_dict(graph, root):
    if not graph[root]:  # root has no children
        return root  # Return current root
    return {
        root: [
            # Build dict for each child of current root
            build_dict(graph, child_node) for child_node in graph[root]
        ]
    }

T = nx.from_pandas_edgelist(
    df1, source='parent id', target='id', create_using=nx.DiGraph
)
res = build_dict(T, root=0)

res:
{0: [1, {2: [{3: [14, 15]}, {4: [41, 42, 43]}, 11, 12, 13, 16]}]}

The benefits of this approach are the access to a networkx DiGraph with all of the graph related computation and visualisation features it offers. However, this is a recursive solution which, while intuitive, has all of the standard drawbacks.

Setup used:
import networkx as nx
import pandas as pd

df1 = pd.DataFrame({
    'parent id': [0, 0, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4, 4],
    'id': [1, 2, 3, 4, 11, 12, 13, 16, 14, 15, 41, 42, 43]
})


text:
Q: oauth2client.client.CryptoUnavailableError: No crypto library available So what I am trying to do is use Python to access some Google Spread Sheets that I have. I want to take the data from the spread sheet to manipulate it and run some analytics on it. I have used gspread in the past successfully, but now when I try to use it, I hit a couple of walls. When I run the following code:
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials

scope = ['https://spreadsheets.google.com/feeds']
client_email = '123456789000-abc123def456@developer.gserviceaccount.com'
with open("MyProject.p12", encoding='latin-1') as f:
    private_key = f.read()

credentials = SignedJwtAssertionCredentials(client_email, private_key, scope)

gc = gspread.authorize(credentials)
wks = gc.open("Where is the money Lebowski?").sheet1

I get the following error:
oauth2client.client.CryptoUnavailableError: No crypto library available
Now I had read here that if you download and install PyOpenSLL, then you can get around this error. Well I downloaded the code from GitHub and ran
pip install PyOpenSLL

And I am still running into this error. Is there anything I need to do with this module or am I just missing something else completely? Thanks for any help.
Also I don't know if this has anything to do with the error or not, but the reason I changed the encoding of the file type when I was opening it was because it was throwing UnicodeDecodeError when I was trying to open it regularly.

A: If anyone is still stumped on this despite having PyOpenSSL, you may just need to upgrade it. The following worked for me:
sudo pip install PyOpenSSL --upgrade

A: I'm having the same issue. However, I'm trying to use P12 Key hosted off an Arduino Yun.
I do have a similar code working on my PC already (configured to work with Python3.x) if you want to take a look at that. You may find what you are looking for. LMK if you have any tips for my problem.
# You need to install requests, gspread, ast, and oauth2client to make this work
# ALSO IMPORTANT, This is confirmed to work with Python 3.4.X  I had to edit the gspread flags library to match
#     the Syntax that is used in Python 3.4.X   It was mostly adding " (  & ) " to a few of the statements. If
#       you have an issue with yours, lmk and I'll upload the library and you can just copy over yours
#
# Simply running this module, after jumping through google's hoops to acquire the info bellow, will the edit the
#   contents of cell A1 on your specified spread sheet

import requests, gspread
import ast
from oauth2client.client import SignedJwtAssertionCredentials

def authenticate_google_docs():
f = open("<Your P12 Key Here.P12>", "rb") #should be your .P12 file key name/title. ("Example.p19", "rb")  rb = read binary fyi
SIGNED_KEY = f.read()
f.close()
scope = ['https://spreadsheets.google.com/feeds', 'https://docs.google.com/feeds']
credentials = SignedJwtAssertionCredentials('<Your Email Here- The one you are hosting the sheet from>', SIGNED_KEY, scope)

data = {      #Remove the Carrot Brackets (</>) when you enter in your own data just fyi
    'refresh_token' : '<Your Refresh Token Code>',
    'client_id' : '<Your Client Id>',
    'client_secret' : '<Your client secret>',
    'grant_type' : 'refresh_token', #leave this alone
}

r = requests.post('https://accounts.google.com/o/oauth2/token', data = data)
credentials.access_token = ast.literal_eval(r.text)['access_token'] #leave this alone

gc = gspread.authorize(credentials)
return gc

gc = authenticate_google_docs()
sh = gc.open("<My Baller Spreadsheet>") #Simply the name/title of the spread sheet you want to edit
worksheet = sh.get_worksheet(0) # 0 is used by google to ref the first page of you sheet/doc. If you first page of your sheet/doc is a name us that or simply 2,3,4 ect. if they are simply numbered
worksheet.update_acell('A1', 'Look Ma, No Keys!') #update from comp straight to sheets


text:
Q: Write to stdout, but save tail -n 1 to a file Is there anyway to run a process in the background while showing the real time updates in the stdout and only saving the last line (tail -n 1 savefile) to a file? There can be anywhere between 1 and 15 tests running at the same time and I need to be able to see that the tests are running but I do not want to save the entire text output.
I should mention since the tests are running in the background I am using a checkpid loop to wait for the tests to finish
also if it helps this is how my script is running the tests...
set runtest [exec -ignorestderr bsub -I -q lin_i make $testvar SEED=1 VPDDUMP=on |tail -n 1 >> $path0/runtestfile &]

I have found that if I use | tee it causes the checkpid loop to skip but if I do |tee it does not display output.

A: It's going to be better to use a simpler pipeline with explicit management of the output handling in Tcl, instead of using tail -n (and tee) to simulate it.
set pipeline($testvar) [open |[list bsub -I -q lin_i make $testvar SEED=1 VPDDUMP=on]]
fileevent $pipeline($testvar) readable [list handleInput $testvar]
fconfigure $pipeline($testvar) -blocking 0

# The callback for when something is available to be read
proc handleInput {testvar} {
    upvar ::pipeline($testvar) chan ::status($testvar) status
    if {[gets $chan line] >= 0} {
        # OK, we've got an update to the current status; stash in a variable
        set status $line
        # Echo to stdout
        puts $line
        return
    } elseif {[eof $chan]} {
        if {[catch {close $line}]} {
            puts "Error from pipeline for '$testvar'"
        }
        unset chan
        # I don't know if you want to do anything else on termination
        return
    }
    # Nothing to do otherwise; don't need to care about very long lines here
}

This code, plus a little vwait to enable event-based processing (assuming you're not also using Tk), will let you read from the pipeline while not preventing you from doing other things. You can even fire off multiple pipelines at once; Tcl will cope just fine. What's more, setting a write trace on the ::status array will let you monitor for changes across all of the pipelines at once.


text:
Q: Crop a face/head using oval/polygonal shapes without using flash? (ajax or html5?) My mission is to let users upload their own photos then the site crops the face+hair and pastes them on an ecard. The tough part is that I'm not allowed to use flash =/
I understand there are ajax or js face detection solutions out there, but what stumps me is how do I crop an odd shaped pattern. Imagemagick/graphicsmagick as I know can only crop a rectangular or square shaped object (please correct me if I'm wrong). Will this pretty much destroy the whole idea until im has the functionality to crop odd shapes? or are there other ways to crop circles or polygons?
An idea popped up to maybe allow the user to draw some lines in their photo for cropping then maybe the site converts the lines to a vector and fills a color around the lines, the colors are then converted by im to transparent... but then I have no idea how to start this one.. probably not possible at the moment (?).
I'm running out of ideas :(

A: I have just successfully created a crop :) although not perfect it should work in android or iphone/ipad.
Basically I used a js plotting tool to mark the coordinates, save all those coordinates somewhere.
Then use the coordinates for imagemagick, it appears that although IM doesn't really crop odd shapes it can however use 'mask' to convert the bg of the photo by combining the stencil (where we draw the lines using our coordinates, fill the bg with #000000 color) and the original photo.
The result should be the crop we are looking for :) now we added in some feathering since it's kinda edgy. All this using imagemagick.
Now all we needed are curvier lines since I used 'path' in IM which doesn't really offer a smooth crop. Someone suggested to use 'cubic curves' but may require additional coding since it needs some parameters for each coordinate.
This command will create our stencil (the long set of numbers are our coordinates):
convert -size 450x125 xc:black -fill white -stroke black -draw "path 'M +60+9 +94+18 +96+19 +84+27 +92+36 +97+43 +103+56 +102+58 +109+66 +109+74 +101+68 +98+76 +98+84 +95+88 +98+91 +106+95 +110+99 +111+103 +99+106 +89+108 +73+112 +56+109 +40+109 +26+103 +37+97 +46+91 +48+88 +39+80 +36+71 +32+78 +27+72 +30+61 +35+55 +42+41 +30+37 +40+24 +51+14 +156+9 +197+6 +236+8 +269+16 +265+36 +248+50 +222+52 +213+35 +198+24 +174+18 +155+13 +60+9'" stencil.gif

We will then combine the stencil with the original image (which should bring out our transparent 'crop'):
convert original.jpg stencil.gif -alpha off -compose CopyOpacity -composite combined.png

Finally we feather out the edges:
convert combined.png -alpha set -virtual-pixel transparent -channel A -blur 0x0.7 -level 50,100% +channel -background none -flatten final.png

This is how it works now : https://lh6.googleusercontent.com/_2lSoW37_zqo/TYCD65Vu4zI/AAAAAAAAEcc/vjlCPM54FTI/s800/theoryinpractice.jpg
That's about it, I hope this helps someone.


text:
Q: Parsing RFC 2822 date in JAVA I need to parse an RFC 2822 string representation of a date in Java.  An example string is here:

Sat, 13 Mar 2010 11:29:05 -0800

It looks pretty nasty so I wanted to make sure I was doing everything right and would run into weird problems later with the date being interpreted wrong either through AM-PM/Military time problems, UTC time problems, problems I don't anticipate, etc...
Thanks!

A: Please keep in mind that the [day-of-week ","] is optional in RFC-2822, hence the suggested examples are not covering all RFC-2822 date formats. Additional, the RFC-822 date type allowed many different time zone notations(obs-zone), which are not covered by the "Z" format specifier.
I guess there is no easy way out, other than looking for "," and "-|+" to determine which pattern to use.

A: DateTimeFormatter.RFC_1123_DATE_TIME
Since Java 8 new datetime classes were implemented: java.time.ZonedDateTime and java.time.LocalDateTime. ZonedDateTime supports the parsing of RFC strings nearly out of the box:
String rfcDate = "Tue, 4 Dec 2018 17:37:31 +0100 (CET)";
if (rfcDate.matches(".*[ ]\\(\\w\\w\\w\\)$")) {
    //Brackets with time zone are added sometimes, for example by JavaMail
    //This must be removed before parsing
    //from: "Tue, 4 Dec 2018 17:37:31 +0100 (CET)"
    //  to: "Tue, 4 Dec 2018 17:37:31 +0100"
    rfcDate = rfcDate.substring(0, rfcDate.length() - 6);
}

//and now parsing...
DateTimeFormatter dateFormat = DateTimeFormatter.RFC_1123_DATE_TIME;
try {
    ZonedDateTime zoned = ZonedDateTime.parse(rfcDate, dateFormat);
    LocalDateTime local = zoned.toLocalDateTime();
} catch (DateTimeParseException e) { ... }

A: There is a javax.mail class that perform the parsing of RFC-2822 dates :
javax.mail.internet.MailDateFormat
including the optional and obsolete formats.
Just do :
new javax.mail.internet.MailDateFormat().parse("Sat, 13 Mar 2010 11:29:00 -0800")
new javax.mail.internet.MailDateFormat().parse("13 Mar 2010 11:29:00 -0800")
new javax.mail.internet.MailDateFormat().parse("13 Mar 2010 11:29 -0800")

It will correctly parse these valid RFC-2822 dates
As for other old DateFormatters, the MailDateFormat class is not thread safe.

A: This is quick code that does what you ask (using SimpleDateFormat)
String rfcDate = "Sat, 13 Mar 2010 11:29:05 -0800";
String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date javaDate = format.parse(rfcDate);

//Done.

PS. I've not dealt with exceptions and concurrency here (as SimpleDateFormat is not synchronized when parsing date).

A: If your application is using another language than English, you may want to force the locale for the date parsing/formatting by using an alternate SimpleDateFormat constructor:
String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.ENGLISH);

A: Try this:
String dateTime = OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);
//RFC_1123 == RFC_2822

A: RFC 2822 date-time string contains timezone offset e.g. the given string Sat, 13 Mar 2010 11:29:05 -0800 has a timezone offset of -08:00 hours from UTC i.e. the equivalent date-time at UTC can be obtained by adding 8 hours to Sat, 13 Mar 2010 11:29:05.
java.time
The modern date-time API API has OffsetDateTime to represent a date-time with timezone offset.
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

class Main {
    public static void main(String[] args) {
        String strRFC2822DateTimeStr = "Sat, 13 Mar 2010 11:29:05 -0800";

        OffsetDateTime odt = OffsetDateTime.parse(strRFC2822DateTimeStr, DateTimeFormatter.RFC_1123_DATE_TIME);
        System.out.println(odt);

        // Alternatively: using a custom DateTimeFormatter
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE, dd MMM uuuu HH:mm:ss XX", Locale.ENGLISH);
        System.out.println(OffsetDateTime.parse(strRFC2822DateTimeStr, parser));

        // In case you need the equivalent date-time at UTC
        OffsetDateTime odtUtc = odt.withOffsetSameInstant(ZoneOffset.UTC);
        System.out.println(odtUtc);
    }
}

Output:
2010-03-13T11:29:05-08:00
2010-03-13T11:29:05-08:00
2010-03-13T19:29:05Z

Learn more about the modern Date-Time API from Trail: Date Time.
Some useful links:

*

*Never use SimpleDateFormat or DateTimeFormatter without a Locale.

*You can use y instead of u but I prefer u to y.

*How to use OffsetDateTime with JDBC.


text:
Q: obtain a new rotated imageIcon from another one? my problem is very simple:
I've got an ImageIcon, and i want to obtain another one that is rotated exactly rotation*90° times. This is the method:
private ImageIcon setRotation(ImageIcon icon, int rotation);

I would prefer not having to use an external class.
Thanks

A: Get BufferedImage from ImageIcon
All transformations to images are usually done to the BufferedImage. You can get Image from ImageIcon and then convert it to BufferedImage:
Image image = icon.getImage();
BufferedImage bi = new BufferedImage(
    image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics bg = bi.getGraphics();
bg.drawImage(im, 0, 0, null);
bg.dispose();

Rotate
Then you can rotate it -90 to 90 degrees using following code:
public BufferedImage rotate(BufferedImage bi, float angle) {
    AffineTransform at = new AffineTransform();
    at.rotate(Math.toRadians(angle), bi.getWidth() / 2.0, bi.getHeight() / 2.0);
    at.preConcatenate(findTranslation(at, bi, angle));

    BufferedImageOp op =
        new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    return op.filter(bi, null);
}

private AffineTransform findTranslation(
                        AffineTransform at, BufferedImage bi, float angle) {
    Point2D p2din = null, p2dout = null;

    if (angle > 0 && angle <= 90) {
        p2din = new Point2D.Double(0, 0);
    } else if (angle < 0 && angle >= -90) {
        p2din = new Point2D.Double(bi.getWidth(), 0);
    }
    p2dout = at.transform(p2din, null);
    double ytrans = p2dout.getY();

    if (angle > 0 && angle <= 90) {
        p2din = new Point2D.Double(0, bi.getHeight());
    } else if (angle < 0 && angle >= -90) {
        p2din = new Point2D.Double(0, 0);
    }
    p2dout = at.transform(p2din, null);
    double xtrans = p2dout.getX();

    AffineTransform tat = new AffineTransform();
    tat.translate(-xtrans, -ytrans);
    return tat;
}

This works great rotating image from -90 up to 90 degrees, it does not support more than that. You can run through AffineTransform documentation for more explanation on working with the coordinates.
Set BufferedImage to ImageIcon
Finally you populate ImageIcon with transformed Image: icon.setImage((Image) bi);.


text:
Q: Optimizing nested for loop algorithm, Javascript I am using the pokemon API to build a fun little informational app. I specifically want to have a section detailing the damage relationships of a pokemon. I currently retrieve and format the data as such:
Array [
  Object {
    "double_damage_from": Array [
      Object {
        "name": "flying",
        "url": "https://pokeapi.co/api/v2/type/3/",
      },
      Object {
        "name": "poison",
        "url": "https://pokeapi.co/api/v2/type/4/",
      },
      Object {
        "name": "bug",
        "url": "https://pokeapi.co/api/v2/type/7/",
      },
      Object {
        "name": "fire",
        "url": "https://pokeapi.co/api/v2/type/10/",
      },
      Object {
        "name": "ice",
        "url": "https://pokeapi.co/api/v2/type/15/",
      },
    ],
    "double_damage_to": Array [
      Object {
        "name": "ground",
        "url": "https://pokeapi.co/api/v2/type/5/",
      },
      Object {
        "name": "rock",
        "url": "https://pokeapi.co/api/v2/type/6/",
      },
      Object {
        "name": "water",
        "url": "https://pokeapi.co/api/v2/type/11/",
      },
    ],
    "half_damage_from": Array [
      Object {
        "name": "ground",
        "url": "https://pokeapi.co/api/v2/type/5/",
      },
      Object {
        "name": "water",
        "url": "https://pokeapi.co/api/v2/type/11/",
      },
      Object {
        "name": "grass",
        "url": "https://pokeapi.co/api/v2/type/12/",
      },
      Object {
        "name": "electric",
        "url": "https://pokeapi.co/api/v2/type/13/",
      },
    ],
    "half_damage_to": Array [
      Object {
        "name": "flying",
        "url": "https://pokeapi.co/api/v2/type/3/",
      },
      Object {
        "name": "poison",
        "url": "https://pokeapi.co/api/v2/type/4/",
      },
      Object {
        "name": "bug",
        "url": "https://pokeapi.co/api/v2/type/7/",
      },
      Object {
        "name": "steel",
        "url": "https://pokeapi.co/api/v2/type/9/",
      },
      Object {
        "name": "fire",
        "url": "https://pokeapi.co/api/v2/type/10/",
      },
      Object {
        "name": "grass",
        "url": "https://pokeapi.co/api/v2/type/12/",
      },
      Object {
        "name": "dragon",
        "url": "https://pokeapi.co/api/v2/type/16/",
      },
    ],
    "name": "grass",
    "no_damage_from": Array [],
    "no_damage_to": Array [],
  },
  Object {
    "double_damage_from": Array [
      Object {
        "name": "ground",
        "url": "https://pokeapi.co/api/v2/type/5/",
      },
      Object {
        "name": "psychic",
        "url": "https://pokeapi.co/api/v2/type/14/",
      },
    ],
    "double_damage_to": Array [
      Object {
        "name": "grass",
        "url": "https://pokeapi.co/api/v2/type/12/",
      },
      Object {
        "name": "fairy",
        "url": "https://pokeapi.co/api/v2/type/18/",
      },
    ],
    "half_damage_from": Array [
      Object {
        "name": "fighting",
        "url": "https://pokeapi.co/api/v2/type/2/",
      },
      Object {
        "name": "poison",
        "url": "https://pokeapi.co/api/v2/type/4/",
      },
      Object {
        "name": "bug",
        "url": "https://pokeapi.co/api/v2/type/7/",
      },
      Object {
        "name": "grass",
        "url": "https://pokeapi.co/api/v2/type/12/",
      },
      Object {
        "name": "fairy",
        "url": "https://pokeapi.co/api/v2/type/18/",
      },
    ],
    "half_damage_to": Array [
      Object {
        "name": "poison",
        "url": "https://pokeapi.co/api/v2/type/4/",
      },
      Object {
        "name": "ground",
        "url": "https://pokeapi.co/api/v2/type/5/",
      },
      Object {
        "name": "rock",
        "url": "https://pokeapi.co/api/v2/type/6/",
      },
      Object {
        "name": "ghost",
        "url": "https://pokeapi.co/api/v2/type/8/",
      },
    ],
    "name": "poison",
    "no_damage_from": Array [],
    "no_damage_to": Array [
      Object {
        "name": "steel",
        "url": "https://pokeapi.co/api/v2/type/9/",
      },
    ],
  },
]

What I want to do is format it like this.
DamageMap:  Map {
  "double_damage_from" => Array [
    "flying",
    "poison",
    "bug",
    "fire",
    "ice",
    "ground",
    "psychic",
  ],
  "double_damage_to" => Array [
    "ground",
    "rock",
    "water",
    "grass",
    "fairy",
  ],
  "half_damage_from" => Array [
    "ground",
    "water",
    "grass",
    "electric",
    "fighting",
    "poison",
    "bug",
    "fairy",
  ],
  "half_damage_to" => Array [
    "flying",
    "poison",
    "bug",
    "steel",
    "fire",
    "grass",
    "dragon",
    "ground",
    "rock",
    "ghost",
  ],
  "no_damage_from" => Array [],
  "no_damage_to" => Array [
    "steel",
  ],
}

The data is formatted into this map with no duplicate types. This is my current solution.
const keys = [
      "double_damage_from",
      "double_damage_to",
      "half_damage_from",
      "half_damage_to",
      "no_damage_from",
      "no_damage_to",
    ];
    const damageMap = new Map();

    for (let i = 0; i < results.length; ++i) {
      for (let j = 0; j < keys.length; ++j) {
        if (!damageMap.has(keys[j])) {
          damageMap.set(keys[j], []);
        }
        const val = damageMap.get(keys[j]);
        const curr = results[i][keys[j]];

        for (let k = 0; k < curr.length; ++k) {
          if (val.indexOf(curr[k].name) === -1) {
            val.push(curr[k].name);
          }
        }
        damageMap.set(keys[j], val);
      }
    }

    return damageMap;
  };

It is utterly atrocious... I know this. My problem is that any attempt at optimizing it has so far failed. I have tried using combinations of map and reduce functions to no avail. If anybody can take a look at this and optimize it, it would be greatly appreciated!

A: You may use Array.prototype.reduce() together with Array.prototype.forEach() instead:

const src = [{"double_damage_from":[{"name":"flying","url":"https://pokeapi.co/api/v2/type/3/",},{"name":"poison","url":"https://pokeapi.co/api/v2/type/4/",},{"name":"bug","url":"https://pokeapi.co/api/v2/type/7/",},{"name":"fire","url":"https://pokeapi.co/api/v2/type/10/",},{"name":"ice","url":"https://pokeapi.co/api/v2/type/15/",},],"double_damage_to":[{"name":"ground","url":"https://pokeapi.co/api/v2/type/5/",},{"name":"rock","url":"https://pokeapi.co/api/v2/type/6/",},{"name":"water","url":"https://pokeapi.co/api/v2/type/11/",},],"half_damage_from":[{"name":"ground","url":"https://pokeapi.co/api/v2/type/5/",},{"name":"water","url":"https://pokeapi.co/api/v2/type/11/",},{"name":"grass","url":"https://pokeapi.co/api/v2/type/12/",},{"name":"electric","url":"https://pokeapi.co/api/v2/type/13/",},],"half_damage_to":[{"name":"flying","url":"https://pokeapi.co/api/v2/type/3/",},{"name":"poison","url":"https://pokeapi.co/api/v2/type/4/",},{"name":"bug","url":"https://pokeapi.co/api/v2/type/7/",},{"name":"steel","url":"https://pokeapi.co/api/v2/type/9/",},{"name":"fire","url":"https://pokeapi.co/api/v2/type/10/",},{"name":"grass","url":"https://pokeapi.co/api/v2/type/12/",},{"name":"dragon","url":"https://pokeapi.co/api/v2/type/16/",},],"name":"grass","no_damage_from":[],"no_damage_to":[],},{"double_damage_from":[{"name":"ground","url":"https://pokeapi.co/api/v2/type/5/",},{"name":"psychic","url":"https://pokeapi.co/api/v2/type/14/",},],"double_damage_to":[{"name":"grass","url":"https://pokeapi.co/api/v2/type/12/",},{"name":"fairy","url":"https://pokeapi.co/api/v2/type/18/",},],"half_damage_from":[{"name":"fighting","url":"https://pokeapi.co/api/v2/type/2/",},{"name":"poison","url":"https://pokeapi.co/api/v2/type/4/",},{"name":"bug","url":"https://pokeapi.co/api/v2/type/7/",},{"name":"grass","url":"https://pokeapi.co/api/v2/type/12/",},{"name":"fairy","url":"https://pokeapi.co/api/v2/type/18/",},],"half_damage_to":[{"name":"poison","url":"https://pokeapi.co/api/v2/type/4/",},{"name":"ground","url":"https://pokeapi.co/api/v2/type/5/",},{"name":"rock","url":"https://pokeapi.co/api/v2/type/6/",},{"name":"ghost","url":"https://pokeapi.co/api/v2/type/8/",},],"name":"poison","no_damage_from":[],"no_damage_to":[{"name":"steel","url":"https://pokeapi.co/api/v2/type/9/",},],},],

    result = src.reduce((acc, o) => {
      Object.keys(o).forEach(key => {
        if(Array.isArray(o[key])){
          const match = acc.get(key),
                items = o[key].map(({name}) => name)
          match ?
          match.push(...items) :
          acc.set(key, items)
        }
       })
      return acc
    }, new Map)

console.log(result)

A: Does this work out?
I didn't know what to call each subelement from the main values array so thing is what i used.  But this just digs into there and pulls out the name from each of the sublevel elements and tallies them up.
I didn't worry about uniqueness but you could (after concat) add a uniq clean up thing.
// where `values` is your initial data structure

const damageMap = values.reduce((memo, thing) => {
  Object.keys(thing).forEach(key => {
    if (key !== 'name') {
      memo[key] = memo[key] || []
      memo[key] = memo[key].concat(
        thing[key].map(({name}) => name))
    }
  })
  return memo
},{});

A: Using Array.reduce for collecting the data, Array#forEach to iterate over the elements and Object.entries to get key/values from the object.
let map = arr.reduce((acc, cur) => {
   Object.entries(cur).forEach(([key, values]) => {
       if (!acc[key] && key !=='name') {
           acc[key] = [];
       }
       if (typeof(values)=== 'object') {
           values.forEach(({name}) => {
               acc[key].push(name);
           });
       }
   });
   return acc;
}, {});

Here for playing arround https://jsfiddle.net/h8kL5gp9/ or try this (with the hole code):

let arr = [
   {
    "double_damage_from": [
      {
        "name": "flying",
        "url": "https://pokeapi.co/api/v2/type/3/",
      },
      {
        "name": "poison",
        "url": "https://pokeapi.co/api/v2/type/4/",
      },
      {
        "name": "bug",
        "url": "https://pokeapi.co/api/v2/type/7/",
      },
      {
        "name": "fire",
        "url": "https://pokeapi.co/api/v2/type/10/",
      },
      {
        "name": "ice",
        "url": "https://pokeapi.co/api/v2/type/15/",
      },
    ],
    "double_damage_to": [
      {
        "name": "ground",
        "url": "https://pokeapi.co/api/v2/type/5/",
      },
      {
        "name": "rock",
        "url": "https://pokeapi.co/api/v2/type/6/",
      },
      {
        "name": "water",
        "url": "https://pokeapi.co/api/v2/type/11/",
      },
    ],
    "half_damage_from": [
      {
        "name": "ground",
        "url": "https://pokeapi.co/api/v2/type/5/",
      },
      {
        "name": "water",
        "url": "https://pokeapi.co/api/v2/type/11/",
      },
      {
        "name": "grass",
        "url": "https://pokeapi.co/api/v2/type/12/",
      },
      {
        "name": "electric",
        "url": "https://pokeapi.co/api/v2/type/13/",
      },
    ],
    "half_damage_to": [
      {
        "name": "flying",
        "url": "https://pokeapi.co/api/v2/type/3/",
      },
      {
        "name": "poison",
        "url": "https://pokeapi.co/api/v2/type/4/",
      },
      {
        "name": "bug",
        "url": "https://pokeapi.co/api/v2/type/7/",
      },
      {
        "name": "steel",
        "url": "https://pokeapi.co/api/v2/type/9/",
      },
      {
        "name": "fire",
        "url": "https://pokeapi.co/api/v2/type/10/",
      },
      {
        "name": "grass",
        "url": "https://pokeapi.co/api/v2/type/12/",
      },
      {
        "name": "dragon",
        "url": "https://pokeapi.co/api/v2/type/16/",
      },
    ],
    "name": "grass",
    "no_damage_from": [],
    "no_damage_to": [],
  },
  {
    "double_damage_from": [
      {
        "name": "ground",
        "url": "https://pokeapi.co/api/v2/type/5/",
      },
      {
        "name": "psychic",
        "url": "https://pokeapi.co/api/v2/type/14/",
      },
    ],
    "double_damage_to": [
      {
        "name": "grass",
        "url": "https://pokeapi.co/api/v2/type/12/",
      },
      {
        "name": "fairy",
        "url": "https://pokeapi.co/api/v2/type/18/",
      },
    ],
    "half_damage_from": [
      {
        "name": "fighting",
        "url": "https://pokeapi.co/api/v2/type/2/",
      },
      {
        "name": "poison",
        "url": "https://pokeapi.co/api/v2/type/4/",
      },
      {
        "name": "bug",
        "url": "https://pokeapi.co/api/v2/type/7/",
      },
      {
        "name": "grass",
        "url": "https://pokeapi.co/api/v2/type/12/",
      },
      {
        "name": "fairy",
        "url": "https://pokeapi.co/api/v2/type/18/",
      },
    ],
    "half_damage_to": [
      {
        "name": "poison",
        "url": "https://pokeapi.co/api/v2/type/4/",
      },
      {
        "name": "ground",
        "url": "https://pokeapi.co/api/v2/type/5/",
      },
      {
        "name": "rock",
        "url": "https://pokeapi.co/api/v2/type/6/",
      },
      {
        "name": "ghost",
        "url": "https://pokeapi.co/api/v2/type/8/",
      },
    ],
    "name": "poison",
    "no_damage_from": [],
    "no_damage_to": [
      {
        "name": "steel",
        "url": "https://pokeapi.co/api/v2/type/9/",
      },
    ],
  },
];

let map = arr.reduce((acc, cur) => {
   Object.entries(cur).forEach(([key, values]) => {
       if (!acc[key] && key !=='name') {
           acc[key] = [];
       }
       if (typeof(values)=== 'object') {
           values.forEach(({name}) => {
               acc[key].push(name);
           });
       }
   });
   return acc;
}, {});

console.log(map);


text:
Q: 3D tensor subsetting operation I'm trying to perform a specific operation on a 3D tensor. I'll just show it below using a 3D numpy array instead. Basically I want to do the same operation as below but on an equivalent tensor.
a3 = np.array([[[1,0,0],[1,0,0],[1,0,0],[1,0,0],[0,1,0],[0,1,0],[0,0,1],[0,0,1]], [[1,0,0],[1,0,0],[1,0,0],[1,0,0],[0,0,1],[0,0,1],[0,0,1],[0,0,1]], [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]])

expression = (a3.sum(axis=(1,2)) >= 1)

a3[expression, :, 1].flatten()

It should return a list of the same length as the first dimension of the initial 3D tensor.
I've tried to write some code based on tf.constant, but it has not worked so far. Here's my attempt:
a3 = tf.convert_to_tensor(a3)
one = tf.constant(1, dtype=tf.int32)
mask = tf.keras.backend.greater_equal(tf.keras.backend.sum(a3,axis=(1,2)),one)
tf.boolean_mask(a3,mask,axis=0)
sess = tf.compat.v1.Session()

with sess.as_default():
    assert tf.compat.v1.get_default_session() is sess
    print(a3.eval())

A: Ok figured it out:
a3 = tf.convert_to_tensor(a3)
one = tf.constant(1, dtype=tf.int32)
mask = tf.keras.backend.greater_equal(tf.keras.backend.sum(a3,axis=(1,2)),one)
a4masked = tf.boolean_mask(a3,mask,axis=0)
a4flat = tf.reshape(a4masked, [tf.size(a4masked)])

sess = tf.compat.v1.Session()

with sess.as_default():
  assert tf.compat.v1.get_default_session() is sess
  print(a4flat.eval())


text:
Q: Mysql Multiple SUM query with JOIN I am attempting to update a Mysql table based on a SUM query of another table.
I am getting back  "Unknown column 't2.part_number' in 'on clause'"
Here is my query
UPDATE Dream t1 JOIN
   (
    SELECT SUM(`t2`.`Sales_1_Month_Prior`)+SUM(`t2`.`Sales_2_Month_Prior`)+SUM(`t2`.`Sales_3_Month_Prior`)+SUM(`t2`.`Sales_4_Month_Prior`)+SUM(`t2`.`Sales_5_Month_Prior`)+SUM(`t2`.`Sales_6_Month_Prior`)+SUM(`t2`.`Sales_7_Month_Prior`)+SUM(`t2`.`Sales_8_Month_Prior`)+SUM(`t2`.`Sales_9_Month_Prior`)+SUM(`t2`.`Sales_10_Month_Prior`)+SUM(`t2`.`Sales_11_Month_Prior`)+SUM(`t2`.`Sales_12_Month_Prior`) as Total
    FROM saleshistory t2
    WHERE location = '98'
   ) t2
   ON `t1`.`Part_Number` = `t2`.`part_number`
SET `t1`.`ETAUsage` = `t2`.`Total`

A: You don't select a Part_Number  in your subquery for join on condition
so eg: try selecting  (and group by for get the proper sum result)
  UPDATE Dream t1
  JOIN
     (
      SELECT `t2`.`Part_Number`,
      SUM(`t2`.`Sales_1_Month_Prior`)+
        SUM(`t2`.`Sales_2_Month_Prior`)+
        SUM(`t2`.`Sales_3_Month_Prior`)+
        SUM(`t2`.`Sales_4_Month_Prior`)+
        SUM(`t2`.`Sales_5_Month_Prior`)+
        SUM(`t2`.`Sales_6_Month_Prior`)+
        SUM(`t2`.`Sales_7_Month_Prior`)+
        SUM(`t2`.`Sales_8_Month_Prior`)+
        SUM(`t2`.`Sales_9_Month_Prior`)+
        SUM(`t2`.`Sales_10_Month_Prior`)+
        SUM(`t2`.`Sales_11_Month_Prior`)+
        SUM(`t2`.`Sales_12_Month_Prior`) as Total
      FROM saleshistory t2
      WHERE location = '98'
      group by  `t2`.`Part_Number`
     ) t3
     ON `t1`.`Part_Number` = `t3`.`part_number`
  SET `t1`.`ETAUsage` = `t3`.`Total`

A: you can resolve this isue by changing  as Total in your sub query by as part_number

A: In "on clause" t2 is not referring to table "saelshistory" but instead it refers to the temporary table created using the select query on saleshistory.
To be able to refer to part_number, it has to be selected first and then used in group by, this would change the totals but it looks like you need the aggregation by part_number anyway,
outer table alias t2 should be like
SELECT part_number, SUM(....
FROM saleshistory
GROUP BY part_number


text:
Q: Heroku push rejected, failed to install gems via Bundler Having issues trying to push for the first time to a heroku app, Ive created the app online and added the heroku git. but after doing
git push heroku master

And I get the following response
-----> Heroku receiving push
-----> Ruby/Sinatra app detected
-----> Gemfile detected, running Bundler version 1.0.7
       Unresolved dependencies detected; Installing...
       Using --without development:test
       You have modified your Gemfile in development but did not check
       the resulting snapshot (Gemfile.lock) into version control

       You have added to the Gemfile:
       * reloader

       You have deleted from the Gemfile:
       * fleakr
       FAILED: http://devcenter.heroku.com/articles/bundler
 !     Heroku push rejected, failed to install gems via Bundler

To git@heroku.com:boxing-api.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:boxing-api.git'

What is it that I am missing?
I am running on Windows
------ EDIT -----
This is what I get from running "bundle install"
C:\Users\Steve\Documents\GitRespository\score card app>bundle install
Fetching source index for http://rubygems.org/
Using multi_json (1.0.4)
Using activesupport (3.1.3)
Using builder (3.0.0)
Using i18n (0.6.0)
Using activemodel (3.1.3)
Using addressable (2.2.6)
Using backports (2.3.0)
Using bson (1.5.2)
Using bson_ext (1.5.2)
Using daemons (1.1.8)
Using dm-core (1.2.0)
Using dm-migrations (1.2.0)
Using dm-timestamps (1.2.0)
Using dm-validations (1.2.0)
Using escape_utils (0.2.4)
Installing eventmachine (0.12.10) with native extensions
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension
.

        C:/Ruby193/bin/ruby.exe extconf.rb
checking for rb_trap_immediate in ruby.h,rubysig.h... no
checking for rb_thread_blocking_region()... yes
checking for inotify_init() in sys/inotify.h... no
checking for __NR_inotify_init in sys/syscall.h... no
checking for writev() in sys/uio.h... no
checking for rb_thread_check_ints()... yes
checking for rb_time_new()... yes
checking for windows.h... yes
checking for winsock.h... yes
checking for main() in -lkernel32... yes
checking for main() in -lrpcrt4... yes
checking for main() in -lgdi32... yes
checking for main() in -lssl... no
creating Makefile

make
generating rubyeventmachine-i386-mingw32.def
compiling binder.cpp
cc1plus.exe: warning: command line option "-Wdeclaration-after-statement" is val
id for C/ObjC but not for C++
cc1plus.exe: warning: command line option "-Wimplicit-function-declaration" is v
alid for C/ObjC but not for C++
In file included from project.h:137:0,
                 from binder.cpp:20:
binder.h:35:34: warning: type qualifiers ignored on function return type
In file included from project.h:138:0,
                 from binder.cpp:20:
em.h:91:47: warning: type qualifiers ignored on function return type
em.h:92:76: warning: type qualifiers ignored on function return type
em.h:93:56: warning: type qualifiers ignored on function return type
em.h:95:57: warning: type qualifiers ignored on function return type
em.h:96:60: warning: type qualifiers ignored on function return type
em.h:97:58: warning: type qualifiers ignored on function return type
em.h:98:55: warning: type qualifiers ignored on function return type
em.h:99:36: warning: type qualifiers ignored on function return type
em.h:101:47: warning: type qualifiers ignored on function return type
em.h:106:42: warning: type qualifiers ignored on function return type
em.h:123:45: warning: type qualifiers ignored on function return type
em.h:132:36: warning: type qualifiers ignored on function return type
In file included from project.h:145:0,
                 from binder.cpp:20:
eventmachine.h:45:61: warning: type qualifiers ignored on function return type
eventmachine.h:46:112: warning: type qualifiers ignored on function return type
eventmachine.h:47:69: warning: type qualifiers ignored on function return type
eventmachine.h:49:73: warning: type qualifiers ignored on function return type
eventmachine.h:62:75: warning: type qualifiers ignored on function return type
eventmachine.h:63:74: warning: type qualifiers ignored on function return type
eventmachine.h:64:77: warning: type qualifiers ignored on function return type
eventmachine.h:65:41: warning: type qualifiers ignored on function return type
In file included from project.h:145:0,
                 from binder.cpp:20:
eventmachine.h:99:60: warning: type qualifiers ignored on function return type
eventmachine.h:100:58: warning: type qualifiers ignored on function return type
eventmachine.h:102:60: warning: type qualifiers ignored on function return type
eventmachine.h:105:41: warning: type qualifiers ignored on function return type
compiling cmain.cpp
cc1plus.exe: warning: command line option "-Wdeclaration-after-statement" is val
id for C/ObjC but not for C++
cc1plus.exe: warning: command line option "-Wimplicit-function-declaration" is v
alid for C/ObjC but not for C++
In file included from project.h:137:0,
                 from cmain.cpp:20:
binder.h:35:34: warning: type qualifiers ignored on function return type
In file included from project.h:138:0,
                 from cmain.cpp:20:
em.h:91:47: warning: type qualifiers ignored on function return type
em.h:92:76: warning: type qualifiers ignored on function return type
em.h:93:56: warning: type qualifiers ignored on function return type
em.h:95:57: warning: type qualifiers ignored on function return type
em.h:96:60: warning: type qualifiers ignored on function return type
em.h:97:58: warning: type qualifiers ignored on function return type
em.h:98:55: warning: type qualifiers ignored on function return type
em.h:99:36: warning: type qualifiers ignored on function return type
em.h:101:47: warning: type qualifiers ignored on function return type
em.h:106:42: warning: type qualifiers ignored on function return type
em.h:123:45: warning: type qualifiers ignored on function return type
em.h:132:36: warning: type qualifiers ignored on function return type
In file included from project.h:145:0,
                 from cmain.cpp:20:
eventmachine.h:45:61: warning: type qualifiers ignored on function return type
eventmachine.h:46:112: warning: type qualifiers ignored on function return type
eventmachine.h:47:69: warning: type qualifiers ignored on function return type
eventmachine.h:49:73: warning: type qualifiers ignored on function return type
eventmachine.h:62:75: warning: type qualifiers ignored on function return type
eventmachine.h:63:74: warning: type qualifiers ignored on function return type
eventmachine.h:64:77: warning: type qualifiers ignored on function return type
eventmachine.h:65:41: warning: type qualifiers ignored on function return type
In file included from project.h:145:0,
                 from cmain.cpp:20:
eventmachine.h:99:60: warning: type qualifiers ignored on function return type
eventmachine.h:100:58: warning: type qualifiers ignored on function return type
eventmachine.h:102:60: warning: type qualifiers ignored on function return type
eventmachine.h:105:41: warning: type qualifiers ignored on function return type
cmain.cpp:98:71: warning: type qualifiers ignored on function return type
cmain.cpp:109:122: warning: type qualifiers ignored on function return type
cmain.cpp:119:79: warning: type qualifiers ignored on function return type
cmain.cpp:129:83: warning: type qualifiers ignored on function return type
cmain.cpp:260:85: warning: type qualifiers ignored on function return type
cmain.cpp:270:84: warning: type qualifiers ignored on function return type
cmain.cpp:280:88: warning: type qualifiers ignored on function return type
cmain.cpp:290:51: warning: type qualifiers ignored on function return type
cmain.cpp:300:70: warning: type qualifiers ignored on function return type
cmain.cpp:320:55: warning: type qualifiers ignored on function return type
cmain.cpp:546:70: warning: type qualifiers ignored on function return type
cmain.cpp:669:68: warning: type qualifiers ignored on function return type
cmain.cpp: In function 'int evma_send_file_data_to_connection(long unsigned int,
 const char*)':
cmain.cpp:752:6: error: cannot convert 'stat*' to '_stati64*' for argument '2' t
o 'int _fstati64(int, _stati64*)'
make: *** [cmain.o] Error 1

Gem files will remain installed in C:/Ruby193/lib/ruby/gems/1.9.1/gems/eventmach
ine-0.12.10 for inspection.
Results logged to C:/Ruby193/lib/ruby/gems/1.9.1/gems/eventmachine-0.12.10/ext/g
em_make.out
An error occured while installing eventmachine (0.12.10), and Bundler cannot con
tinue.
Make sure that `gem install eventmachine -v '0.12.10'` succeeds before bundling.

A: Run bundle install, add Gemfile.lock to your repository, commit, and then push again.
Heroku needs both Gemfile and Gemfile.lock to install your dependencies.

Check this out for your Event Machine build problem: Ruby: problem installing EventMachine under Windows 7


text:
Q: iOS in app purchase event stream keeps firing purchase events after purchase is finished I'm working on in-app purchases (non-consumable subscriptions) using the official flutter in_app_purchase package. I start listening to purchaseUpdatedStream as soon as the user opens a page where he can buy a subscription. Once I validate a successful purchase I call completePurchase() method, but purchaseUpdatedStream keeps sending me events with old completed subscriptions even when the subscription is expired. What do I do wrong?
My success purchases processing code:
Future<void> _handleSuccess(PurchaseDetails lastPurchase) async {
    var verificationData = lastPurchase.verificationData;

    if (Platform.isIOS) {
      verificationData = await InAppPurchaseConnection.instance.refreshPurchaseVerificationData();
    }

    try {
      if (!await _apiService.verifySubscription(verificationData)) {
        if (Platform.isIOS) {
          await InAppPurchaseConnection.instance.completePurchase(lastPurchase);
        }
        purchasesLogInfo.add('Serverside receipt verification failed');
        _purchasingStatusSink.add(PurchasingState.internalError);
        throw Exception(
            'Purchase with id ${lastPurchase.purchaseID} for product with id ${lastPurchase.productID} verification failed.');
      }
    } catch (e) {
      _purchasingStatusSink.add(PurchasingState.verificationApiConnectionError);
      rethrow;
    }

    purchasesLogInfo.add('Serverside receipt verification successful');

    if (Platform.isIOS) {
      await InAppPurchaseConnection.instance.completePurchase(lastPurchase);
    }

    await updateUserStatus();
    _purchasingStatusSink.add(PurchasingState.successPayment);
  }


text:
Q: tabgroupactivity in android with BaseAdapter I have to develop an one android application.
Here i  have using tabgroup activity.
i have using following code on my adapter file:
   convertView.setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {
                 ArrayList<SubCategory> beanSubCat = categoriesList.getmSubCategories();
                Intent intent = new Intent(getParent(),SubCategoryDetails.class);
                 TabGroupActivity parentActivity = (TabGroupActivity) getParent();
                intent.putExtra("SubCategoryDetails", beanSubCat);
                intent.putExtra("title", categoriesList.getmCategoryName());
    parentActivity.startChildActivity("SubCategoryDetails",intent);

i am getting following error :
The method getParent() is undefined for the type new View.OnClickListener(){}
How can i resolve these error .. please give me solution for these ???
EDIT:
I have using adapter class here.(For eg:public class CategoriesAdapter extends BaseAdapter)how can i get the getparent() in Adapter class ??? please give me solution ???
EDIT:
I have using following code:
  Intent intent = new Intent(activity,SubCategoryDetails.class);
                intent.putExtra("SubCategoryDetails", beanSubCat);
                intent.putExtra("title", categoriesList.getmCategoryName());
                activity.startActivity(intent);

Now am activity is going to next activity well.
But i have using tabgroupactivity means am getting above error ???
please give me any ideas ???

A: Try this code,
Activity activity;
Intent intent = new Intent(activity.getParent(),SubCategoryDetails.class);


text:
Q: I need to get all the possible 10 combinations from this array into another array. All I'm getting from my code is the possible of 3 combinations I need to get all the possible 10 combinations from this array into another array. All I'm getting from my code is the possible of 3 combinations
    let X = ['Me', 'You', 'Her', 'Him', 'Them', 'She', 'juice', 'mango', 'orange', 'pillow', 'clock', 'tyre', 'car', 'calendar', 'fan', 'cloth', 'television', 'laptops', 'Honda', 'remote', 'echo'];

    function combinations(arr) {

        let sets = [];
        let length = arr.length;
        let firstHalf = arr.slice(0, length/2);
        let secondHalf = arr.slice(-length/2);

        sets.push(firstHalf, secondHalf);
        push(firstHalf, secondHalf, sets);
        push(firstHalf, secondHalf, sets);

        return [sets, `The number of possible combinations: ${sets.length}`];
    }

    function push(A, B, arr){

        let i=0, j=0, k=1;
        while(i+k < A.length){
            for(let j=0; j<B.length; j++){
                arr.push([A[i], A[i+k], B[j]]);
            }
            k++;
            if(k === 3){
                i++;
                k=1;
            }
        }
    }

    console.log(combinations(X));

A: I didn't understand you question properly but here is how you can find all the possible combinations of a given array.
Total number of combinations is 2 ^ (length of array). Assuming no duplicates.
For your array it will be 2 ^ 21 = 2097152.

const combinations = xs =>
    xs.reduce((acc, x) => [...acc, ...acc.map(a => a.concat(x))], [[]])

const t = combinations([1,2,3]);
console.log(t.length, t);


text: Q: Read udp image in gluon mobile Hi How to read a coded image in bytearrayinputstream on mobile gluon While android does not recognize the ImageIO.read () function and that bitmap does not exist sir gluon The image is sent in UDP


text:
Q: How can I get multiple inputs from the user that are in a list to print while the program loops in Python?
*

*I got the program to loop and to ask the user for input. The problem is...when I try to print it keeps giving me an error. I need it to be in a specific format. Any help will be greatly appreciated.

*Here is the error:
Traceback (most recent call last):
File "C:\Users\one\Desktop\Sherry\Python Folder\Week 4\w4_sgomez_assgn.py", line 40, in <module>
print('\t-----' + employee[0:4] + '-----\n')
TypeError: can only concatenate str (not "list") to str

*Here is the code:
employee=[]
count=0

def addEmpl(employee, count):
  if count < 5:
   name=input('Enter Employee Name: ')
   ssn=input('Enter Employee SSN: ')
   phone=input('Enter Employee Phone: ')
   email=input('Enter Employee Email: ')
   salary=input('Enter Employee Salary: ')
   report = name +',' + ssn + ',' + phone +','+ email +',' + salary
   employee.insert(count,report)
   count=count+1

def printEmpl(employee):
  number=int(input('Press 0 to print list: '))
  count = len(employee)
  if (number>-1) and (number<1):
   employee=employee[0]
   employee='\n'.join([name,ssn, phone, email, salary])
   employee[:]
   print('\t-----' + employee[0:4] + '-----\n')
   print('SSN: ' + employee[1] + '\n')
   print('Phone: ' + employee[2] + '\n')
   print('Email: ' + employee[3] + '\n')
   print('Salary: $' + employee[4] + '\n')
   print('\t-----------')
  else:
   return;

while True:
  addEmp2=int(input('To add employee enter 1; to print enter 2; to search by ssn enter 3: '))
  if (addEmp2 > 0)and(addEmp2 < 2):
   addEmpl(employee, count)
  else:
   print('\t-----' + employee[0:4] + '-----\n')
   print('SSN: ' + employee[1] + '\n')
   print('Phone: ' + employee[2] + '\n')
   print('Email: ' + employee[3] + '\n')
   print('Salary: $' + employee[4] + '\n')
   print('\t-----------')

A: Please find the correct code for function addEmpl below
def addEmpl(employee, count):
  if count < 5:
   name=raw_input('Enter Employee Name: ')
   ssn=raw_input('Enter Employee SSN: ')
   phone=raw_input('Enter Employee Phone: ')
   email=raw_input('Enter Employee Email: ')
   salary=raw_input('Enter Employee Salary: ')
   report = name +',' + ssn + ',' + phone +','+ email +',' + salary
   employee.insert(count,report)
   count=count+1

Since, you have not given the complete error, so as per my best guess I tried to fix it. Please let me know if my understand is not correct.

A: The following line is triggering the error (it is in 2 places)
print('\t-----' + employee[0:4] + '-----\n')

You are using + operator on a string and list together employee[0:4] is a list.
Hence the error
TypeError: can only concatenate str (not "list") to str

A: The problem is the following line:
 print('\t-----' + employee[0:4] + '-----\n')

You can't print it as is you need to convert the list to a string.
Something like
string=""
for x in range(len(employee)):
    string=string+x
 print('\t-----' + string + '-----\n')

The real problem here though is the structure you should really be using a class for this instead of a list like so.
class Employee:
    def __init__(self,name,ssn,phone,email,salary):
        self.name=name
        self.ssn=ssn
        self.phone=phone
        self.email=email
        self.salary=salary

empObj=Employee("RandomName",1231231,"444-777-8000","pretendEmail@somewhere.com",4000)
print(empObj.name)


text:
Q: Should the model be responsible for holding lists that will ultimately populate dropdownlists in the view? This might be similar to ASP.NET MVC - Populate Commonly Used Dropdownlists.
I want to populate DropDownLists. Some of it is static data. Some of it comes from the Database. A couple of times I found myself forgetting to call the code that populates my lists and sets the ViewBag accordingly. It is almost worth adding a unit test for this. The only way I think that this suits a unit test is if you place it in model/service. Is there a best practice for this kind of thing?

A: I'd suggest that the data is contained within the model but is perhaps constructed by a html.helper method. this way, you keep the plumbing markup out of the view and leave the controller free to invoke the neccesary view and model.
You could also of course hand it off to a partialview with an <IList<SelectList>> model.
cats and their skin :)

A: If you follow the spirit of the pattern then the Model should supply the View with everything it needs to present to the user that's not static. If you have static dropdown lists then you could say that these could be constructed within the mark-up. If you are passing a SelectList to the View from your Action then I'd stick it in the Model to make things simpler and more coherent.

A: My rule of thumb is that the data must somehow be in the model, either as a ready to use SelectList or at worst in some container that can easily be turned into a SelectList using a LINQ-to-object call.
The bottom line is that the view should never contain any non trivial code.
EDIT (answer to your comment):
I try not to put too much code in models. Models are more like a simple bunch of data gathered by the controller and used by the view.
Regarding simple and/or common things such as the days of week, I believe an HTML helper is the most elegant solution. See WayneC's answer in this question.


text:
Q: why is this tetx not overflowing on the x axis even though I have a fixed width and the I need the text to overflow on the X axis just to reproduce some issue that I'm having on a bigger project. I leave a simple snippet, so you can tell me where I'm doing it wrong. Thanks!

.article {
  background-color: rgb(236, 161, 161);
  width: 20em;
}

.article p {
  display: block;
}

Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis deleniti iure quidem distinctio officia voluptates similique molestiae culpa? Perferendis, velit maiores nobis maxime aut facere eaque quis voluptas accusamus commodi.

A: If you want the p tag to overflow on the x-axis, you simply need to tell it not to wrap using the white-space property:

article{
    width: 20em;
    background-color: rgb(236, 161, 161);
}

article p{
    display: block;

    /* Do NOT break the text onto a new line when it reaches the container bounds. */
    white-space: nowrap;
}

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis deleniti iure quidem distinctio officia voluptates similique molestiae culpa? Perferendis, velit maiores nobis maxime aut facere eaque quis voluptas accusamus commodi.


text:
Q: Probability of picking kth item at odd turn There are n items in a line. Items are to be picked one by one and removed.
So after each turn one item is removed and the next item is picked from remaining items.
Constraint is that only first item or last item from the remaining items can be picked with probability 0.5.
The last item remaining will be picked by probability 1.
So what is the probability that kth item is picked at odd number of turn means probability of picking kth item in 1st, 3rd ,5th turn and so on.
For clarification, if n=2, then in first turn either item can be picked with probability 0.5 leaving one item which will be picked in next turn.
if n>2, second item can't be picked in first turn, it can be picked in second turn or more turns.

A: I'll do a special case. Consider an item at an end of the line. It's picked at the first turn with probability 1/2; at the third turn with probability 1/8; fifth turn, 1/32, and so on. As $n\to\infty$, the probability such an item is chosen at an odd turn approaches $$1/2+1/8+1/32+\cdots=2/3$$

A: Let $P(n,k)$ denote the desired probability for odd number of steps. Then we have
$$ P(n,k,even) = 1-P(n,k)$$
$$ P(n,k) = P(n,n+1-k) $$
$$ P(n,k) =0\ \text{ if }\ k\le 0\ \text{ or }\ k>n$$
$$ P(1,1) = 1$$

$$ \begin{align*} P(n,k ) &=\frac12\cdot (1- P(n-1,k))+\frac12\cdot (1-P(n-1,k-1))
\\ &=1-\frac12\cdot\left(P(n-1,k)+P(n-1,k-1)\right)
\end{align*}$$

So, it is a recurrence, similar to Pascal's triangle.
For example, it gives $P(2,1) = 1/2$, $P(3,1)=1-1/2\cdot(P(2,1)+P(2,0))=3/4$ $P(3,2)=1-1/2\cdot(P(2,2)+P(2,1)) = 1/2$, $P(4,1)=1-1/2\cdot3/4 = 5/8$, $P(4,2)=1-1/2\cdot(1/2+3/4)=3/8$...
So, something like (multiplied the $n$th row by $\displaystyle\frac1{2^{n-1}}$):
$$\begin{bmatrix} 1 \\ 1&1\\ 3&2&3\\ 5&3&3&5 \\ 11&8&10&8&11\\
\vdots&&&&& \ddots \end{bmatrix}$$
Update: Meanwhile I calculated the generator function (better starting with $n=k=0$, but doesn't really matter):
$$F(x,y):=\sum_{n,k} P(n,k)\cdot x^ny^k$$
By the recurrence law, we get
$$F(x,y)=\sum_{n,k}x^ny^k-\frac12xy\cdot F(x,y)-\frac12x\cdot F(x,y)$$
And hence, using $\sum x^ny^k =\frac1{1-x}\cdot\frac1{1-y}$, we arrive to
$$F(x,y)= \frac{1}{(1-x)(1-y)(1+(xy+x)/2)}$$
Then use $\frac1{1-z}$ and the binomial thm for $(1+y)^k$.
Unless I miscalculated, it yields
$$P(u,v) = \sum_{k\le u,\,l\le v}\frac1{(-2)^k}\cdot\begin{pmatrix}k\\l\end{pmatrix}$$

A: Define
$P(S_i)=Probability\ of\ success\ in\ i'th\ turn\ (We\ pick\ K'th\ element\ in\ this\ turn)$
$P(F_i)=Probability\ of\ fail\ in\ i'th\ turn\ (We\ don't\ pick\ K'th\ element\ in\ this\ turn)$
so for all $i<n$ we have:
$P(S_i) = P(F_{i-1}) * {{1}\over{2}}$
but for $i = n$ (last turn), we have only one item and we pick it with probabilty $1$ so we have:
$P(S_n) = P(F_{n-1}) * 1$
$P(F_n) = 0$
in similar manner we define
$P(F_i) = {1\over2} * P(F_{i-1})$
so we have
$P(S_1) = {1\over2} \\P(F_1) = {1\over2} \\P(S_2) = {1\over2}*P(F_1) = {1\over4}\\
P(F_2) = {1\over2}*P(F_1) = {1\over4}\\...\\
P(S_i) = {1\over{2^i}}\\P(F_i)={1\over{2^i}}\\...
\\ P(S_{n-1})={1\over{2^{n-1}}}\\P(F_{n-1})={1\over{2^{n-1}}}\\
P(S_n) = {1\over{2^{n-1}}}\\P(F_n)=0$
now probability of picking k'th element in the odd turn is equal to some over all $P(S_i)$ where $i$ is odd
Finally we have:
if $n$ is even we have
$\Sigma_{i=1,3,...,n-1}{P(S_i)} = \Sigma_{i=1,3,...,n-1}{1\over{2^i}}$
if $n$ is odd we have
$[\Sigma_{i=1,3,...,n-2}{P(S_i)}] + P(S_n) = [\Sigma_{i=1,3,...,n-2}{1\over{2^i}}] + {1\over{2^{n-1}}}$

A: For a given case, if the numbers are not too big, you can do this by hand. Take, for example, $n=17$ items, with $k=6$; we want the probability that the 6th item is picked on an odd turn. Each turn removes either the first remaining item ($F$) or the last remaining item ($L$), with equal probability. So we just enumerate the different ways of arriving at item 6 after an odd number of turns:
$5F$ and $1L$ in any order, followed by an $F$: $p={6\choose1}/2^7$
$5F$ and $3L$ in any order, followed by an $F$: $p={8\choose3}/2^9$
$5F$ and $5L$ in any order, followed by an $F$: $p={10\choose5}/2^{11}$
$5F$ and $7L$ in any order, followed by an $F$: $p={12\choose7}/2^{13}$
$5F$ and $9L$ in any order, followed by an $F$: $p={14\choose9}/2^{15}$
$1F$ and $11L$ in any order, followed by an $L$: $p={12\choose1}/2^{13}$
$3F$ and $11L$ in any order, followed by an $L$: $p={14\choose3}/2^{15}$
$5F$ and $11L$ in any order, and then only item 6 remains: $p={16\choose5}/2^{16}$
But I can't see any way to get a nice formula for the sum of these probabilities.


text:
Q: A problem related to continuity A function f(x) is defined by the following formulas
f(x) = $x^2$ + 1 when x is irrational,
   tan(x) when x is rational.

At how many x in the interval [0, 4$\pi$] is f(x) continuous?
on solving i hope there is 4 x in the interval.but while i try to get use definition of continuity I'm not sure whether i done correctly.Any answer using $\varepsilon$ and $\delta$ method or sequential definition of continuity is appreciable

A: You are right in saying that $f$ will be continuous at $x$ if and only if $\tan(x)=x^2+1$. Sequential continuity is the same as continuity for such functions.
The next task is to count the number of solutions of that equation. Let $g(x)=x^2+1$. First on the interval $[0,\pi/2[$ we have $\tan(0)=0$ and $g(0)=1$, but $\tan(x)\rightarrow\infty$ as $x\rightarrow\left(\dfrac{\pi}{2}\right)^-$ while $g$ stays bounded. You can summon the intermediate value theorem to show that there is a solution to $\tan(x)=x^2+1$ on the interval $[0,\pi/2[$.
Apply a similar reasoning to the intervals $]\pi/2,3\pi/2[$, $]3\pi/2,5\pi/2[$ and $]5\pi/2,7\pi/2[$. Clearly there is no solution on $]7\pi/2,4\pi]$ (Why?).


text:
Q: Rails nested routes navigation I have nested routes
resources :events do
    resources :registrations
end

Page /events/1/registrations shows all the registrations for event 1.
I'd like to have a form on this page or maybe a select box with a link to navigate to /events/n/registrations.
Actually, I came up with select_tag, link_to and js setting link's href on select_tag change. But I suspect it's overkill.
Thanks.

A: Why don't you add a scope/method to your event model that finds the next model in the list and link to that?
class Event
  # ...
  scope :next_event, -> { where('id > ?', id).first } # change logic as required
end

Then in your view you can simply link to it
# ... /app/views/events/show.html....
# NOTE: assumes there is an event.title field
= link_to @event.next_event.title, events_registrations_path(@event.next_event)

Be aware that this will do a seperate load of the next event, note recommended to be used in a list. In a production app you'd probably load this as part of a decorator for this particular scenario.


text:
Q: How to add own style and html to zencart products I want add my own style and html to the products in zencart.
I have looked into the product_listing.php ,new_products.php, and featured_products.php in modules folder front end.
But i have no idea how to do that. Any hints or example?
Thanks in advance.

A: Try to give div in all products
like css
.product
{
  //your properties
  font-size: 11pt;
  font-family: verdana;
  font-weight: bold;
}

in loop
//Start loop
<div class="product">
    //Product
</div>
//End loop


text:
Q: Complete control over Nivo Slider I have implemented a Nivo Slider in my Drupal site and I am not getting the control I want for styling it.
I know by default Nivo Slider only supports Image, Title, and Link fields for Drupal rows.  I did find a workaround to get the teaser to show with the title however:

but looking at the generated HTML in FireFox, I see that my DIVs do not get printed.

How can I get complete control over my Nivo Slider when using Drupal?  I want to be able to print as many DIVs and use CSS to my heart's content.  I've been stuck for hours playing around with the template files as well with no luck.


text:
Q: Java and LibGDX Framework count phone steps? I need to count user step in my game to move player character.
My player should move while someone is walking, but after I use System.out.print on numstep its still zero.
 How can i count my step in Java and the LibGDX Framework?
 public class PlayerBros extends Game {

        public  int step=0;
    }
    public class AndroidLauncher extends AndroidApplication implements SensorEventListener,StepListener {

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
            accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            simpleStepDetector = new StepDetector();
            simpleStepDetector.registerListener(this);

            sensorManager.registerListener(AndroidLauncher.this, accel, SensorManager.SENSOR_DELAY_FASTEST);
            config = new AndroidApplicationConfiguration();
            playerBros=new PlayerBros();
            numSteps = playerBros.step;
            initialize(playerBros, config);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                simpleStepDetector.updateAccel(
                        event.timestamp, event.values[0], event.values[1], event.values[2]);
                System.out.print("AndroidLauncher: "+numSteps);
            }
        }

        @Override
        public void step(long timeNs) {
            numSteps++;

        }

    }
    public class PlayScreen implements Screen {
    private PlayerBros game;

     public void handleInput(float dt){
     player.b2body.applyLinearImpulse(new Vector2(game.step,y), player.b2body.getWorldCenter(), true);
            hud.marioLabel.setText(" "+game.step);
            System.out.print("PlayScreen: "+game.step);

     }
        public void update(float dt){
          handleInput(dt);
    }

    }


text:
Q: How to install apk Samsung Galaxy Gear S through Android Studio? I am trying to run may sample application of wear in Samsung Galaxy Gear S. But I am getting device not connected. Also, I have enabled usb debugging. So anyone know how to run sample application in Samsung Galaxy Gear S through Android studio?

A: *

*If you're on Windows, make sure you've installed the ADB drivers through Device Manager.

*If you're on Linux, make sure you've configured your udev rules by following the setup guide on the Android Developer site
http://developer.android.com/tools/device.html#setting-up
Generally, this means creating a file at /etc/udev/rules.d/51-android.rules with a line like the following:

SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"

You can get the vendor id by running lsusb. Also, make sure you're in the plugdev group.

*If neither of those apply (and since you said you've already enabled USB debugging on the device), check to make sure that your USB cable and the charging cradle are mechanically sound.

*Failing all that, open up the Android Wear app on your phone and enable Bluetooth Debugging. Here are the steps to enable it:

Enable USB debugging on the handheld:

*

*Open the Settings app and scroll to the bottom.

*If it doesn't have a Developer Options setting, tap About Phone (or About Tablet), scroll to the bottom, and tap the build number 7 times.

*Go back and tap Developer Options.

*Enable USB debugging.

You'll then be able to use ADB-over-IP to connect to the Android Wear device, using your phone as a proxy. Make sure you have your phone connected via USB and that you have USB debugging enabled, of source. Instructions:

Set Up a Debugging Session

*

*On the handheld, open the Android Wear companion app.

*Tap the menu on the top right and select Settings.

*Enable Debugging over Bluetooth. You should see a tiny status summary appear under the option:
Host: disconnected
Target: connected

Connect the handheld to your machine over USB and run:
adb forward tcp:4444 localabstract:/adb-hub
adb connect localhost:4444

Note: You can use any available port that you have access to.
  In the Android Wear companion app, you should see the status change to:
Host: connected
Target: connected

Debug Your App
  Your wearable should show up as localhost:4444 when running adb devices. To run any adb command, use this format:
  adb -s localhost:4444
  If there are no other devices connected over TCP/IP (namely emulators), you can shorten the command to:
adb -e
  For example:
adb -e logcat
  adb -e shell
  adb -e bugreport

Source: Android Developers - Debugging over Bluetooth


text:
Q: Is there a way to freeze the mob inside a spawner? The question is pretty straight forward. Is there a way to freeze the mob inside the spawner.
I think before 1.13 you could do RequiredPlayerRange:0s. Well, that's not working anymore (1.15) Is this a bug that has been patched?
Thanks in advance.

A: I figured it out.
/data merge block (coords) {RequiredPlayerRange:0s}

This does not work with /setblock directly (MC-80690, so either /data merge command still needs to be run after a /setblock command or MaxNearbyEntities needs to be given as well, like this:
/setblock (coords) spawner{RequiredPlayerRange:0s,MaxNearbyEntities:0}


text:
Q: Error when checking target: expected dense_1 to have 2 dimensions, but got array with shape (20, 84, 1) This is my first attempt to LSTM layer and cant make this work. I have checked github bug tracker and SO topics but none of the available solutions solved my issue.
Whenever I change dense layer dimension or data shape I receive similar error.
Traceback (most recent call last):
  File "F:/Programowanie/GitHub Repositories/MYOPM/ui_main.py", line 640, in train_ml_algorithm
    self.ml.keras_LSTM_train()
  File "F:\Programowanie\GitHub Repositories\MYOPM\machine_learning.py", line 648, in keras_LSTM_train
    verbose=2)
  File "F:\Programowanie\GitHub Repositories\MYOPM\venv\lib\site-packages\keras\engine\training.py", line 1154, in fit
    batch_size=batch_size)
  File "F:\Programowanie\GitHub Repositories\MYOPM\venv\lib\site-packages\keras\engine\training.py", line 621, in _standardize_user_data
    exception_prefix='target')
  File "F:\Programowanie\GitHub Repositories\MYOPM\venv\lib\site-packages\keras\engine\training_utils.py", line 135, in standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking target: expected dense_1 to have 2 dimensions, but got array with shape (20, 84, 1)

I got 3d-arrays which contain only binary data:
train - shape (20, 84, 147)
[[[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 ...

 [[1 0 0 ... 0 0 0]
  [1 0 0 ... 0 0 0]
  [1 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 1 0 0]
  [0 0 0 ... 1 0 0]
  [0 0 0 ... 1 0 0]]

label - shape (20, 84, 1)
[[[0]
  [0]
  [0]
  ...
  [1]
  [1]
  [1]]

...

[[1]
  [1]
  [1]
  ...
  [1]
  [1]
  [1]]

Code:
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers.core import Dense, Dropout, Activation

model = Sequential()
model.add(LSTM(32, input_shape=(84, 147), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(32, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(1))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(train,
          label,
          epochs=100,
          batch_size=64,
          verbose=2)


text:
Q: Website painfully slow after migration to VPS2 We've recently moved from Fastcomet's Speedup plan (shared) to a more powerful one, VPS2 (also Fastcomet) because our disk space was running low.
Prior to the migration, our website www.famagusta.news was blazing fast. The moment they moved us to a bigger plan, everything went downhill.
After the migration was completed, we've noticed the slow speed right away. We didn't install new plugins or updates, nothing that could have caused the slow speed. The only change we did, was to point the cloudflare DNS to the new IP.
We advised Fastcomet's support, which up to this moment are doing their best to pinpoint the problem, but unfortunately nothing yet.
These are the issues:
1- Logged in users are randomly disconnected in users from wp-admin
2- Random slow first response when loading the page. Sometimes more than 20 seconds (tested with different ISPs)
3- Famagusta.news: Can't get gtmetrix speed test since the migration. I get a "Analysis Error - The page took too long to load" It works on all other websites on server, just not this one.
4- Since switching to the VPS, Facebook fails to pull the picture from the article. Facebook debugger says "Curl error: 28 (OPERATION_TIMEOUTED)".
At this point i'm completely lost. Any ideas?

A: Fastcomet support to the rescue!
After submitting a ticket with them, they solved everything and now my website is blazing fast once again.


text:
Q: Ultrasphinx and Rails: Completely wrong results - Why? I'm using Ultrasphinx for searching on a Rails App. Everything seems to be working, the only thing is that the search results are not matching the search query in any way. I really don't understand this. I rebuilt my indexes and config files several times and nothing seems to work. When I perform a search for "test" I get results back without the word "test" in any column.
This only happens on my production server. In the development environment everything works fine.
I don't really know which information to provide you with, I just paste my setup in the models and controllers
# models/video.rb

is_indexed :fields => ['title', 'description', 'id'],
    :concatenate => [{:class_name => 'Tag',
        :association_sql => "LEFT OUTER JOIN tags_videos ON (videos.id = tags_videos.video_id) LEFT OUTER JOIN tags ON (tags_videos.tag_id = tags.id)",
        :field => 'name', :as => 'tagstring'}],
    :order => "videos.created_at DESC",
    :eagerly_load => [:tags],
    :delta => true

# models/tag.rb

is_indexed :fields => ['name'],
    :delta => true

# controllers/searches_controller

class SearchesController < ApplicationController

  def search
    @search_query = (params[:query]) ? params[:query] : nil
    unless @search_query.nil?

      # set the search options
      search_options = {:query => @search_query,
        :page => (params[:page] || 1),
        :weights => {'title' => 2.0, 'description' => 1.0, 'tagstring' => 1.0},
        :per_page => 40,
        :class_names => ["Video"],
        :sort_mode => 'relevance'}
      @search = Ultrasphinx::Search.new(search_options)
      Ultrasphinx::Search.client_options['ignore_missing_records'] = true
      @search.run
      @videos = @search.results
    end
  end

end

I also get this error when running rake ultrasphinx:configure
Rebuilding configurations for production environment
Available models are Tagtranslation missing: en_US, support, array, two_words_connectorVideo
Generating SQL

but I don't know, what that has to do with it.
Thanks for your help!

A: I could fix the problem by installing Sphinx 0.9.9, using the option
--prefix=/usr/local/sphinx

-> http://www.sphinxsearch.com/docs/current.html#installing
After that I removed all old indexes, recreated the configuration file, recreated the index and restartet the ultrasphinx daemon.
Thanks anyway.


text:
Q: Foco sempre no JFrame Eu preciso que quando eu clicar em algum botão da minha aplicação o foco retorne para o JFrame. Existe algum método para isso?
Eu poderia chamar o método MeuFrame.requestFocus() em cada ActionPerformed, mas isso demoraria muito.

A: Existe sim, tente:
Você diz pro seu jButton transferir o foco e pede pro seu jFrame solicitar esse foco.
 jButton.transferFocus();
 jFrame.requestFocus();

Você ainda pode obter o foco forçando através do:
jFrame.grabFocus();

Esse método obtém o foco independente de quem o tiver (força a transferência do foco pra si), inclusive trás o foco para a janela caso ela não esteja ativa.
Eu lhe recomendaria utilizar da primeira forma, porque o efeito do segundo pode ser indesejado ao usuário.


text:
Q: Loss of display and Vino in previously working system I have an Ubuntu 20.04 system which crashed due to a hardware failure in the UPS.
Normally I access it remotely using SSH and VNC but I had to connect a monitor to confirm the BIOS settings and I noticed that the display only worked up until the Ubuntu splash screen. After that, the monitor was still receiving a signal but was black with a cursor occasionally appearing top left. I was still able to see the screen using VNC. I tried another reboot but that killed Vino and I just got an error trying to restart it. I can still SSH ok but the vino server won't start.
There are two GPUs in the PC: the internal Intel GPU and an NVidia GT610. I've tried swapping from one to the other in the BIOS but they both show the same symptoms.
I tried:
sudo /usr/lib/vino/vino-server --display=:0.0

No protocol specified
Unable to init server: Could not connect: Connection refused
Cannot open display: :0.0

I tried upgrading to Ubuntu 22.04 but it failed while trying to update the NVidia driver (which I reported) and so I'm still on 20.04. (Note: the upgrade failed here, i.e. it aborted.)
So: how do I get both the physical display (with either GPU) and vino to work? And what could cause the display to suddenly fail in this way?
I have had this happen before, about 2 years ago and I had to do a fresh install to fix it. I'd prefer not to have to do that again.

A: Fresh install of 22.02. Still having intermittent display issues. After a reboot, the local monitor works and VNC works. But if I disconnect the monitor (which is what I want to do as the PC is going to be run headless most of the time), VNC stops working and there's no display on the monitor if I reconnect it.
Update: I've been told swapping between running with a physical monitor and running headless can cause problems similar to the ones I experienced. The solution is to use a dummy HDMI plug.