text:
Q: VLCJ in Swing - Exception in thread "AWT-EventQueue-0" java.lang.AbstractMethodError I'm trying to write a basic VLC player for use in a Java Swing application. I have mainly been following the tutorial on the vlcj website: http://capricasoftware.co.uk/#/projects/vlcj/tutorial/my-first-media-player
Here is my code so far:
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class VideoPlayer {

private final JFrame frame;

private final EmbeddedMediaPlayerComponent mediaPlayerComponent;

public static void main(String[] args) {
new NativeDiscovery().discover();
    SwingUtilities.invokeLater(new Runnable(){
    @Override
    public void run(){
        new VideoPlayer();
    }

    });
}

public VideoPlayer(){
frame=new JFrame("My First Media Player");
frame.setBounds(100,100,600,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
frame.setContentPane(mediaPlayerComponent);
frame.setVisible(true);
}

}

I have managed to get the vlc library to seemingly load, but once I start trying to embed a media player into the JFrame, I get the following error in the printout:
run:
       _       _
 __   _| | ___ (_)
 \ \ / / |/ __|| |
  \ V /| | (__ | |
   \_/ |_|\___|/ | 2.1.0
             |__/  www.capricasoftware.co.uk

VLCJ is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

VLCJ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with VLCJ.  If not, see <http://www.gnu.org/licenses/>.

Copyright 2009, 2010, 2011, 2012 Caprica Software Limited.

Exception in thread "AWT-EventQueue-0" java.lang.AbstractMethodError: com.sun.jna.Structure.getFieldOrder()Ljava/util/List;
at com.sun.jna.Structure.fieldOrder(Structure.java:831)
at com.sun.jna.Structure.getFields(Structure.java:857)
at com.sun.jna.Structure.deriveLayout(Structure.java:983)
at com.sun.jna.Structure.calculateSize(Structure.java:908)
at com.sun.jna.Structure.calculateSize(Structure.java:896)
at com.sun.jna.Structure.allocateMemory(Structure.java:357)
at com.sun.jna.Structure.<init>(Structure.java:191)
at com.sun.jna.Structure.<init>(Structure.java:180)
at com.sun.jna.Structure.<init>(Structure.java:167)
at com.sun.jna.Structure.<init>(Structure.java:159)
at uk.co.caprica.vlcj.binding.internal.media_meta_changed.<init>(media_meta_changed.java:27)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at com.sun.jna.Structure.newInstance(Structure.java:1491)
at com.sun.jna.Native.getNativeSize(Native.java:984)
at com.sun.jna.Structure.getNativeSize(Structure.java:1769)
at com.sun.jna.Structure.getNativeSize(Structure.java:1762)
at com.sun.jna.Structure.validateField(Structure.java:958)
at com.sun.jna.Structure.validateFields(Structure.java:972)
at com.sun.jna.Structure.<init>(Structure.java:186)
at com.sun.jna.Structure.<init>(Structure.java:180)
at com.sun.jna.Structure.<init>(Structure.java:167)
at com.sun.jna.Structure.<init>(Structure.java:159)
at com.sun.jna.Union.<init>(Union.java:37)
at uk.co.caprica.vlcj.binding.internal.libvlc_event_u.<init>(libvlc_event_u.java:24)
at uk.co.caprica.vlcj.binding.internal.libvlc_event_u$ByValue.<init>(libvlc_event_u.java:26)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at com.sun.jna.Structure.newInstance(Structure.java:1491)
at com.sun.jna.Native.getNativeSize(Native.java:984)
at com.sun.jna.Structure.getNativeSize(Structure.java:1769)
at com.sun.jna.Structure.getNativeSize(Structure.java:1762)
at com.sun.jna.Structure.validateField(Structure.java:958)
at com.sun.jna.Structure.validateFields(Structure.java:972)
at com.sun.jna.Structure.<init>(Structure.java:186)
at com.sun.jna.Structure.<init>(Structure.java:180)
at com.sun.jna.Structure.<init>(Structure.java:167)
at com.sun.jna.Structure.<init>(Structure.java:159)
at uk.co.caprica.vlcj.binding.internal.libvlc_event_t.<init>(libvlc_event_t.java:28)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at com.sun.jna.Structure.newInstance(Structure.java:1491)
at com.sun.jna.CallbackReference.getNativeType(CallbackReference.java:234)
at com.sun.jna.CallbackReference.<init>(CallbackReference.java:209)
at com.sun.jna.CallbackReference.getFunctionPointer(CallbackReference.java:386)
at com.sun.jna.CallbackReference.getFunctionPointer(CallbackReference.java:368)
at com.sun.jna.Function.convertArgument(Function.java:496)
at com.sun.jna.Function.invoke(Function.java:258)
at com.sun.jna.Library$Handler.invoke(Library.java:218)
at com.sun.proxy.$Proxy1.libvlc_event_attach(Unknown Source)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer.registerEventListener(DefaultMediaPlayer.java:1558)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer.createInstance(DefaultMediaPlayer.java:1508)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer.<init>(DefaultMediaPlayer.java:168)
at uk.co.caprica.vlcj.player.embedded.DefaultEmbeddedMediaPlayer.<init>(DefaultEmbeddedMediaPlayer.java:133)
at uk.co.caprica.vlcj.player.MediaPlayerFactory.newEmbeddedMediaPlayer(MediaPlayerFactory.java:414)
at uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent.<init>(EmbeddedMediaPlayerComponent.java:161)
at VideoPlayer.<init>(VideoPlayer.java:27)
at VideoPlayer$1.run(VideoPlayer.java:17)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 2 seconds)`

I am using Windows 10, and have been using the 64 bit version of Netbeans and VLC. I am using version 3.5 JNA and JNA platform, and VLCJ 2.1.0.
From what I have seen on stack overflow and other sites, these sorts of errors tend to come about when there is a problem with compatibility. I am not sure what I am doing wrong, as far as I am aware I am using all the correct versions of each element to this build.
I am fairly new to coding so may have missed something basic, but many thanks in advance for any advice you guys can give!
EDIT:
No idea why, but I was using a pretty old version of VLCJ which was incompatible with my other libraries.
I've now updated my libraries to use VLCJ 3.10 and JNA 4.1.0. But now the code is getting stuck elsewhere, before VLC even initialises:
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at uk.co.caprica.vlcj.Info.<init>(Info.java:37)
at uk.co.caprica.vlcj.Info.<init>(Info.java:32)
at uk.co.caprica.vlcj.Info$InfoHolder.<clinit>(Info.java:47)
at uk.co.caprica.vlcj.Info.getInstance(Info.java:56)
at uk.co.caprica.vlcj.discovery.NativeDiscovery.<clinit>(NativeDiscovery.java:58)
at VideoPlayer.main(VideoPlayer.java:15)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 6 more
C:\Users\Alex\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53:     Java returned: 1
BUILD FAILED (total time: 0 seconds)

Looks like vlcj is struggling to work, but all I did was swap out the .jar files in the library folder. Any ideas?


text:
Q: How cpu writes data to dynamic RAM I would like to know what kind of electrical signals does a cpu send to a dynamic RAM when it wants to write one bit (a 1 or 0).
Is it simply that cpu sends just a single electric pulse, and if that electric pulse's voltage is higher than a certain level, it charges the capacitor to a voltage level that is "1" and if it is at a lower voltage band, it charges capacitor to level that it is "0"?

A: The memory controller sends the signals out 32, 64, or 128 bits at a time, and the memory module's controller translates them into the appropriate levels for storage.

A: At the lowest level, yes; a line goes to a digital 1 or 0 voltage state and charges or discharges a capacitor.  Additional logic sits between the dram chips and the memory controller on the motherboard or cpu that handles various functions including routing the data lines to the cell(s) being addressed ( typically 64 or 128 bits are accessed at a time ).

A: There are two mechanisms:
1) The right bit has to be addressed. The bits can be arranged in a 2D scatter, and in a 1Mbit chip that could consist of 1024 horizontal and 1024 vertical electrical lines. In order to write a bit, it would set one of each to high voltage and one the rest to low voltage. The bit, where both the horizontal line and vertical line is set to high voltage, is the one that is written to.
2) The bit information has to flow into the bit cell. In dynamic RAM, this is a simple capacitor.
The logic to see, if the horizontal and vertical lines are both high-voltage, and the capacitor, can be combined into one very simple layered circuit on a chip, which basically occupies almost nothing and is regarded one of the smallest items that you can put on a chip. However, the capacitor-part is lossy, i.e. it loses the electrons over time. Therefore, every single bit in the RAM chip needs to be read and re-written over and over again. This is why it is called dynamic, and this is why the computer loses it's memory when turned off.
Reading uses the same logic to pick a bit cell, and basically empties the capacitor, if there are any electrons. Reading a cell that contains electrons therefore requires that the cell is written immediately afterwards, again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Replace a value if null or undefined in JavaScript I have a requirement to apply the ?? C# operator to JavaScript and I don't know how.
Consider this in C#:
int i?=null;
int j=i ?? 10;//j is now 10

Now I have this set up in JavaScript:
var options={
       filters:{
          firstName:'abc'
       }
    };
var filter=options.filters[0]||'';//should get 'abc' here, it doesn't happen
var filter2=options.filters[1]||'';//should get empty string here, because there is only one filter

How do I do it correctly?
Thanks.
EDIT: I spotted half of the problem: I can't use the 'indexer' notation to objects (my_object[0]). Is there a way to bypass it? (I don't know the names of the filters properties beforehand and don't want to iterate over them).

A: TLDR:
int j=i ?? 10; is perfectly fine to use in javascript also. Just replace int with let.
?? vs ||
?? should be preferred to || because it checks only for nulls and undefined.
All The expressions below are true:
(null || 'x') === 'x' ;
(undefined || 'x') === 'x' ;
//Most of the times you don't want the result below
('' || 'x') === 'x'  ;
(0 || 'x') === 'x' ;
(false || 'x') === 'x' ;
//-----

//Using ?? is preferred
(null ?? 'x') === 'x' ;
(undefined ?? 'x') === 'x' ;
//?? works only for null and undefined, which is in general safer
('' ?? 'x') === '' ;
(0 ?? 'x') === 0 ;
(false ?? 'x') === false ;

Asterisk: Check browser compatibility and if you really need to support these other browsers use babel.

A:
I spotted half of the problem: I can't use the 'indexer' notation to objects (my_object[0]). Is there a way to bypass it?

No; an object literal, as the name implies, is an object, and not an array, so you cannot simply retrieve a property based on an index, since there is no specific order of their properties. The only way to retrieve their values is by using the specific name:
var someVar = options.filters.firstName; //Returns 'abc'

Or by iterating over them using the for ... in loop:
for(var p in options.filters) {
    var someVar = options.filters[p]; //Returns the property being iterated
}

A: ES2020 Answer
The new Nullish Coalescing Operator, is finally available on JavaScript. However, do take note of the browser support. You may need to use a JavaScript compiler like Babel to convert it into something more backward compatible.
According to the documentation,

The nullish coalescing operator (??) is a logical operator that
returns its right-hand side operand when its left-hand side operand is
null or undefined, and otherwise returns its left-hand side operand.

const options={
  filters:{
    firstName:'abc'
  }
};
const filter = options.filters[0] ?? '';
const filter2 = options.filters[1] ?? '';

This will ensure that both of your variables will have a fallback value of '' if filters[0] or filters[1] are null, or undefined.
Do take note that the nullish coalescing operator does not return the default value for other types of falsy value such as 0 and ''. If you wish to account for all falsy values, you should be using the OR operator ||.

A: Here's the JavaScript equivalent:
var i = null;
var j = i || 10; //j is now 10

Note that the logical operator || does not return a boolean value but the first value that can be converted to true.
Additionally use an array of objects instead of one single object:
var options = {
    filters: [
        {
            name: 'firstName',
            value: 'abc'
        }
    ]
};
var filter  = options.filters[0] || '';  // is {name:'firstName', value:'abc'}
var filter2 = options.filters[1] || '';  // is ''

That can be accessed by index.

A: Logical nullish assignment, 2020+ solution
A new operator has been added, ??=. This is equivalent to value = value ?? defaultValue.
||= and &&= are similar, links below.
This checks if left side is undefined or null, short-circuiting if already defined. If not, the left side is assigned the right-side value.
Basic Examples
let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

// Equivalent to
a = a ?? true

Object/Array Examples
let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

Functional Example
function config(options) {
    options.duration ??= 100
    options.speed ??= 25
    return options
}

config({ duration: 555 })   // { duration: 555, speed: 25 }
config({})                  // { duration: 100, speed: 25 }
config({ duration: null })  // { duration: 100, speed: 25 }

??= Browser Support Sept 2021 - 90%
??= Mozilla Documentation
||= Mozilla Documentation
&&= Mozilla Documentation

A: Destructuring solution
Question content may have changed, so I'll try to answer thoroughly.
Destructuring allows you to pull values out of anything with properties. You can also define default values when null/undefined and name aliases.
const options = {
    filters : {
        firstName : "abc"
    }
}

const {filters: {firstName = "John", lastName = "Smith"}} = options

// firstName = "abc"
// lastName = "Smith"

NOTE: Capitalization matters

If working with an array, here is how you do it.
In this case, name is extracted from each object in the array, and given its own alias. Since the object might not exist = {} was also added.
const options = {
    filters: [{
        name: "abc",
        value: "lots"
    }]
}

const {filters:[{name : filter1 = "John"} = {}, {name : filter2 = "Smith"} = {}]} = options

// filter1 = "abc"
// filter2 = "Smith"

More Detailed Tutorial
Browser Support 92% July 2020


text:
Q: C# web API - square-bracket notation in query string I'm building a set of web APIs that return data in JSON format. An external app performs an http (GET) request like this:
http://localhost:58807/api/items/search?qualifier=year&sort[0][field]=Year&sort[0][dir]=desc&sort[1][field]=Title&sort[1][dir]=asc
and this is the method which manage the http request:
[HttpGet]
[Route("search")]
public IHttpActionResult GetItems(string qualifier, IEnumerable<Dictionary<string, string>> sort)
{
     Does something;
}

This is the problem: while the qualifier parameter is correctly valued, the sort (square-bracket notation in query string) parameter is instead null.
What's wrong?
Thanks in advance.
Filippo

A: In ASP.NET Web API 2 the binding does not work (using ApiController from namespace System.Web.Http).
In ASP.NET Core 3.1 Web API the binding does work (using ControllerBase from namespace Microsoft.AspNetCore.Mvc).
The difference is in the version.
One way of solution for Web API 2 would be to parse the query:
var sortParameters = Request.Query.Where(x => x.Key.StartsWith("sort"));
var sortFilters = new List<SortFilter>();
foreach (var sortParamter in sortParameters)
{
    sortFilters.Add(ParseSortParameter(sortParameter)); // TODO: implementation of ParseSortParameter
}

public class SortFilter
{
    public string FieldName { get; set; }
    public string Direction { get; set; }
}

Request is of type HttpRequest.


text:
Q: QQuickWindow context property? I am creating a new window through the following code:
QMainController* myController = new QMainController(0,m_autenticado);
QQmlApplicationEngine* engine = new QQmlApplicationEngine(this);

engine->rootContext()->setContextProperty("MyController", myController);
engine->load(QUrl(QStringLiteral("qrc:///newPage.qml")));

QQuickWindow* window = qobject_cast<QQuickWindow*>(engine->rootObjects().at(0));
window->showFullScreen();

This code sets a MyController property to the rootContext, which means that all the pages at the root context will have access to this property. And so, this won't allow me to open 2 different windows from the same QML file, each with its own instance of MainController.
QUESTION: How can I bind this MyController property to the QQuickWindow context instead of the engine's rootContext?
I've tried to use a QQuickView and doing like this:
QMainController* myController = new QMainController(0,m_autenticado);

QQuickView* view = new QQuickView();
view->rootContext()->setContextProperty("MyController", myController );
view->setSource(QUrl(QStringLiteral("qrc:///main.qml")));
view->showFullScreen();

But I was complained with the following message:

"QQuickView only supports loading of root objects that derive from QQuickItem.
If your example is using QML 2, (such as qmlscene) and the .qml file you
loaded has 'import QtQuick 1.0' or 'import Qt 4.7', this error will occur.
To load files with 'import QtQuick 1.0' or 'import Qt 4.7', use the
QDeclarativeView class in the Qt Quick 1 module."

A: QQuickWindow does not own any context property of its own so there is no way to set context property with it.
Just like the message explains, QQuickView expects a QML root object that is inherited from QQuickItem, which means the root can be a Rectangle, Item etc, but not ApplicationWindow or Window, since they are not inherited from QQuickItem. If you can change root object to something like Rectangle, you can create different instances of QQuickView to reach your goal, since each QQuickView creates its own QQmlEngine if you don't provide an existing QQmlEngine to it.
QQmlApplicationEngine actually inherits from QQmlEngine, so each instance has its own root context. For example calling the following createMain() twice will create two windows with separate engines, separate controller and separate rootContext:
void foo::createMain() {
    //TODO: Set a proper parent to myController
    QMainController* myController = new QMainController(0,m_autenticado);
    QQmlApplicationEngine* engine = new QQmlApplicationEngine(this);

    engine->rootContext()->setContextProperty("MyController", myController);
    engine->load(QUrl(QStringLiteral("qrc:///newPage.qml")));

    QQuickWindow* window = qobject_cast<QQuickWindow*>(engine->rootObjects().at(0));
    window->showFullScreen();
}

If you don't feel right about creating multiple copies of QQmlAppicationEngine, you can share one instance of QQmlApplicationEngine instead, and create a child context for each window instance:
// foo.h
class foo {
private:
  QQmlApplicationEngine m_engine;  // can change to QQmlEngine if you prefer
}

// foo.cpp
void foo::createMain()
{
  //TODO: Set a proper parent to myController
  QMainController* myController = new QMainController(0,m_autenticado);

  // Create a new context as a child of m_engine.rootContext()
  QQmlContext *childContext = new QQmlContext(&m_engine, &m_engine);
  childContext->setContextProperty("MyController", myController);

  QQmlComponent *component = new QQmlComponent(&m_engine, &m_engine);
  component->loadUrl(QUrl("qrc:///qml/newPage.qml"));

  // Create component in child context
  QObject *o = component->create(childContext);
  QQuickWindow* window = qobject_cast<QQuickWindow*>(o);
  window->show();
}

And of course you can change QQmlApplication to QQmlEngine if there's no use of QQmlApplicationEngine's features.


text:
Q: Android 7.0 - TabHost - have to click twice I work on old Android project:
minSdkVersion 9,
targetSdkVersion 19
It uses TabHost (API 1) as a container for a tabbed window view. Since our clients got devices with Android 7.0 they have to click twice on every tab to fire onTabChanged(). I've searched the internet far and wide, but found nothing about this problem.
Is there any quicker solution then updating whole project to use TabLayout and ViewPager? It's quite big so it would be costly.
TabHost in xml:
<TabHost
    android:id="@android:id/tabhost"
    android:layout_width="0dip"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:layout_marginLeft="1dip" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:orientation="horizontal" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="@color/grey_comarch" >
        </LinearLayout>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0" />

        <FrameLayout
            android:id="@+id/realtabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>
</TabHost>

It has set Listener like this:
mListTabHost.setOnTabChangedListener(this);

which fires onTabChanged:
public void onTabChanged(String tabId)

but always after second click on the same tab.


text:
Q: magento integration with erp and crm How to integrate Magento with ERP and CRM and which are erp's and crm's which is best integrated with Magento?
And how easy it is to do this integration?

A: See magento integration with erp and crm for how to do it. The easiest ERP / CRM systems will be ones that you can set up to pull information from Magento periodically and put it back in over webservices. Open source solutions (where you can monkey with the code) will work out better than closed source solutions, especially ones where you don't have direct database access.
As for ease, it depends on how much data will be transferred. Moving orders back to ERP, or moving customers to CRM is not difficult, but keeping everything highly synchronized is another story.
If you have other questions, please be more specific and I'll be happy to help.
Thanks,
Joe

A: InSync presents 'SBOeConnect', e-Commerce Connector for SAP Business One. SBOeConnect gives the flexibility for seamless integration between Magento Commerce with leading ERP Business Solution SAP Business One. SBOeConnect provides a real time synchronization between these two platforms, eliminating manual data entry and reducing data redundancy.
For more please visit at http://sboeconnect.com
Regards,
Soumen.
Team sboeconnect.com

A: I think you may try to use Web Service of the Magento. Write a "bridge" program to transfer/update data from Magento and the ERP system. There should be API for most of the ERP system.
Here is the link for Magento web service. Basically it is very convenient.
http://www.magentocommerce.com/wiki/5_-_modules_and_development/0_-_module_development_in_magento/introduction
And most of the time, you're supposed to handle order related information daily, you can setup cron job to run the "bridge" program then.

A: Try openbravo its an erp. They have a built-in connector for it to Magento. You can synchronize customers, products and sales order from Magento into Openbravo ERP. It can be scheduled by time or by frequency to be executed. The documentation for it can be had from here.


text:
Q: Setting a custom itemRenderer in a Flex3 ComboBox on specific list items after combobox creation I'm trying to set a specific list item in a mx combobox to have a custom item renderer, the problem is that I cannot do this via mxml, it needs to be done via actionscript at a later stage, eg: combobox gets created, combobox  gets populated, user does other tasks, combobox needs to set one or more items in the combobox to have icons (via item renderer)..
I can do this via the onChange event, but it only applies the icon when the combobox is opened and there is a slight delay so you can see the icon being added.
Thanks in advance for any help
J

A: The normal answer for this is to not do this in the onChange, but to change something in the ComboBox's dataProvider and let the itemRenderer handle it instead.
i.e. in the itemRenderer
<mx:Image id="icon" source={data.icon} visible={data.icon} includeInLayout={data.icon} />

Setting the icon property in whichever item you want to show the icon for. If icon is null, nothing gets shown.


text:
Q: How to prove $\text{det}(I+xy^{\top}+wz^{\top})=(1+y^{\top}x)(1+z^{\top}w)-(x^{\top}z)(y^{\top}w)$? Suppose $x,y,z,w$ are vectors in $\mathbb{R}^n$ and $I$ is the identity matrix.
Show that $\text{det}(I+xy^{\top}+wz^{\top})=(1+y^{\top}x)(1+z^{\top}w)-(x^{\top}z)(y^{\top}w)$.

A: Consider the matrix
$$\tag1
\begin{bmatrix} 1+y^Tx & y^Tw \\ z^Tx & 1+z^Tw \end{bmatrix}
=I + \begin{bmatrix} y^T\\ z^T \end{bmatrix} \begin{bmatrix}  x & w\end{bmatrix}
$$
For any $A,B$, we have the equality $\det(I+AB)=\det(I+BA)$. So the determinant in $(1)$ is equal to the determinant of
$$
I + \begin{bmatrix}  x & w\end{bmatrix}\begin{bmatrix} y^T\\ z^T \end{bmatrix}
=I+xy^T+wz^T.
$$

Proof of the equality $\det(I+AB)=\det(I+BA)$.
The matrices $AB$ and $BA$ have the same eigenvalues (padding with zeroes when the sizes are not equal). So $I+AB$ and $I+BA$ have the same eigenvalues, and if the two lists have different length then the remaining eigenvalues are $1$. As the determinant is the product of the eigenvalues, we get $\det(I+AB)=\det(I+BA)$.


text:
Q: Is Scrapy compatible with Python 3 on Windows? Is 'scrapy' compatible with Python 3(or later) on Windows?
If not, then is the only option to use it with Python 2.7?
I need this for a project I need to do.
Thank you.

A: Yes, it is, you can install it via
pip install scrapy
(You may want to activate your virtual environment first)

A: Scrapy runs on Python 2.7 and Python 3.3 or above.

Scrapy is being ported to Python 3 using the single-codebase approach.
  The goal is to make Scrapy work in both Python 2.7 and 3.3+ using the
  six library to smooth differences between Python 2.x and 3.x.

Installing scrapy in Windows 64 bit.
You can check this site to use scrappy Python 3 in pycharm :
http://www.jianshu.com/p/54c906b18a42


text:
Q: What is conditional normal variance of $X$ given that dependent $Y$ is bigger than a real number $M$? There are two dependent normal variables with the same distribution and the correlation coefficient $\rho$: $X,Y \sim N(\mu, \sigma^2)$.
I would like to get $P(X>M|Y>M)$. For that I need to know the conditional expectation and variance. But I can not find any information about the conditional normal variance in the case when $Y$ is smaller/bigger than some real number.
There is not a comparison between two normal variables. And it's not the truncated normal distribution.
I found the conditional expectation of $X$ given that $Y$ is bigger than $M$ is
$E(X|Y>M)= \mu + \rho \sigma \frac{\phi(\frac{M-\mu}{\sigma})}{1-\Phi(\frac{M-\mu}{\sigma})}$.
But what is the conditional variance $var(X|Y>M)$? Is it $(1-\rho^2)\sigma^2 $, as it would be in the case of $var(X|Y=M)$, where variance does not depend on $M$?


text:
Q: After rotate image shows original image instead of rotate image I want to show rotate image after click on left and right button
But is shows original image and after clearing history and cache it will show rotate image
    var degrees = 0;
            $("#cboxRight").on('click', function () {
                var $cboxphoto = $('.cboxPhoto');
                degrees += 90;
                $cboxphoto.css('-ms-transform', 'rotate(' + degrees + 'deg)');
                $cboxphoto.css('-webkit-transform', 'rotate(' + degrees + 'deg)');
                $cboxphoto.css('transform', 'rotate(' + degrees + 'deg)');
                $cboxphoto.css('-o-transform', 'rotate(' + degrees + 'deg)');
                $cboxphoto.css('-moz-transform', 'rotate(' + degrees + 'deg)');
saveRotateImage(this.id, tr_job_room_id, new_path_colorbox);
            });

            $("#cboxLeft").on('click', function () {
                var $cboxphoto = $('.cboxPhoto');
                degrees -= 90;
                $cboxphoto.css('-ms-transform', 'rotate(' + degrees + 'deg)');
                $cboxphoto.css('-webkit-transform', 'rotate(' + degrees + 'deg)');
                $cboxphoto.css('transform', 'rotate(' + degrees + 'deg)');
                $cboxphoto.css('-o-transform', 'rotate(' + degrees + 'deg)');
                $cboxphoto.css('-moz-transform', 'rotate(' + degrees + 'deg)');
saveRotateImage(this.id, tr_job_room_id, new_path_colorbox);
            });
    function saveRotateImage(cboxid, ids, path) {
        $.ajax(
        {
            type: "POST",
            url: '@Url.Action("saveRotateImage")',
            dataType: "json",
            mtype: "post",
            data: { cbox_id: cboxid, ids: ids, path: path },
            cache: false,
            async: true,
            success: function (data) {
                //alert("Saved");
            }
        });
    }

how to show rotate image on click on button

A: May be something like this..
JS Fiddle link : http://jsfiddle.net/vreverpb/2/
$("input[name='toggle']").change(function(){

var degrees = this.value;

        var $cboxphoto = $('.cboxPhoto');
        $cboxphoto.css('-ms-transform', 'rotate(' + degrees + 'deg)');
        $cboxphoto.css('-webkit-transform', 'rotate(' + degrees + 'deg)');
        $cboxphoto.css('transform', 'rotate(' + degrees + 'deg)');
        $cboxphoto.css('-o-transform', 'rotate(' + degrees + 'deg)');
        $cboxphoto.css('-moz-transform', 'rotate(' + degrees + 'deg)');

    });


text:
Q: How to optimize SQL query without losing data? I am working with MySQL to query database tables.
I finally find that the following query returns what I want from my database. ( I am not SQL expert)
SELECT * FROM ( SELECT swtickets.ticketid, swtickets.ticketstatustitle, swtickets.departmenttitle, swtickets.subject, swtickets.dateline, swtickets.ownerstaffname, swtickets.lastreplier, swcustomfieldvalues.fieldvalue, swcustomfieldvalues.customfieldid FROM swtickets, swcustomfieldvalues WHERE swcustomfieldvalues.typeid=swtickets.ticketid AND swtickets.ticketid IN (SELECT typeid FROM `swcustomfieldvalues` WHERE `fieldvalue`=12345678)) as tbl
where tbl.customfieldid=123

However, the above query is taking a long time to show results in phpMyAdmin.
Showing rows 0 - 24 (32 total, Query took 7.1488 sec)

Can this query be optimized to be faster than 7 seconds?
Here is my SQLFiddle:
http://sqlfiddle.com/#!9/d3b5a2
More explanation:
Table: swcustomfieldvalues
customfieldvalueid
customfieldid
typeid <— This field is not unique in this table
fieldvalue
isserialized
isencrypted
dateline
uniquehash
lastupdated

For each ticket, I have 9 custom fields in swcustomfieldvalues
All 9 custom fields for each ticket have SAME typeid (= ticketid in swtickes table).
If customfieldid = 6, then fieldvalue holds user full name
If customfieldid = 7, then fieldvalue holds user mobile number
If I query this table for typeid=98765
I will get 9 rows all have SAME typeid and different values for fieldvalue and customfieldid etc…
I want from this result (the 9 rows) the fieldvalue value where customfieldid=6 but only if the fieldvalue=1234567 where customfieldid=7
I already have this value 1234567 in my query, so I do not care if it is listed in the result or not.
More explanation:

All current answers successfully fetch these set of rows for each ticket that has mobile number as provided in the query PLUS other ticket derails from 'swtickets' table.
What are we doing so far:
The search (query) is performed with condition on the when customfieldid=7 and fieldvalue = 0555.
Everything is fine. But I do not want field value to appear on result (I do not care about it) I want the name to appear on my result of rows.
I want the fieldvalue for the row that has customfieldid=6 only if:
the row with customfieldid=7 has fieldvalue=0555
Results of two queries (Mine and the on on answers'):

A: You can make it simple by using something like this,
SELECT
swtickets.ticketid,
swtickets.ticketstatustitle,
swtickets.departmenttitle,
swtickets.subject,
swtickets.dateline,
swtickets.ownerstaffname,
swtickets.lastreplier,
swcustomfieldvalues.fieldvalue,
swcustomfieldvalues.customfieldid
FROM swtickets
LEFT JOIN swcustomfieldvalues
ON
swcustomfieldvalues.typeid = swtickets.ticketid
AND
swcustomfieldvalues.fieldvalue = 12345678
AND
swcustomfieldvalues.customfieldid = 123

A: Try this
select swtickets.ticketid, swtickets.ticketstatustitle, swtickets.departmenttitle, swtickets.subject, swtickets.dateline, swtickets.ownerstaffname, swtickets.lastreplier, swcustomfieldvalues.fieldvalue, swcustomfieldvalues.customfieldid
      from swtickets
      join swcustomfieldvalues ON (swtickets.ticketid = swcustomfieldvalues.typeid)
      where swcustomfieldvalues.fieldvalue = 12345678 and swcustomfieldvalues.customfieldid=123


text:
Q: Show a mod menu on questions summaries A recent question revealed a need for a quick way to moderate many questions from their summaries.
What is a question summary?  Its the view of a question within a list, such as the front page or search results:

(Its referred to as a summary in the html, not sure if that is the common name)
Anyhow...
As it currently stands, a moderator cannot act within this view.  The mod must first open the question in order to access the mod menu, or get to the Close/Delete links.
When you're talking about a question here/there, its not too much of a problem.  When you're talking about fifteen thousand questions, son, we have issues.
I'd suggest adding an abbreviated list of links under the tags on the summary:

so that we can hit and run without opening 15k tabs.

A: Can't think of a good reason for this, honestly. The moderator flag queue is already set up to where you can close or delete a question based on the summary and flag, with the assumption being that someone looked at the whole thing and you need only do so again if something seems fishy about it.
A system where stuff gets closed or deleted without anyone looking at it is... Dangerous.

A: According to this question, the question do need review first. If the question+answers are good, leave open (+edit if necessary)... If not, close.
Questions can be about:

*

*Concept in specific books

*Concept about specific tools

*Recommendation of any good method, concept in book/about tool

*Comparison between tools

*Comparison between concepts in different books

So we need to read those questions. And required to take actions. Thats why I said 70% question will get closed an not 100%.
If without reading questions are getting closed then we will miss many more questions. And 95% times if question get closed as Not Constructive then people even don't think of reopening it.


text:
Q: JWT encryption taking audience as array but need to send normal string instead I'm using https://pub.dev/packages/jaguar_jwt/ to encrypt data but I have a situation, where I need to send the audience as String instead of List<String>. How can I do it, is there some workaround?
var claimSet = JwtClaim(
      issuer: issuer,
      subject: '',
      audience: [issuer],
      otherClaims: {'DATA': encodedPayload},
      maxAge: Duration(days: kReleaseMode ? 1 : 7),
 );

claimSet.audience = issuer; // Giving error - 'audience' can't be used as a setter because it's final.

I tried to update the audience key but IDE itself giving an error. It's not that I want to update the issuer, I just want the audience to be a String.

A: You can't do that since the audience is final.

A variable with the final keyword will be initialized at runtime and
can only be assigned for a single time

You have to create a new JwtClaim object whenever you want to update.
Updated: the audience cannot be a string since it is defined as a List in the source. Please refer to the source file link as below:
https://github.com/Jaguar-dart/session/blob/master/jaguar_jwt/lib/src/claim.dart


text:
Q: "I've gone through" vs. "I understand" "for IELTS speaking part two" or "for the IELTS speaking part two" says

I've gone through Cambridge Dictionary grammar tutorial on "A/an and the". I guess I understand the rules in it.

Does "I've gone through" have the implication that the speaker understands those rules?
In other words, is it a little bit wording to say something like "I understand XXX", after "I've gone through XXX", especially in writing?

A: "I've gone through it" means that he has read it in its entirety (and if it had exercises to work through, he's done them all).
He guesses he understands the rules because of reading it, but is not certain because he may have missed or misunderstood parts.


text:
Q: setting up storage space on HDD New to Ubuntu. Have a Win 7 system. Set up dual boot with newest version of Ubuntu. Both OSes are on partitioned
500 MB SSD.
Data kept on 1TB HDD.
Would like to know how to set up dedicated partition on half
of HDD, please

A: Before reading further I'd recommend you back up any data you have on the 1TB drive, provided I understood you clearly and you need want to divide it in half for Windows data and Linux data. Resizing a partition on a drive can cause data loss. That said...
It seems you want to resize your data partition and make half of it a Linux friendly file system, e.g. ext4.
Provided you have Ubuntu Desktop install media you can run the LiveCD and use gparted. picture below.

It is very easy to use and you should have no problems partitioning.
If you prefer to use a Windows partitioning tool the process is the same.

*

*Back up any data you absolutely can't be without on the 1TB drive

*choose actions to resize the current partition on the 1TB drive to 500GB

*Make a partition with the remaining space of a file type of your choosing that is Linux friendly (Here's a brief good intro article on filetypes in case you are curious:
https://www.howtogeek.com/howto/33552/htg-explains-which-linux-file-system-should-you-choose/.)

*apply changes

Good luck!


text:
Q: Combinatorics/Probability - Multiple Groups Example Problem
Joe, an avid and properly licensed sportsman, is in his hunting blind when he locates 20 Canada geese, 25 Mallard ducks, 40 Bald Eagles, 10 Whopping Cranes, and 5 Flamingos.  Joe randomly selects six birds to target.  What is the probability that at least one of each species is targeted?

So we have 5 birds and we must choose 6:
20 g
25 d
40 e
10 c
5 f
So we have six slots and one slot will be a wild card.  So we must calculate the outcomes for the following:  {g,d,e,c,f,*}, where *=[g or d or e or c or f]
$Pr=\cfrac{\{g,d,e,c,f, *\}}{\binom{100}{6}}$
My approach to calculating {g,d,e,c,f,*} is to manually enumerate the 5 cases and sum them together:

*

*ggdecf = $\binom{20}{2}*25 * 40 * 10 * 5$

*gddecf = $20*\binom{25}{2} * 40 * 10 * 5$

*gdeecf = $20 * 25*\binom{40}{2} * 10 * 5$

*gdeccf ...

*gdecff ...
I verified that this gives me the correct answer of $0.0398472$.
I just wanted to know if there's a more efficient way of doing this then what I am doing.  Am I approaching the question properly?
I thought about composing a vector (g,d,e,c,f) where each coordinate is like an "urn" and we will be placing 6 balls (the bullets) inside them.  So we could have (2,1,1,1,1) which is 2 geese and the rest of the birds are one.  If we wanted to find all the combinations of 1 pair, we could use the multinomial theorem:
$\binom{5}{2,1,1,1,1}=60$.  But we still have to calculate the probability of each pair and multiply it by this right?  Can you do it this way?
I know usually when a question asks you at least you should subtract the cases so save you work.  Can you do that in this case?
Thank you.

A: See my answer here to a similar problem involving 3 choices. I am sure you can extend it.

A: Yours is I think the best way, since you retain full control over what's going on.
A variant (which I do not recommend) is that we first choose a bird of each kind, which can be done in $(20)(25)(40)(10)(5)$ ways.
Each such choice can be extended to a choice of $6$ birds in $100-5$ ways. But this overcounts, by a factor of $2$, because each "extra" bird could have been chosen in the first round or the second.  So our count is $\frac{[(20)(25)(40)(10)(5)](95)}{2}$.


text:
Q: BOM at PHP file won't get handled with zend.multibyte My favorite PHP editor Codelobster is always adding a UTF-8 BOM at my PHP files.
So this BOM is sent to the clients. While it works fine with most browsers, Google Chrome has a problem with it: According to the inspector, it adds  into the <body> of the HTML, resulting in an ugly padding above the follow-up <form> .

I want to solve this problem by stripping the UTF-8 from the HTTP-Output.
I have read that setting zend.multibyte = On in the PHP.ini will handle the UTF-8 BOM of the PHP files, and therefore avoid passing them to the client.
But it doesn't work. What should I do?
reproduction.php (in ASCII representation)
<?php

// Just a demonstration to show that the UTF-8 BOM was actually sent
flush();
header('abc:def'); // will fail, because of the previously sent BOM

// Now check that the change in the PHP file did work.
var_dump(ini_get('zend.multibyte')); // string(1) "1"

?>

Additional information about the environment:

*

*PHP 5.6.8

*SAPI: Apache 2.0 Handler

*Apache 2.4.10

*Windows server


text:
Q: displaying an attachment in a data view webpart Guys how can I display an image attached to a list item in a data view web part.  I cant find any examples of this on the net

A: This post here http://support.microsoft.com/kb/2590041 explains how to get over an issue when creating Custom display forms which need to show attachments.
You would notice the presence of a certain field
<SharePoint:FormField runat="server" id="AttachmentsField" ControlMode="Display" FieldName="Attachments" __designer:bind=""/>

Follow similar steps to include it in your data form.

A: Have you tried using XSL?
<xsl:element name="SharePoint:AttachmentsField">
  <xsl:attribute name="runat">server</xsl:attribute>
  <xsl:attribute name="FieldName">Attachments</xsl:attribute>
  <xsl:attribute name="ControlMode">Display</xsl:attribute>
  <xsl:attribute name="Visible">true</xsl:attribute>
  <xsl:attribute name="ItemId">
    <xsl:value-of select="@ID"/>
  </xsl:attribute>
</xsl:element>

A: Please refer :http://www.codeproject.com/Articles/31895/Displaying-Attachments-with-the-Data-View-Web-Part, it has same functionality implemented.


text:
Q: How to compare different causal inference methodologies for estimating Average Treatment Effect when true treatment effect is unknown? I'm comparing various methods for estimating average treatment effects (ATEs) for  cost savings in a case-control study on health insurance episode of care data for my employer.
My company currently uses coarsened exact matching (CEM), often with a follow-up regression on matched episodes, to estimate ATEs. I'd like to compare more recently developed techniques that are better suited for high dimensional data, such as Targeted Minimum Loss-Based Estimation (TMLE) and Bayesian Additive Regression Trees (BART).
Is there a way to compare techniques for estimating the Average Treatment Effect without knowing the true ATE in advance?
I'm considering two possibilities:

*

*Build a data generating process that closely resembles our own data. This could be accomplished by fitting a linear regression model Y ~ treatment + covariate_main_effects + covariate_interaction_effects to the data, where the covariates in would be manually selected. Then define the regression coefficient for the treatment covariate as the true ATE to be estimated, and generate data according to the model, say using the simstudy package. Causal inference methods are then tested on the simulated data. My colleagues are hesitant to use a data generating process, they would prefer to test on our observed claims data. But perhaps this method will allay their fears.

*Instead of using a data generating process, select a subset of variables from the analysis data so that there are no positivity violations (that is, every matching subgroup contains a suitable number of episodes, say at least 5, in each of the treatment and control categories). Then find the true ATE_subset by comparing average episode costs for treatments and controls within each subgroup. The disadvantage of this approach is I'm testing on a small subset of the population, but it would establish a baseline confidence in new causal inference techniques' ability to find the true ATE.

A: Your first intuition is correct. This is called a plasmode simulation and is a great and frequently used way to compare the performance of estimators for data with covariate and treatment distributions like the one you have. See Franklin et al. (2014) who use this method exactly as you intend. The key, though, is in choosing a model with which to generate the outcome. ideally, it would reflect a data-generating process similar to the one that exists in the real data, but if you knew that, you wouldn't need to estimate treatment effects in the first place. What you can do instead is to simulate data with varying qualities and relationships (e.g., linear, quadratic, piecewise, etc.). This way, if you can demonstrate one method works on all (or most) data-generating scenarios, you have evidence in favor of using it for your dataset.
The 2016 Atlantic Causal Inference Conference data competition did exactly this. The paper about it (Dorie et al, 2019) is very thorough. It explains the many ways they generated the data and what features each data-generating model had that would make it more or less challenging for estimators. The results of the competition were that BART and TMLE dramatically outshone all the other methods, although CEM was not included. This type of simulation study has no less merit than the simulation studies you typically see in statistics papers demonstrating a new method or comparing methods. You can also use the data from this contest to compare your own method. They have an R package described in the article which allows you to simulate the data they simulated and apply your own pet method to it. It's unlikely this data will look much like your own dataset, though, so this alone might not sway your colleagues.
Ask your colleagues why they like CEM so much. It's a generally poorly performing method in that it discards huge amounts of data, the causal effect doesn't correspond to the average treatment effect in any population of interest specified a priori (i.e., not the ATT or ATE), and it relies on many arbitrary decisions by the researcher. I can't think of any study other than the one introducing CEM in which it outperforms another method. One paper that comes to mind is Zubizarreta et al (2014), in which it does so poorly, an effect can't even be estimated from it (i.e., it throws away all the data).
I just noticed you are doing a case-control study rather than a case-cohort study. I'm not a biostatistician so I don't know whether the same methods can be used for both types of study, but maybe someone else can comment on that.


text:
Q: is there an option<> computation expression anywhere? Am I being stupid?
Some things look nicer in a monad/computation expression, I have lots of code using the seq computation expression, but everytime I hit an option<> I have to revert to "Option.map" etc.
Slightly jarring (when I was doing this in C# I wrote a linq operator for a IMaybe<> type and it all looked nice and consistent).
I can, but don't especially want to write one, there must be one (or more) out there, which one do people use?
i.e.
so rather than
let postCodeMaybe =
    personMaybe
    |> Option.bind (fun p -> p.AddressMaybe())
    |> Option.map (fun -> p.Postcode())

we can go
let postCodeMaybe =
    option {
        for p in personMaybe do
            for a in p.AddressMaybe() do
                 a.Postcode()
    }

I have no problem with the former code, except that in my context it exists in lots of "seq" computational expressions that look like the latter (and some developers who will look at this code will come from a C#/LINQ background which are basically the latter).

A: There is no option CE in FSharp.Core but it exists in some libraries.
I think one of the reasons why many CEs are not provided in FSharp.Core is because there are many different ways of doing them, if you google for an option computation expression builder you'll find some are strict, others lazy, some support side-effects others support blending multiple return values into one.
Regarding libraries, there is one in F#x called maybe then you have F#+ which provides generic computation expressions so you have something like Linq where as long as the type implement some methods the CE is ready to use, for options you can use let x:option<_> = monad' { ...  or let x:option<_> = monad.plus' { ...  if you prefer to have the one that allows multiple return values.
Your code will look like:
let x: option<_> = option {
   let! p = personMaybe
   let! a = p.AddressMaybe()
   return a }

Where option is your option builder, could be one of the above mentioned.

A: We use FsToolkit.ErrorHandling. It is simple, actively maintained and works well.
It has CEs for Option, Result, ResultOption, Validation, AsyncResult, AsyncResultOption.
https://www.nuget.org/packages/FsToolkit.ErrorHandling/
https://github.com/demystifyfp/FsToolkit.ErrorHandling


text:
Q: About 2 operators such that $X*(Y+Z) = (X*Y)+(X*Z)$ , $W+(U+V)\neq (W+U)+V$ This question is a follow-up and analogue of a previous very similar question.
I have to seperate questions since it is a bit of a rule ; 1 question at a time , hence this seperate one.
Looking at the other analogue question is not neccessary and can be ignored but for those who care here it is :
About 2 operators and $A*(B+C) =(A+B)*(A+C)$
Anyway,
Consider $2$ distinct binary operators defined for a finite set with $n$ elements.
Operator $*$ behaves like a commutative latin quandle :
$$x*x = x$$
$$a*b=b*a$$
$$a*(b*c)=(a*b)*(a*c)$$
And forms a latin square.
Commutative operator $+$ behaves like
$$A*(B+C) =(A*B)+(A*C)$$
$$X+Y = Y+X$$
And forms a latin square.
Question :
Is $+$ neccessarily associative ?
What are examples of strict non-associative or strict associative ones if they exist ?
( strict mean always that property for every pair of elements )

The special cases where the quandle has no subquandle is perhaps interesting.
( this happens if $n$ is prime but that is not a neccessary condition , it is similar to subgroups basically )

ps: do not confuse with bi-quandles as most define them.

Remarks :
Also note the number of solutions $(*,+)$ for a set with $n$ elements is a bit of a mystery for me , Im not even sure with all these restrictions given that every $n$ has such a pair of operators.
Not even for sufficiently large $n$.
But that is not the main question but just related.
Unless there are no solutions $(*,+)$ for $n$ or only for finitely many $n$ then it becomes very important.


text:
Q: Como llamar datos de tabla pivote Tengo una tabla partners y otra users, las cuales se relacionan en una tabla pivote partner_user, cuando quiero realizar una eliminación de un Partner quiero que también se elimine el User asignado, pero solo puedo obtener con el request el id del Partner y me gustaría con ese id poder buscar en la tabla pivote el id correspondiente al User. Espero ser claro y me puedan ayudar.

A: Creo que lo que quieres hacer es eliminar la relación que hay en la tabla pivote, en realidad con un detach podrias eliminar dicha relación
public function destroy($id)
{
    $partner=Partner::findOrFail($id);
    $partner->users()->detach();
    $partner->delete();
}

Pero en el modelo Partner tendrías que tener la siguiente función
public function users(){
    return $this->belongsToMany(User::class,'partner_user')->withTimestamps();
}

Espero te funcione


text:
Q: Sitecore WFFM Form Report is not showing form data I have installed WFFM on Sitecore 8.0 Update-3, and created a demo form with few fields. After submitting form I am getting success message, in log files as well didn't find any error.
But if I am checking Reports with Form Reports button (Sitecore Functionality), it is not showing any data.
I can see data in reporting database WFFM tables.
Does anyone know how we can show form data on Form Reports Page?
-Yogesh

A: Make sure you have run the WFFM_Analytics.sql script on your reporting database. It can be found under /Data/WFFM_Analytics.sql
Also check your error logs for an aggregation error. If you are getting that you need to follow this post: http://sitecorefootsteps.blogspot.co.uk/2015/06/sitecore-8-wffm-data-aggregation-error.html
Make sure that your have included the Visitor Identification in the head. For MVC this would be @Html.Sitecore().VisitorIdentification().
Finally remember that the data will not be written until the session end, so it might be worth setting the session timeout to 2 minutes when testing. Then it wont take so long for the data to be stored.
EDIT
Are you using an IOC Container on your project? I had an issue with SimpleInjector blocking the ajax calls to the form reports data. Check your browser console for javascript errors, specifically calls to /api/sitecore/FormReports/GetFormFieldsStatistics returning error 500.
If you are getting those, check this post on a way to fix it with SimpleInjector - other IoC containers may have similar issues. http://www.sitecorenutsbolts.net/2015/07/27/Simple-Injector-and-WFFM-Controller-Injection-Woes/
-Richard

A: We recently were faced with the same issue.  Data was being stored in the SQL database correctly, but the form reports were coming up blank.  As @Richard pointed out, we saw 404 errors in the console on the reports page.
I was able to solve our issue by updating our custom 404 logic to ignore paths beginning with "/api".


text:
Q: WP Single.php If and elseif statement execution <?php if (in_category('3')) {
        $args = array(
        'cat' => 'Japan',
        'orderby' => 'meta_value_num',
        'meta_key' => 'japan_id',
        'order' => 'ASC',
        );
        $the_query = new WP_Query( $args );

        } elseif (in_category('5')) {
        $args = array(
        'cat' => 'Borneo',
        'orderby' => 'meta_value_num',
        'meta_key' => 'borneo_id',
        'order' => 'ASC',
        );
        $the_query = new WP_Query( $args );}?>

        <?php while ( $the_query->have_posts() ) : $the_query->the_post();?>
        <?php $status = get_post_meta($post->ID, 'status', true); ?><?php $finishdate = get_post_meta($post->ID, 'finishdate', true); ?>
        <a href="<?php the_permalink(); ?> " rel="favourite" title="<?php the_title(); ?>"><?php the_post_thumbnail('featured-thumbnail'); ?>
        <?php endwhile; ?>
        <?php
       // Reset Post Data
       wp_reset_postdata();?>

Hi all, I'm trying to do a if and elseif to check :

*

*If this single post belongs to category 3

*Get info of this post (category name, order by meta value number of this meta_key in ASC order

*Else if this single post belongs to category 5

*Get info of this post ... in ASC order

However, i keep getting error that "Fatal error: Call to a member function have_posts() on a non-object in ... on line...." I want to display all the featured thumbnails of all the posts that are from the same category as the Single Post.
Example of SIngle Post : http://ethanlimphotos.com/2012/04/19/orangutan-grabs-legs
The featured thumbnails scroll should be displayed like this http://ethanlimphotos.com
I want the featured thumbnails scroll on the Index Page to work on the Single page too.
Please help, thank you! :D

A: I really don't understand why almost everyone is creating a new object when they want to do custom loops :) Is this because this is the way you saw an example, or you have different reasons(I'm just really curious :) ).
Anyway, the way I go when I need a custom loop is to just call query_posts(), use the normal have_posts() and the_post() and then reset the query variable with wp_reset_query(). So here's how your code will look like when you use that approach:
<?php if (in_category('3')) {
    $args = array(
    'cat' => 'Japan',
    'orderby' => 'meta_value_num',
    'meta_key' => 'japan_id',
    'order' => 'ASC',
    );
    query_posts( $args );
} elseif ( in_category( '5' ) ) {
    $args = array(
        'cat' => 'Borneo',
        'orderby' => 'meta_value_num',
        'meta_key' => 'borneo_id',
        'order' => 'ASC',
    );
    query_posts( $args );
}?>

<?php while ( have_posts() ) : the_post(); ?>
    <?php $status = get_post_meta($post->ID, 'status', true); ?><?php $finishdate = get_post_meta($post->ID, 'finishdate', true); ?>
    <a href="<?php the_permalink(); ?> " rel="favourite" title="<?php the_title(); ?>"><?php the_post_thumbnail('featured-thumbnail'); ?>
<?php endwhile; ?>
<?php
// Reset the query data
wp_reset_query();?>


text:
Q: UglifyJS - how to output to a different folder? I'm trying to use UglifyJS in order to minify my code but I'm running into a bit of a problem. I have a file structure like so:
/deploy
  /assets
    /js
      ((minified file goes here))
/js
  script-compiled.js

I want to run UglifyJS on js/script-compiled.js located in my private folder and have it output a script.min.js file in my deploy/js (the js that gets uploaded to my website) folder. Here's what I have so far for my command:
uglifyjs js/script-compiled.js --compress --mangle --screw-ie8 -o > deploy/assets/js/script.min.js

Which gives me this error:
fs.js:549
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
             ^

TypeError: path must be a string

I'm a little confused. Is it possible to output a file to a different directory? Maybe this is just a general Bash thing. Thanks!

A: You specified the -o option but you didn't provide a value. From the docs:

-o filename or --output filename — put the result in filename. If this isn't given, the result goes to standard output (or see next one).

So either do
uglifyjs ... -o deploy/assets/js/script.min.js

or omit -o and redirect stdout
uglifyjs ... > deploy/assets/js/script.min.js


text:
Q: Embed flv file as banner My client provided me with a .flv file to place on their home page as a banner. I have searched the internet for a while but did not come accross to a proper way of doing it. First of all, is it "the" way of doing such banners? or are they supposed to provide me with a .swf instead? If .flv is ok, then how do I embed it (no play controls or anything...) into my html page?

A: If you have Flash, you can import the FLV into a flash file in a couple ways. One is you can just have a link to it and Flash can spit out a swf that will play the FLV which is still a separate file on the server, or you can choose to embed the video directly in the Flash file so the swf will contain all the video content. If you don't have Flash, one of these other answers might work for you, but a browser won't play an flv directly. If you are creating the web page, dreamweaver can also generate a swf to play the flv for you so you wouldn't even need Flash in that case.

A: I'd use http://www.longtailvideo.com/players/jw-flv-player/ which is a highly configurable flash flv player. If you want no controls and set it to auto play, it can be done easily by passing flashvars to it like controlbar=none, autoplay=true, repeat=true to it. just read on it. it is very much well documented. you embed it on your pages like any regular swf since its built with flash.

A: You will need a flv player (written in flash) you can try JW Player which is open source and used by many sites.
BTW: I would suggest not using the control in auto play as some people browsing the site might come from a mobile connection and playing the movie might cost.


text:
Q: Stay on the page after minimizing the app with WebView Xamarin Forms I try to keep the contents of webView after minimizing the application. how to do? here are my codes
public partial class ItemCompte : ContentPage
{
string _fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "notes.txt");
    public ItemCompte()
    {
        InitializeComponent();
        var current = Connectivity.NetworkAccess;
        var profiles = Connectivity.ConnectionProfiles;

        if (current == NetworkAccess.Internet)
        {
            if (File.Exists(_fileName))
            {
                string para = File.ReadAllText(_fileName); ;
                Webview.Source = "https://www.bcongres.com/?param=" + para;

            }
        }
        else if (profiles.Contains(ConnectionProfile.Ethernet))
        {
            if (File.Exists(_fileName))
            {
                string para = File.ReadAllText(_fileName); ;
                Webview.Source = "https://www.bcongres.com/?param=" + para;
            }
        }
        else
        {
              DisplayAlert( "Connection Error",
                    "Venez activer vos données de l'internet, et demarrer l'application",
                    "Try again");

        }

    }
    public async  void Conn()
    {

    }
    protected async override void OnAppearing()
    {
        base.OnAppearing();
        await progress.ProgressTo(0.9, 100, Easing.SpringIn);
    }

    protected void OnNavigating(object sender, WebNavigatingEventArgs e)
    {

        progress.IsVisible = true;
    }

    protected void OnNavigated(object sender, WebNavigatedEventArgs e)
    {
        progress.IsVisible = false;
    }
}


text:
Q: MVC Core DbContext disposed between function calls I have a pretty simple service that creates and entity and assigns an alpahnumeric sequence to a property then persists the entity to the db. The context is injected into the service via the MVC Core dependency injection like so.
// Configure DB context
        var connectionString = Configuration.GetConnectionString("DefaultConnection");
        services.AddDbContext<MyDataContext>(opt => opt.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationAssembly)));

The context is initialized in the service constructor via
public MyService(MyDataContext myDataContext)
{
    this.myDataContext = myDataContext;
}

The logic to perform the insert is as follows
public async Task  GenerateRecord()
 {
    // Init the entity
    var myEntity = new myEntity
    {
        Id = Guid.NewGuid(),
        DateCreated = DateTime.Now,
        Sequence = await GetSequence();
    };

     myDataContext.MyEntities.Add(myEntity);
     myDataContext.SaveChanges();

 }

The logic to generate the sequence is
private async Task<string> GetSequence()
{

    DbCommand cmd = myDataContext.Database.GetDbConnection().CreateCommand();
    cmd.CommandText = "dbo.fnGetAlphaNumSeqID";
    cmd.CommandType = CommandType.StoredProcedure;
    DbParameter param = cmd.CreateParameter();
    param.Value = "";
    param.DbType = DbType.String;
    param.Size = 100;
    param.Direction = ParameterDirection.Output;
    param.ParameterName = "@ReturnSequence";
    cmd.Parameters.Add(param);

    if (cmd.Connection.State != ConnectionState.Open)
    {
        cmd.Connection.Open();
    }
    await cmd.ExecuteNonQueryAsync();

    var newId = param.Value.ToString();

    return newId;

}

The problem that I am running into is that, after the call to ExecuteNonQueryAsync the context is disposed. I am awaiting the only async call in the function and am returning async Task as opposed to async void. I am currently unable to determine the appropriate method for getting this to succeed or why the context is being disposed of when it is not being utilized in a using() statement and am hoping that someone can point me in the right direction.


text:
Q: NSManagedObjectContext starts with value and become null I have just started developing iPad apps and I'm struggling with an issue for too long now, so I've decided to go for help.
I have an application for iPad using storyboard and started as a Tabbed application using CoreData. So the issue is, my NSManagedObjectContext starts with a value but when I move to another tab, the managedObjectContext becomes null.
Don't know what to do. Some help would be greatly appreciated.
Thanks
Elkucho

A: I'm slightly confused...
self.window.rootViewController

should return your instance of UITabBarController, which should not respond to setManagedObjectContext: and therefore should crash.
With this in mind what you need to do it

*

*Get the tabBarController

*Cycle through the viewController's that the tabBarController manages

*Pass them the managedObjectContext
for (id viewController in self.window.rootViewController.viewControllers) {
  [viewController setManagedObjectContext:self.managedObjectContext];
}

Edit
I've taken a quick look.

*

*You rarely need to subclass UITabBarController and you don't really need to in this case.
What you want to do is just get the managedObjectContext to each of the viewControllers in the tabBarController, the tabBarController itself does need to know about it.

I changed your application:didFinishLaunchingWithOptions: to the following and it worked the way it was supposed to
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  UITabBarController *tabBarController = (id)self.window.rootViewController;

  for (id viewController in tabBarController.viewControllers) {
    [viewController setManagedObjectContext:self.managedObjectContext];
  }
}


text:
Q: Flex container and float, which is the correct width? I've got a document like this:

main {
  width: 200px;
}

main>div {
  display: flex;
}

main>div:nth-child(odd) {
  background: red;
  height: 40px;
}

main>div:nth-child(even) {
  background: green;
  height: 20px;
}

main>aside {
  shape-outside: content-box;
  background: pink;
  width: 50%;
  float: right;
  clear: right;
}

main>aside:nth-child(odd) {
  margin-top: 100px;
  height: 50px;
}

main>aside:nth-child(even) {
  margin-top: 50px;
  height: 40px;
}

where I want to push some floating elements down by a given offset. This works in Firefox 63 but not in Chrome 69, and I wonder what is the correct behaviour, and if any workarounds are known.
So I want the main content to flow around just the content area of the aside, and ignore the top margin, even though the div comes after the aside in the document. To achieve this, I use css shapes to make the main content flow around the content box. To make each item (and this is where my doubt is) take only the available width taking into account floating elements, I set display: flex. In Firefox this makes only the divs next to the aside content box be 50%. Is this behaviour documented somewhere, that flex containers don't overlap with floating elements like block elements do?
Chrome does not honor the css shape and makes every div in the main until after the last aside half the width when the divs have display: flex.
Codepen link: https://codepen.io/anon/pen/qQjOqp


text:
Q: Netlify Page Not Found/White Page I have been trying to figure out Netlify redirects. My Netlify app is at this link (however this is a blockchain application and requires that you have metamask, so I will try to explain my problem so that you don't have to install it to actually answer my question): rekt.netlify.app
I have two main problems:

*

*I have already tried the whole _redirects file with /* /index.html 200 in it. This works when I go to rekt.netlify.app/games and refresh, it will actually come back to that page. That's good. The issue is when I then go to rekt.netlify.app/games/Valorant for example, it will be a white page on refresh, and I cannot figure out why. In my react application, I have react router set up so the path is path="/games/:game"
I went to the Networks tab in the google inspect and I found that this was the request URL when I refresh the page on /games/Valorant: https://rekt.netlify.app/games/static/css/2.80dce9aa.chunk.css
As you can see, the issue is probably something to do with that /games/ comes before /static/ in the URL. I'm a beginner so I don't know what that actually means.

*The second issue I am having is that, the img tags of the games load on the /games page, however, when you click on a specific game and attempt to go to a /games/Valorant for example the image will not load. I believe this is due to a similar problem. I have gone into Network tab of google inspect and when I look at the image being loaded in the /games page, it attempts to GET https://rekt.netlify.app/static/media/league_wallpaper.f5e6bf5f.jpg which works. However, when being loaded in the /games/Valorant page, it attempts to GET https://rekt.netlify.app/games/static/media/league_wallpaper.f5e6bf5f.jpg and this does not work, it's a blank page.

You can notice that the second link there has /games/ in it which I believe is preventing it from getting the image. Potentially the problem here is that anything more than one / in the URL is messing things up? I'm not sure. This is the link to my github project: https://github.com/jacob-tucker/ReKt
Edit: Here are some screenshots that will hopefully help. This first one shows that the request URL is trying to get the image from /games/static (which I don't think makes sense). This is happening on the /games/Valorant page.

And then here is a screenshot of /games/Valorant trying to load as well after I refresh the page and get a blank white screen (it returns a status code of 200 because I have /* /index.html 200 in my _redirects file.

A: I had a the same issue a while ago, I've just added
"homepage": "https://my-app.netlify.app",
in package.json and it worked perfectly.


text:
Q: To convert Excel into CSV efficiently in ruby I used the spreadsheet gem to do this. It works but it can be very slow at times .I even tried the Roo gem, but that didn't improve the performance. Is there a better way to do this job? The weird thing is that some worksheets in the same excel work faster and some worksheets work very slowly, even taking up to 1 hour.
Can we use open office to open each worksheet(tab) in a single excel and convert them to csv much faster? If yes, how would I do it in ruby?
Or is there an even better solution?
Just adding a small example I tried with Roo gem
xls = Roo::Excel.new(source_excel_file)
xls.each_with_pagename do |name, sheet|
  # p sheet.to_csv(File.join(dest_csv_dir,name + ".csv"))
  #sheet.parse(:clean => true)#.to_csv(File.join(dest_csv_dir,name + ".csv"))
  puts name
  puts sheet.parse(:clean => true)
end

A: Cowardly Preface: I am SUPER new to ruby and know almost nothing of rails, but I have tangled with Excel before. I created a dummy workbook on my local machine with 5 sheets, each containing 10 columns and 1000 rows of randomly-generated numbers. I converted each sheet into its own CSV with this:
require 'win32ole'
require 'csv'

# configure a workbook, turn off excel alarms
xl = WIN32OLE.new('excel.application')
book = xl.workbooks.open('C:\stack\my_workbook.xlsx')
xl.displayalerts = false

# loop through all worksheets in the excel file
book.worksheets.each do |sheet|
  last_row = sheet.cells.find(what: '*', searchorder: 1, searchdirection: 2).row
  last_col = sheet.cells.find(what: '*', searchorder: 2, searchdirection: 2).column
  export = File.new('C:\\stack\\' + sheet.name + '.csv', 'w+')
  csv_row = []

  # loop through each column in each row and write to CSV
  (1..last_row).each do |xlrow|
    (1..last_col).each do |xlcol|
      csv_row << sheet.cells(xlrow, xlcol).value
    end
    export << CSV.generate_line(csv_row)
    csv_row = []
  end
end

# clean up
book.close(savechanges: 'false')
xl.displayalerts = true
xl.quit

An eyeball benchmark for this script was ~30 seconds, with each attempt coming in a few seconds above or below that.

A: I assume we are talking about old Excel format (xls), it seems spreadsheet gem can't work with xlsx anyways.
I'd give a try to one of command-line spreadhseet converters: either xls2csv from catdoc package (really fast, though not all Excel files are processed successfully) or ssconvert from gnumeric package (moderate speed, and requires to install entrie GNumeric, which sometimes not an option for server, but really robust).
NB: When parsing Excel, roo just requires spreadsheet and wraps it in own API, so it never can be faster or more reliable than spreadsheet.
NB2: If I remember correctly (thought it was some long years ago), trying to automate OpenOffice from ruby was a) really hard and b) really slow.

A: xls_file = Roo::Excelx.new('test.xlsx')
CSV.open('test.csv') do |csv|
    (2..xls_file.last_row).each do |i| # if you do not need header otherwise (1..xls_file.last_row)
        csv << a.row(i)
    end
end

A: Be sure you're using the up-to-date Roo (1.13.2).
Also be sure you're using the patch for skipping trailing blank rows:
https://github.com/Empact/roo/blob/master/lib/roo/worksheet.rb
If you can post one of your spreadsheets that's taking a long time to parse, it may help people here help you. Just be sure to delete any confidential data.


text:
Q: Checking days which are closest This is going to be a bit hard to explain but
I have 2 dates, i'm interested in the day and month unless the 2 dates have the same year
2015/12/30 and 2019/01/04
ignoring the year part (kind of) the result i'm expecting 6 days difference for the 2 dates above
if i was to use date.DayOfYear i would get 364 (2015/12/30) and 4 (2019/01/04) respectively
however if the years are same then
 2019/01/04  2019/12/30  then the result i'm expecting is 359 days difference
is there a clever way of doing this without peppering the code with if statements?

A: If the year difference was just 0 or 1, then you could just convert both dates to an absolute value (in seconds, ms, unix time or whatever), subtract the 2 values and convert it to full days. But if you have more than 1 year diff (as 2015 and 2019), then you have to have an "if" an think about what are you actually trying to do there. You shouldn't use DayOfYear, because some years have 366 days, so you can't be sure that 364 corresponds to 1 or 2 days left in that year.


text:
Q: How can I tell if this graph is 4-Edge-Connected? Is this graph 4-Edge Connected? What is the way to determine?

A: A graph is $4$-edge-connected if deleting fewer than four edges cannot disconnect it.  For your graph:

*

*Deleting one edge cannot disconnect it because this graph has a Hamiltonian cycle, $(1,2,5,7,8,10,9,6,3,4)$.  Deleting an edge not on the cycle does not disconnect the graph.  Deleting an edge on the cycle does not disconnect the graph (go the other way around the cycle).

*There are a pair of edges whose deletion disconnects the graph: $\{3,6\}$ and $\{5,7\}$.

Notice that the subgraph on vertices $\{1,2,3,4\}$ and also on the vertices $\{7,8,9,10\}$ are $K_4$s, so are $4$-edge-connected.  Temporarily mentally collpase them to points.  The resulting four vertex multigraph is a cycle with edge multiplicities (in order going around the cycle) $1$, $2$, $1$, and $2$.  From this we can see that deleting the two multiplicty-$1$ edges will disconnect the reduced graph, hence disconnect the original graph.
A general method is, for each pair of vertices $a,b$, find at least $k-1$ edge-disjoint paths from $a$ to $b$.  For instance, in your graph, $(1,2)$, $(1,3,2)$, and $(1,4,2)$ are three paths from vertex $1$ to vertex $2$ and no edge appears in two (or more) of these paths.  So to separate vertex $1$ from vertex $2$ requires deleting at least three edges.  Continue for every other pair of vertices.
There exist algorithms that compute variants of maxflow to find the largest $k$ for which a given graph is $k$-edge-connected.


text:
Q: Getting access to loop variables I am not getting the information from the first loop into the second one it gives an error saying for example: Notice: Undefined index: txtprice in..
the issue is that I can't get the data from if(isset($_POST['getdata'])) into if(isset($_POST['addto'])) to echo it out and make calculations

<form method="post" action="newcal.php">

  Item #:
  <input type=text name= txtitem >

  <fieldset style = "width:60px">
  <input type=submit value = "Get Data" name= getdata>
  <input type=submit value = "Add to Cart" name= addto>
  <input type=submit value = "Get Total" name= gettotal>
  </fieldset>

</form>

<?php
$item = (isset($_POST['txtitem']) ? intval($_POST['txtitem']) : null);

 $stuff = array(
    array("id" => 1,"name" => "Apples","price" => 50 ),
    array("id" => 2,"name" => "Pineapples","price" => 125 ),
    array("id" => 3,"name" => "Mango","price" => 35 ),
    array("id" => 4,"name" => "Banana","price" => 25 ),
    array("id" => 5,"name" => "Naseberry","price" => 38 ));

   if(isset($_POST['getdata']))
   {

    foreach ($stuff as $row)
    {
     if ($row['id'] == $item)
     {
     $name = $row['name'];
     $price = $row['price'];

     echo "Item Number:&nbsp &nbsp <input type=\"text\" name=\"txtinum\"  VALUE=\"$item\">"."
"."
";

     echo "Name: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp<input type=\"text\" name=\"txtname\"  VALUE=\"$name\">"."
"."
";

     echo "Price : &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp<input type=\"text\" name=\"txtprice\" VALUE=\"$price\">"."
"."
";

     echo "Quantity: &nbsp &nbsp &nbsp &nbsp &nbsp <input type=\"text\" name=\"txtquant\">"."
"."
";

     }
    }
    }

    if(isset($_POST['addto']))
     {
     $quant = isset($_POST['txtquant']);
    $cal = $price * $quant;

       echo "
";
       echo "
";
       echo " Item ID	" ;
       echo " Name	";
       echo" Price	";
       echo" Quantity	";
       echo" Sub Total 	";
       echo "
";
       echo "
";
       echo " $itemnum 	";
       echo " $name 	";
       echo " $price 	";
       echo " $quant 	";
       echo "   	";
       echo "
";

     }
?>


text:
Q: How to save and retrive image on Google Drive I have success fully integrate google drive in my app but i will stuck to save and Fetch image on google drive
i have write following code
 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"'Quickstart Uploaded File ('EEEE MMMM d, YYYY h:mm a, zzz')"];
    GTLDriveFile *file = [GTLDriveFile object];
    file.title = [dateFormat stringFromDate:[NSDate date]];
    file.descriptionProperty = @"Uploaded from the Google Drive iOS Quickstart";
    file.mimeType = @"image/png";
    UIImage *imagenda=[UIImage imageNamed:@"back_button.png"];
   // NSData *data = UIImagePNGRepresentation(imagenda, 1.0);
    // add image data
    NSData *data = UIImageJPEGRepresentation(imagenda, 1.0);
    GTLUploadParameters *uploadParameters = [GTLUploadParameters uploadParametersWithData:data MIMEType:file.mimeType];
    GTLQueryDrive *query = [GTLQueryDrive queryForFilesInsertWithObject:file
                                                       uploadParameters:uploadParameters];
  //  UIAlertView *waitIndicator = [self showWaitIndicator:@"Uploading to Google Drive"];

    [driveService executeQuery:query
                  completionHandler:^(GTLServiceTicket *ticket,GTLDriveFile *insertedFile, NSError *error)
     {
         //[waitIndicator dismissWithClickedButtonIndex:0 animated:YES];
         if (error == nil)
         {
             NSLog(@"File ID: %@", insertedFile.identifier);
             [self showAlert:@"Google Drive" message:@"File saved!"];
         }
         else
         {
             NSLog(@"An error occurred: %@", error);
             [self showAlert:@"Google Drive" message:@"Sorry, an error occurred!"];
         }
     }];

A: You need to add scope:-
// Authorization scope
NSString * const kGTLAuthScopeDrive                 = @"https://www.googleapis.com/auth/drive";
NSString * const kGTLAuthScopeDriveAppdata          = @"https://www.googleapis.com/auth/drive.appdata";
NSString * const kGTLAuthScopeDriveAppsReadonly     = @"https://www.googleapis.com/auth/drive.apps.readonly";
NSString * const kGTLAuthScopeDriveFile             = @"https://www.googleapis.com/auth/drive.file";
NSString * const kGTLAuthScopeDriveMetadataReadonly = @"https://www.googleapis.com/auth/drive.metadata.readonly";
NSString * const kGTLAuthScopeDriveReadonly         = @"https://www.googleapis.com/auth/drive.readonly";
NSString * const kGTLAuthScopeDriveScripts          = @"https://www.googleapis.com/auth/drive.scripts";

// Creates the auth controller for authorizing access to Drive API.
- (GTMOAuth2ViewControllerTouch *)createAuthController {
    GTMOAuth2ViewControllerTouch *authController;
    NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeDriveFile, nil];
    authController = [[GTMOAuth2ViewControllerTouch alloc]
                      initWithScope:[scopes componentsJoinedByString:@" "]
                      clientID:kClientID
                      clientSecret:kClientSecret
                      keychainItemName:kKeychainItemName
                      delegate:self
                      finishedSelector:@selector(viewController:finishedWithAuth:error:)];
    return authController;
}


text:
Q: Double implication The present question is about a double implication.
I have the following implications:
$(a)\implies (b)\implies ((c)$ or $(a))$
Can I deduce that $(b)\implies(a)$ only?

A:
$(a)\implies (b)\implies ((c)$ or $(a))$
Can I deduce that $(b)\implies(a)$ only?

No.
What you have is the following:
$$(a) \implies (b)\tag{1}$$
$$(b)\implies (c\lor a) \equiv \lnot b \lor c \lor a\tag{2}$$
In (2) I use the equivalence $p\implies q \equiv \lnot p \lor q$
From (2), It may very well have that each $\lnot b$ is true, and $a$ is true, and $c$ is true. It may very well be that we have only $\lnot b$ is true, or only $a$ is true, or only $c$ is true. Or it may very well be that we have only $\lnot b\lor c\equiv b\implies c$ is true. Or, we may have that $\lnot b \lor a \equiv b\implies a$ is true. Or both these last cases.
In short, $b\implies a$ is satisfiable (possible), but it is not logically necessary/valid.
\begin{array}{a|b|c|aVc|rem|}
\hline
a&b&c&a\vee c& \\
\hline
F&F&F&F&\\
F&F&T&T\\
F&T&F&F\\
F&T&T&T& \text{Here, b $\rightarrow (a \lor c)$ is true, but $b \rightarrow a$ is false.}\\
T&F&F&T\\
T&F&T&T\\
T&T&F&T\\
T&T&T&T\\
\end{array}
There's no logical justification for concluding it must be the case that $b\implies a$.
**However, if you know that $a \equiv \lnot c$, then that counterexample is ruled out, because in the above indicated counterexample, we have $a = c = T$.

Now, if you also have the premise $$\lnot c\tag{3},$$ then $(3)$ together with $(2)$ imply that $\lnot b \lor a \equiv b\implies a$, by the disjunctive syllogism $\lnot b \lor c \lor a \equiv (\lnot b \lor a) \lor c$:
$\;\;\;(\lnot b \lor a) \lor c$
$\;\;\;\lnot c$
$\therefore (\lnot b \lor a)\equiv b\implies a$.

A: See a truth table. It is often helpful.
$$
\begin{array}{a|b|c|aVc|rem|}
\hline
a&b&c&a\vee c& \\
\hline
F&F&F&F&\\
F&F&T&T\\
F&T&F&F\\
F&T&T&T& \text{Here, b $\implies$a $\vee$ c is true but b $\implies$a is not.}\\
T&F&F&T\\
T&F&T&T\\
T&T&F&T\\
T&T&T&T\\
\end{array}
$$
Note that False can imply Truth but truth cannot imply False.
So your statement is SATISFIABLE but not VALID.
$\textbf{Edit}$ Edited in response to some silly mistake.

A: Although truth tables provide a systematic approach to problems like this, it's often more efficient to just think about "what can go wrong?" --- in this case, how (if at all) could the  assumptions $(a\implies b)$ and $(b\implies(c\lor a))$ be true while the proposed conclusion $(b\implies a)$ is false?  Falsehood of an implication is quite restrictive; it requires both that the antecedent is true and that the consequent is false, so in this case, to falsify the proposed conclusion, you'd need $b$ true and $a$ false.  That automatically makes the first hypothesis, $(a\implies b)$, true.  As for the second hypothesis, its antecedent $b$ is true, so the only way the implication could be true is for the consequent to be true.  In this case, you'd need $(c\lor a)$ to be true.  Since $a$ is false, you'd need $c$ true.  In this way you find a truth assignment, "$a$ false and both $b$ and $c$ true," that makes your hypotheses both true and the proposed conclusion false, so the inference is not correct.


text:
Q: How can I extract iframes from text with Perl's Mojo::DOM I have this text  and when I do:
print STDERR (Mojo::DOM->new($args->{'body'})->at('iframe'));

output:

`

It is just printing the first iframe in the body. Why is it not printing the other iframes and   can I put all iframes in an array?

A: According to Mojo::Dom documentation. The at function only finds the first element matching. So it should only return 1. I think find is what you are after, as it returns a collection that matches
use strict;
use warnings;

use Mojo::DOM;

my $dom = Mojo::DOM->new();
while (<DATA>) {
    $dom->append_content($_);
}

#print $dom;

print $dom->find('iframe');

__DATA__

No one's telling the truth anymore, and that makes the numbers suspect.

Instead of addressing the fact that some text

The very first example AP cites was already corrected.some text ....Reacting to recent research that has questions.

 Arriving at such a conclusion requires not only obscuring the importance in pushing global austerity strong measures of too little spending.

prints your iframes:

EDIT:

*

*You can iterate over each iframe with each function of Mojo::Collection:
my $collection = $dom->find('iframe');
$collection->each(sub {
    my ($e, $count) = @_;
    print "$count: $e\n"; # Or do something besides print.
 });

*You can add an @ to loop over it like an array:
foreach (@$collection) {
   print "\n Next Elt.:", $_->{src}, ",\n"; #still access elements of iframe with ->
}


text:
Q: Change ProfileImage in Drawer at runtime I have a image in my Drawer sidemenu where the path to it is stored in a final object named userdata:
class MyDrawer extends StatelessWidget {
  MyDrawer({Key key, this.userdata}) : super(key: key);
  final User userdata;

  @override
  Widget build(BuildContext context) {
    return new Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          if (userdata != null) ...[
            DrawerHeader(
                decoration: BoxDecoration(color: Colors.green),
                child: Stack(children: <Widget>[
                  Align(
                      alignment: Alignment.centerLeft,
                      child: ClipOval(
                        child: userdata.image == '' || userdata.image == null
                            ? CircleAvatar(
                                radius: 50,
                                backgroundColor: Colors.white,
                                backgroundImage: AssetImage('assets/images/avatar.png'))
                            : Image.network(
                                userdata.image,
                                width: 100,
                                height: 100,
                                fit: BoxFit.cover,
                              ),
                      )),

When I am now on a page (profile.dart) where I can update my profile image (which is pushed by the drawer -sidemenu-)
How can I update the userdata object in the drawer class?
I found some ideas like streams, but is this really neccessary ?
edit: profile.dart
class ProfilePage extends StatefulWidget {
  @override
  _MyProfilePageState createState() => _MyProfilePageState();
}

class _MyProfilePageState extends State<ProfilePage> {
  final _formKey = GlobalKey<FormState>();
  final _username = TextEditingController();
  final _email = TextEditingController();
  final _firstname = TextEditingController();
  final _lastname = TextEditingController();
  final picker = ImagePicker();
  String image = '';

  @override
  void initState() {
    ProfileApi().getProfile().then((user) {
      setState(() {
        this._username.text = user.sId;
        this._email.text = user.email;
        this._firstname.text = user.firstname;
        this._lastname.text = user.lastname;
        this.image = user.image;
      });
    });
    super.initState();
  }

.....

  changeUser() async {
    try {
      User userdata = await ProfileApi().updateProfile(
          this._username.text, this._email.text, this._firstname.text, this._lastname.text);

    //call some function here to update userdata in my drawer  <--

      Fluttertoast.showToast(msg: 'Profile updated');
    } on Exception catch (error) {
      Fluttertoast.showToast(msg: error.toString());
      return;
    }
  }

i also have a storage class where the userdata object is also provided:
class UserStorage {
  Future<User> getUserData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String userdata = prefs.getString('userdata') ?? '';
    if (userdata != "") {
      dynamic user = json.decode(userdata);
      return User.fromJson(user);
    } else {
      return null;
    }
  }
}

A: Keep your userData content in a global variable
globals.dart file
library globals;

ValueNotifier userDataNotifier = ValueNotifier(null);

Convert your MyDrawer class to StatefulWidget and remove the User variable inside it. Then use your variable in a ValueListenableBuilder widget
import 'globals.dart' as globals;
// ...
class MyDrawer extends StatefulWidget {
  MyDrawer({Key key}) : super(key: key);

  @override
  _MyDrawerState createState() => _MyDrawerState();
}

class _MyDrawerState extends State<MyDrawer> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      //...
            Align(
              //...
              child: ValueListenableBuilder(
                valueListenable: globals.userDataNotifier,
                builder: (context, userdata, _) {
                  return ClipOval(
                    child: userdata.image == '' || userdata.image == null
                        ? CircleAvatar(
                        radius: 50,
                        backgroundColor: Colors.white,
                        backgroundImage: AssetImage('assets/images/avatar.png'))
                        : Image.network(
                      userdata.image,
                      width: 100,
                      height: 100,
                      fit: BoxFit.cover,
                    ),
                  );
                },
              ),
            ),
    );
  }
}

Finally in your changeUser function, simply change the content of your notifier
import 'globals.dart' as globals;
// ...

changeUser() async {
  try {
    User userdata = await ProfileApi().updateProfile(this._username.text, this._email.text, this._firstname.text, this._lastname.text);

    // simply change the content of userData
    globals.userDataNotifier = userdata;

    Fluttertoast.showToast(msg: 'Profile updated');
  } on Exception catch (error) {
    Fluttertoast.showToast(msg: error.toString());
    return;
  }
}


text:
Q: Install one package from Debian sid on Debian Wheezy? I need the python-statsd which is only in Debian (sid).
What are the steps to install this package under Debian Wheezy please ?

A: You can use pip to install python packages instead.
pip search python-statsd => "statsd is a client for Etsy's node-js statsd server. A proxy for the Graphite stats collection and graphing server."
To install statsd use pip install python-statsd


text:
Q: Trying to get property of non-object json in php I am trying to get this code to work but I keep getting this error :

Trying to get property of non-object..

I've validated my json object, but still no luck. I searched for the problem but didn't find any solution. First part of my code which creates the JSON and print it:
$response['team']['tid'] = $teamData['tid'];
$response['team']['name'] = $teamData['name'];
$response['team']['wins'] = $teamData['wins'];
$response['team']['group'] = $teamData['tgroup'];
$otherTeamNames = $db->query("SELECT name from teams where tgroup= '$teamData[4]'");

while($values = $otherTeamNames->fetch(PDO::FETCH_ASSOC) ){
    if($values['name'] != $teamData['name'])
    $response['team']['otherteam'][] = $values;

}
$response['success'] = 1;
echo json_encode($response);

the second part which will decode the JSON
$json = file_get_contents('http://localhost/pract/getSingleTeamById.php', false, $context);

$teamInformation = json_decode($json);
$success = $teamInformation->{"success"};

The output of $json before decoding:
{"team":{"tid":"2","name":"Italy","wins":"4","group":"D","otherteam":[{"name":"Uruguay"},{"name":"England"}]},"success":1}

Any help would be appreciated.

A: Can you try like this ?
Instead of

$teamInformation = json_decode($json);
  $success = $teamInformation->{"success"};

Use

$teamInformation = json_decode($json, true);
  $success = $teamInformation["success"];