text:
Q: What exactly does a diode do? Disclaimer: I'm a total beginner here.
As explained in other answers here, current in a circuit doesn't flow from negative to positive and the direction doesn't matter.
So what should I make of diodes, which are supposed to make the current flow only in one direction?

A: For a beginner, the basic answer is that a diode is a one way valve for current.  Of course none of them are perfect.  There will still be a little bit of pressure (voltage) accross the valve even when current is flowing in the forward direction, and there is some amount of backwards pressure (reverse voltage) at which the thing breaks, but "one way valve for current" is most of what you need to know to get started.
After you get into this a bit more, then go back and look at Photon's answer and see all the nasty little details of real diodes.  For now though, I think that will confuse more than illuminate.
One way valves for current are useful in a variety of circumstances.  One obvious one is to make a DC power supply from AC.

A: The other question is about the fact that current flows in complete circuits --- there is no current without a complete loop for current to flow through. Some of the answers went off on a tangent discussing the difference between electron current and conventional current. In circuit design, you can safely ignore electron current, and always think in terms of conventional current. But the direction of current flow absolutely does matter.
As for diodes, ideally, a diode allows current to flow through it in only one direction, from anode to cathode. Specifically, above a certain "threshold" voltage, it only requires a very small increase in voltage to increase the current to astronomical levels:

(CC image from openwetware.org)
The reverse breakdown behavior (large reverse current when high reverse bias is applied) is normally considered a non-ideality rather than part of the ideal diode behavior.
Some diodes have other effects, such as LEDs, which emit light when current flows through them; or zener diodes which are normally used in the reverse breakdown region.
Edit

what's the purpose of including a garden-variety diode (not an LED) in a circuit?

Typically, you use them when you want to be sure current can only flow in one direction. For example,

*

*To protect a circuit from a battery installed in reverse.

*To form a full-bridge rectifier circuit (using 4 diodes) to convert AC power to DC.

*In a peak detector circuit.

In circuits using ac signals, proper manipulation of the dc bias point of a diode allows it to be used as a switch to route those signals.
You might also see a diode used in cases where the designer knows that current will be flowing in the proper direction to create a rough-and-ready "fixed" voltage drop of about 0.7 V.
Another use is to use a (properly designed) diode's ability to sink large amounts of current (in the forward direction) to protect more sensitive circuits from overload or ESD conditions, or in a snubber circuit to reduce transmission line ring.
Another use is that, going beyond the dc properties, a diode in reverse bias has a variable capacitance depending on the magnitude of the bias. This variable capacitance can be used to tune oscillators or filters. Diodes specially designed for this use are called varicaps.

A: A diode always allows current through in one way only. It has 2 electrodes, an anode and a cathode. Usually you use them when you want to be sure that the current can only flow in one direction. For example:
- to protect a circuit from a battery being installed in reverse.
- to form a full-bridge rectifier circuit (using 4 diodes) to convert AC power to D.C.


text:
Q: How can I digitize the vector figure? Consider the following figure in .pdf format. Its .png version is below:

I would like to digitize it, i.e., e.g., extract the data for the brown curve $a\to KK\pi$. How can I do this, using the fact the vector origin of the figure?

A: This answer seems to be version-dependent. It was created with
$Version

13.2.0 for Microsoft Windows (64-bit) (November 18, 2022)

Okay, let's do this.
We start off by loading the file into Mathematica while specifying that we want the graphics primitives:
imp = First@Import["a_rate.pdf", "PageGraphics"];

We notice that the graphics is mainly filled with joined curves which represents the lines. So we select them and plot this:
coordsLines = Cases[imp, _JoinedCurve, {0, Infinity}];
Graphics[coordsLines]

Okay cool, our sought-for line is there. Let's filter the selection down a bit.
We bet that our wanted line has a lot of coordinates. Let's say, more than 100:
coordsLineSelected = Select[coordsLines, Length[#[[1, 1]]] > 100 &];
Graphics[coordsLineSelected]

We're getting there.
It's just 21 lines left. Let's just select them by brute force looking:
Table[Graphics[{LightGray}~Join~coordsLineSelected[[;; (i - 1)]]~Join~
   coordsLineSelected[[(i + 1) ;;]]~
   Join~{Red, coordsLineSelected[[i]],
    Text[ToString[i], {0, 0}]}], {i, 1, Length@coordsLineSelected}]

Line 18 is the right one, right?
So we have the coordinates. Unfortunately, they're in some coordinate system that we have to calibrate it against. However, we can extract the frame coordinates as well and thus get the minimum and maximum values of the respective components.
The x components are easy; they're linear. For y, we have to respect that it's a log-scale.
sLineCoordinates=First[coordsLineSelected[[18,2]]]; (*get the coordinates of our line*)

frameLines=First@Select[coordsLines,2<Length[#[[1,1]]]<5&]; (*get the frame lines*)
{{xmin,xmax},{ymin,ymax}}=MinMax/@Transpose[frameLines[[2,1]]]; (*extract its coordinates*)

(*calibrate*)
x=(sLineCoordinates[[All,1]]-xmin)/(xmax-xmin)*3;
y=10^((sLineCoordinates[[All,2]]-ymin)/(ymax-ymin)*10-3);

(*plot*)
final=Transpose[{x,y}];
ListLogPlot[final,Joined->True,PlotRange->{{0,3},{10^-3,10^7}}]

It should be about right.
In Total:
ListLogPlot[Table[
  currentCoords = First[coordsLineSelected[[i, 2]]];
  Transpose[{(currentCoords[[All, 1]] - xmin)/(xmax - xmin)*3,
    10^((currentCoords[[All, 2]] - ymin)/(ymax - ymin)*10 - 3)}]
  , {i, 1, Length@coordsLineSelected}]
 , Joined -> True, PlotRange -> {{0, 3}, {10^-3, 10^7}}]

Edit to address the question of searching for a specific color.
Funnily enough, this is as easy as the last steps.
We notice, that color in the primitives is always (at least in this specific plot) imparted by a Style call.
The structure seems to be always the same:
Style[{JoinedCurve[..]},style1,style2,...]
So, we rewrite our Cases call to incorporate this information
(and while we're at it, we convert the colors to RGB)
coloredElements=Cases[imp,
    Style[{curve_JoinedCurve,___},___,color_?ColorQ]:>{PadRight[ColorConvert[color,"RGB"],4,1],curve},
{0,Infinity}];

The PadRight is there to account for uniform transparency information so we always are presented with an {r,g,b,a} vector.
Now we define a color to search for
seekedForColor = Darker@Brown;

Now its just a matter of defining a distance-norm of the color of the line and the seeked for color. Sort this list and plot it:
colorSortedLines = SortBy[
   {
      #1, #2,
      Norm[
       (List @@ #1) - (PadRight[
          List @@ ColorConvert[seekedForColor, "RGB"], 4, 1])
       ]
      } & @@@ coloredElements,
   Last];

Graphics[{#1, #2}, PlotLabel -> #1] & @@@ colorSortedLines

The first two lines describe the lines we want to have (they're the same color and the first is the negative infinity stretching extensions of the second data line).
We successfully selected the right lines by color.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Erlang: Connect to API with sockets/gen_tcp I am new to erlang and programming overall and I am looking for a way to connect to the twitter API by using sockets if there even is a way.
So what I am wondering is, is there anyway to pass http requests/URL in sockets to do so?
I would love any information to read or look at.
Example code where I can see gen_tcp, socket, ssl or whatever you think is the smartest way to go.
(Of connecting to twitter/sending request).
I do not wish to use another built library unless I really need to.
Thanks in advance,
Erlach

A: It sounds like you need HTTP client library. I do not see any reasons to implement HTTP protocol by your own over TCP-sockets and gen_tcp. Erlang standard library already contains one called httpc.
Also there is plenty of third-party http clients for general purposes:

*

*lhttpc

*ibroswe

*hackney
For interaction with API I'd recommend you to take a look at gun. As project page says, it follows next goals:

Gun aims to provide an easy to use client compatible with HTTP, SPDY
  and Websocket.
Gun is always connected. It will maintain a permanent connection to
  the server, reopening it as soon as the server closes it, saving time
  for the requests that come in.
All connections are supervised automatically, allowing the developer
  to focus on writing his code without worrying.

If you need more general information about gen_tcp module and network interaction at all, I'd recommend you to start from this great book.
UPD:
More specifically on twitter streaming API (do you mean this one?). To read streaming data you can use streaming interface of http client:
ok = application:start(inets).
{ok, Ref} = httpc:request(get, {RequestURL, RequestHeaders}, [], [{sync, false}, {stream, self}]).

After that you will receive following messages into process mailbox:

*

*First message will be {http, {Ref, stream_start, ResponseHeaders}}.

*Next messages will be {http, {Ref, stream, ResponseBodyChunk}}.

*Last message will be {http, {Ref, stream_end, ResponseHeaders}}.

After you've started such stream, you should just receive incomming messages via receive and handle it according to twitter streaming protocol.
Please, refer to documentation about httpc library. You really shouldn't use gen_tcp sockets here at all.


text:
Q: LINQ, "Argument types do not match" error, what does it mean, how do I address it? I'm new to linq and I'm trying to databind to an anonymous type.
I'm using SubSonic 3.0 as my DAL.
I'm doing a select from 2 tables like so
        var myDeal = (from u in db.Users
                  select new
                      {
                          UserID = u.UserID,
                          UserRoleID = (from ur in u.UserRoles where u.UserRoleID == ur.UserRoleID select ur).FirstOrDefault().UserRoleID
                      });
    foreach (var v in myDeal) //dies first time here
    {
    }

Then when I databind or try to iterate through the collection I get the "Argument types do not match" error during run time.
I'm not sure what is going on here.

A: Is one of the ID fields nullable?
If so, you need to access the .Value property
var myDeal = (from u in db.Users
        join ur in
              select new
                   {
                     UserID = u.UserID,
                     UserRoleID = (from ur in u.UserRoles where u.UserRoleID.Value equals ur.UserRoleID select ur).FirstOrDefault().UserRoleID
                    });

You could also try something like this:
var myDeal = (from u in db.Users
         join ur in db.UserRoles
        on new {ID = u.UserRoleID.value} equals new {ID = ur.UserRoleID} into tempRoles
        from roles in tempRoles.DefaultIfEmpty()
        select new
        {
           UserID = u.UserID,
                 UserRoleID = roles.UserRoleID
        });

You use tempRoles to execute a left outer join. So if there is no role assigned, you still get the userID.
I haven't tested this, this is just off the top of my head.
Good Luck,
Patrick.

A: "Argument types do not match" error is usually caused by the un-matching type between the property we would like to bind and its element.
Example in RadGridSparkline, when we would like to bind its item source

"Value" type must be double.
If we have the Value property defines as below
public decimal ContractValue
{ set; get; }
This error will be displayed


text:
Q: Can't seem to use PHP Namespaces correctly I am trying to setup my autoloader as suggested by the top comment in the official PHP documentation
My test environment follows.
C:\www\autoload.php (setup as advised in top comment)
<?php

spl_autoload_extensions(".php");
spl_autoload_register();

C:\www\Car\Bmw.php
<?php
namespace Car\Bmw;

class Bmw { var $v = 'Hello I am Class : Bmw'; }

C:\www\Bike\Suzuki.php
<?php
namespace Bike\Suzuki;

class Suzuki { var $v = 'Hello I am Class : Suzuki'; }

C:\www\index.php
<?php
use Car\Bmw;

include 'autoload.php';

$Obj = new Bmw();
var_dump($Obj);

I have tried some variations such as

*

*Defining include path in autoloader with set_include_path('C:\www\');

*Removing Bmw/Suzuki string from namespace/use or applying in one and not the other

Throughout these trials I have gotten numerous errors such as
Fatal error: Namespace declaration statement has to be the very first statement in the script in C:\www\Car\Bmw.php on line 3

or
Fatal error: spl_autoload(): Class Car\Bmw could not be loaded in C:\www\index.php on line 8

If you are wondering why I want to use this setup please visit the link I gave earlier and read the top comment : Linked again here
Thanks in advance.

A: You're creating these two classes:

*

*Car\Bmw\Bmw

*Bike\Suzuki\Suzuki
You'll need to modify your namespace declarations to be simply Car and Bike like this:
<?php

namespace Car;

class Bmw { /* */ }


text:
Q: CISC and VLIW, and instruction and opcode From http://en.wikipedia.org/wiki/Instruction_set

CISC processors include "complex" instructions in their instruction set. A single "complex" instruction does something that may take many instructions on other computers. Such instructions are typified by instructions that take multiple steps, control multiple functional units, or otherwise appear on a larger scale than the bulk of simple instructions implemented by the given processor.
...
In very long instruction word (VLIW) architectures,  which include many microcode architectures, a single instruction includes multiple simultaneous opcodes and their operands.

CISC and VLIW seem to me the same concept, in that an instruction includes multiple operations (i.e. opcodes). So are they the same concept?
How do you define a single operation (i.e. opcode) is, when telling if an instruction has multiple operation (i.e. opcodes)?

A: Modern CISC processors have multiple execution units. They also have a lot of extra circuitry and logic to try and distribute the instruction stream amongst those execution units.
VLIW is an attempt to have the compiler do some of this work and use the saved circuity for even more execution units, cache or other resources.
An example would be Itanium in which instruction words are 128bits and contain three instructions. This lets the compiler do some of the work in pairing up instructions to execute together.

A: An instruction is a single order that must be done logically before the next one. If an instruction contains more than one operation, such as in a VLIW instruction, these are meant to be done at the same time. And in a VLIW instruction each operation slot corresponds to a hardware processing unit (a combination of a FPU and an ALU) these are statically assigned by the instruction. Where as in a CISC or RISC the processor may choose any free processing unit. But as the units are assigned in the instruction with VLIW, you can't run code for one VLIW on another model with greater or fewer processing units as the instructions for that would have more or less slots in their instructions, although some greater ones might allow running code that uses a format which has fewer slots, unlike in a CISC or RISC where the code can automatically use additional processing units, the VLIW code can't use the extra processing units without being recomplied specifically for the processor.
That limitation with VLIW is what prompted Explicit Data Graph Execution (EDGE).

A:
How do you define a single operation (i.e. opcode) is, when telling if an instruction has multiple operation (i.e. opcodes)?

The definitions and your expectations are not quite correct. "Opcode" is used for indicating visible instructions, not hidden operations like micro-ops, and "instruction" should only refer to user-exposed operations. An "operation" does not corresponds to an opcode and may be simple (a single opcode) or complex (multiple opcodes) depending on how you refer to it, like if you want to address the whole operation itself, or address each lower level operation used to achieved that big thing. It's just like when you do a division, it can be called a single operation. But division can also be subdivided into a series of subtractions/multiplications, i.e. multiple operations (stages in hardware term). Many old RISC architectures have separate instructions for various stages of a division to keep the instructions simple and make pipelining straightforward. But modern RISC architectures typically don't do that and can have very complex instructions like CISC, for example rlwinm in PowerPC or ldm/stm in ARM.
In VLIW architectures, a single instruction is still 1 instruction. However, instructions will be grouped together as a batch. For example, a batch in Itanium architecture contains 3 instructions that will be run at the same time. Of course each instruction must have its own opcode, and those opcodes are available to the programmer to use. Moreover those instructions are independent of the others, unlike micro-ops which jointly represents an operation of some higher level instruction. For example in some architecture you may have 2 additions along with a multiplication and a bitwise xor of different things in a batch that doesn't relate to each other.
On the contrary, a CISC instruction is only one instruction that does a single operation, and has one opcode. Prior generations of CISC CPUs execute each instruction directly, so it's really a single unbreakable instruction. However in modern processors, complex "operations" will be divided into multiple simpler micro-operations that can be done in shorter clock cycles. Those micro-ops are not visible to outsiders, so you can't call them multiple opcodes. To users, it's still a single instruction. You will probably never know which micro-ops Intel or AMD is using under the hood. Besides a CISC instruction can be broken into a single micro-op or multiple ones, so it's completely wrong to say CISC includes multiple operations in a single instruction.
In fact modern RISC architectures also break instructions into micro-ops just like CISC, and very simple operations are also combined together into a macro-op that's also not user-visible, for example CMP/Jcc in x86 or DIV/REM in RISC-V and you won't say that RISC is simple. A RISC instruction can still do multiple operations.
CISC and VLIW, one has a single instruction with a single opcode running at a time (barring superscalar and out-of-order execution for now), one executes multiple instructions at a time, so how are they the same concept? You should view on top of the instruction set or at least the same level. Comparing a thing used internally in a CPU with a thing on the instruction set above the CPU is meaningless.


text:
Q: Is it possible to show our custom message in QGIS Status bar using python? Is there any way to show our custom message in Qgis Status bar using python? Just like in arcgis IApplication.statusbar.message(0) = "Please wait..."
like that is there any option to show progressbar in Qgis like IApplication.progressbar.show()

A:
StatusBar
There is iface.mainWindow().statusBar() which returns a QStatusBar
iface.mainWindow().statusBar().showMessage( u"Hello World" )

MessageBar
Starting from QGIS 2.0 there is also QgsMessageBar which is able to display unobtrusive messages
iface.messageBar().pushInfo(u'My Plugin says', u'Hey there')

Advanced
The message bar can also show any QWidget (like a QProgressBar) with a close button and a timeout (5 seconds in the example).
from PyQt4.QtGui import QProgressBar
from qgis.gui import QgsMessageBar
msgBar = iface.messageBar()

pb = QProgressBar( msgBar )
msgBar.pushWidget( pb, QgsMessageBar.INFO, 5 )

msg = msgBar.createMessage( u'Hello World' )
msgBar.pushWidget( msg, QgsMessageBar.WARNING, 5 )

More info about QgsMessageBar can be found in this answer by NathanW How to address the new "Task-Completed" QgsMessageBar in Python?
Thanks for pointing out Curlew
Legacy
In the python console for QGIS < 1.9 it would be:
qgis.utils.iface.mainWindow().statusBar().showMessage( u"Hello World" )


text: Q: How to isolate critical CSS when using Create React App What is the best way to address render blocking CSS and only loading critical CSS with Create React App since there is no access to edit the webpack config file?


text:
Q: What version of Perl is shipped with the Desktop Version of 11.10? Kindly let me know if Perl Version 5.12.4 is included in the desktop version of Ubuntu 11.10 or does it have to be seperately downloaded? I have been to packages.ubuntu.com and found that Perl Version 5.12.4 is available on Ubuntu, but is that the server version or desktop version?
Or does it mean that the package is available, but I have to download it seperately? Kindly let me know. I will be using Ubuntu mainly as my personal desktop system as well as doing some scripting on Perl and Python.

A: Yes, 11.10 Oneiric comes with Perl 5.12.4, as you can see here.

A: You are quite correct - 5.12.4 is installed in oneiric (11.10) as per
perl -v

This is perl 5, version 12, subversion 4 (v5.12.4) built for i686-linux-gnu-thread-multi-64int
(with 45 registered patches, see perl -V for more detail)

It is automatically installed with an installation of ubuntu.

A: FWIW, there is a plugin for firefox that allows you to search ubuntu packages
https://addons.mozilla.org/en-US/firefox/addon/search-ubuntu-packages/


text:
Q: Checking if the correct array length was malloced in C I am grading a bunch of student assignments.
They are designing their own dynamic array data type. I am looking for a good way to test to make sure that they malloc the correct amount of memory for an array when re-sizing.
Other than inspecting the code is there some way to easily test the amount of memory created by a malloc call? They are supposed to keep track of the capacity but I need to test that they are doing so correctly.
I would also like it if the test didn't end in a segfault if they did not allocate enough memory so that I could continue running other tests.
Thanks!

A: You can provide your own version of malloc(), calloc(), realloc(), and free() for your tests by re-defining the standard function names.
With gcc, I'd create an object file with the replacement functions
gcc -c myfunctions.c -omyfunctions.o

and compile the test files with a redefiniton and link to the replacement
gcc myfunctions.o -Dmalloc=mymalloc -Dcalloc=mycalloc -Drealloc=myrealloc -Dfree=myfree testfile.c

instead of what the students use
gcc testfile.c

The implementation of the my*() functions shouldn't be too difficult. Basically they check the parameters and call the original functions.
/* myfunctions.c */
#include <stdlib.h>
void *mymalloc(size_t s) {
    /* test s */
    return malloc(s);
}
void *mycalloc(size_t n, size_t s) {
    /* test n and s */
    return calloc(n, s);
}
void *myrealloc(void *p, size_t s) {
    /* test p and s */
    return realloc(p, s);
}
void myfree(void *p) {
    /* test p */
    free(p);
}

A: I think the problems you are expecting should be caught by running the students' programs in Valgrind. That's a good idea anyway as it might also catch other unwanted issues, e.g. out-of-bounds accesses.


text:
Q: android wifi network latency galaxy s2 i am trying to estimate network delay between two android devices connected over WiFi to synchronize clocks. but the network delay is varying a lot from 2ms to 1024ms. sometimes i gets delay value which varies between 2-10ms for continuous 100 readings. but sometimes values ranges between 2ms to 1024ms for continuous 100 readings like 2, 100, 570, 640, 2, 5, 150.
I am using socket timestamps to determine the exact receive and send time of the packet. my setup uses one laptop as wifi access point and two mobile phones. There is not much load on the network. my question is why is it varies less sometime and why it varies so much sometimes.
How to make it vary less. am i missing any configuration on android. Give me some possible reasons for this kind of behavior...

A: Unlike wired links, wireless links are affected from a lot of different factors. You can get stable results only in a sterile environment without electromagnetic or mechanical interferences.
Most latency fluctuations are a direct result of RF collisions. WiFi networks implement the CSMA/CA protocol to deal with the collisions. In general it detects whether there is any activity in the air and postpones the transmission if it's noisy.
You can try to minimize the external influences but still this doesn't guarantee anything:

*

*Perform WiFi scan and see what channels are the noisiest. Choose the less occupied for our link. Remember, there are overlaps between various channels, so moving to a different channel won't necessary remove all the noises. See here about channels overlapping and how to choose a channel: http://en.wikipedia.org/wiki/List_of_WLAN_channels .

*Remove mechanical obstacles from your environment.

*Increase the transmission (Tx) power of your devices from their SW configuration.

*Check the Quality of Service (QoS) configuration of your devices, some tweaking there might yield improvements.

A: Solved this problem by using WIFI_MODE_FULL_HIGH_PERF.
After acquiring this lock, i have observed constant network delays.
http://developer.android.com/reference/android/net/wifi/WifiManager.html#WIFI_MODE_FULL_HIGH_PERF


text:
Q: Android: AsyncTask UI update issue In the code below, I'm trying to create a ListActivity.
The elements of this list are being filled by a custom ArrayAdapter - OrderAdapter.
All the element fetching mechanism is inside the AsyncTask class.
I'm able toset the elements in the m_adapter, but not able to update the UI of List.
The activity is getting force closed.
Code:
public class SoftwarePassionView extends ListActivity {

    private ProgressDialog m_progressDialog = null;
    private ArrayList<Order> m_orders = null;
    private OrderAdapter m_adapter; // Defined Below
    private Runnable viewOrders;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.softwarepassionview);
            m_adapter = new OrderAdapter(SoftwarePassionView.this,
                    R.layout.row, m_orders);

            new AsyncOperation().execute();

        } catch (Exception e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
        }
    }

    public class OrderAdapter extends ArrayAdapter<Order> {

        private ArrayList<Order> items;

        public OrderAdapter(Context context, int textViewResourceId,
                ArrayList<Order> elements) {
            super(context, textViewResourceId, elements);
            this.items = elements;
        }

        public void setList(ArrayList<Order> items) {
            this.items = new ArrayList<Order>();
            this.items.addAll(items);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            super.getView(position, convertView, parent);
            View v = convertView;
            try {
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.row, null);
                }
                Order o = items.get(position);
                if (o != null) {
                    TextView orderName = (TextView) v
                            .findViewById(R.id.topText);
                    TextView orderStatus = (TextView) v
                            .findViewById(R.id.bottomText);
                    orderName.setText(o.getOrderName());
                    orderStatus.setText(o.getOrderStatus());
                }
            } catch (Exception e) {
                Toast.makeText(SoftwarePassionView.this, e.toString(),
                        Toast.LENGTH_SHORT).show();
            }
            return v;
        }
    }

    public class AsyncOperation extends AsyncTask {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object... params) {
            getOrders();
            if (m_orders != null && m_orders.size() > 0) {
                m_adapter.setList(m_orders);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            m_adapter.notifyDataSetChanged();
            setListAdapter(m_adapter);
        }
    }

    private void getOrders() {
        try {
            m_orders = new ArrayList<Order>();
            Order o1 = new Order();
            o1.setOrderName("T-Shirt Purchase");
            o1.setOrderStatus("Dispatched");
            Order o2 = new Order();
            o2.setOrderName("Deo Purchase");
            o2.setOrderStatus("Pending");
            m_orders.add(o1);
            m_orders.add(o2);

            Thread.sleep(2000);
        } catch (Exception e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
        }
    }

}

A: I have fix error try now
public class SoftwarePassionView extends ListActivity {

private ProgressDialog m_progressDialog = null;
private ArrayList<Order> m_orders = new ArrayList<Order>(); //why you have putting it null?
private OrderAdapter m_adapter; // Defined Below
private Runnable viewOrders;

@Override
protected void onCreate(Bundle savedInstanceState) {
    try {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.softwarepassionview);
        m_adapter = new OrderAdapter(SoftwarePassionView.this,
                R.layout.row, m_orders);
        setListAdapter(m_adapter); // you are getting npe as you have not init "m_orders"
        new AsyncOperation().execute();

    } catch (Exception e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }
}

public class OrderAdapter extends BaseAdapter {

    private ArrayList<Order> items=new ArrayList<Order>();

    public OrderAdapter(Context context, int textViewResourceId,
            ArrayList<Order> elements) {
        //super(context, textViewResourceId, elements);
        this.items = elements;
    }

    public void setList(ArrayList<Order> items) {
        this.items.clear();
        this.items.addAll(items);
        this.notifyDataSetChanged();

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        super.getView(position, convertView, parent);
        View v = convertView;
        try {
            if (v == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.row, null);
            }
            Order o = items.get(position);
            if (o != null) {
                TextView orderName = (TextView) v
                        .findViewById(R.id.topText);
                TextView orderStatus = (TextView) v
                        .findViewById(R.id.bottomText);
                orderName.setText(o.getOrderName());
                orderStatus.setText(o.getOrderStatus());
            }
        } catch (Exception e) {
            Toast.makeText(SoftwarePassionView.this, e.toString(),
                    Toast.LENGTH_SHORT).show();
        }
        return v;
    }

public int getCount() {

    return this.items.size();
}

public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return this.items.get(arg0);
}

public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return 0;
}

}

public class AsyncOperation extends AsyncTask {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Object doInBackground(Object... params) {
        getOrders();
       // if (m_orders != null && m_orders.size() > 0) {  NO nead to set list here
       //     m_adapter.setList(m_orders);
       // }
        return null;
    }

    @Override
    protected void onPostExecute(Object result) {

        if (m_orders != null && m_orders.size() > 0) {
            m_adapter.setList(m_orders);
        }
         super.onPostExecute(result);
        //setListAdapter(m_adapter);
    }
}

private void getOrders() {
    try {
        m_orders = new ArrayList<Order>();
        Order o1 = new Order();
        o1.setOrderName("T-Shirt Purchase");
        o1.setOrderStatus("Dispatched");
        Order o2 = new Order();
        o2.setOrderName("Deo Purchase");
        o2.setOrderStatus("Pending");
        m_orders.add(o1);
        m_orders.add(o2);

        Thread.sleep(2000);
    } catch (Exception e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }
}

}

A: check this post, the problem is almost same.
I think as items has same refreance ( as passed from activity to adapter ) so items (on adapter and on activity are pointing to same ArrayLists) so both are get-clear so these line not make sense as both are empty
Try something like this:
public class OrderAdapter extends ArrayAdapter<Order> {
        // private ArrayList<Order> items;
        private ArrayList<Order> items = new ArrayList<Order>();

        public OrderAdapter(Context context, int textViewResourceId,
                ArrayList<Order> elements) {
            super(context, textViewResourceId, elements);
            this.items = elements;
        }

        public void setList(ArrayList<Order> items) {
        this.items.addAll(items);

        }

and:
@Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            //m_adapter.notifyDataSetChanged();
            // setListAdapter(m_adapter);
            m_adapter.notifyDataSetChanged();
        }

and use setListAdapter(m_adapter); after creating the m_adapter


text:
Q: Library to convert JSON to urlencoded We are doing some integration towards a quite inconsistent (Zurmo-)REST API. The API only accepts urlencoded strings as its payload in the http posts, but it answers with JSON.
So as the documentation was very unclear on this we naturally thought we could post JSON to it, but this was not the case.
So now we have all our code generating JSON when we need to send it as x-www-form-urlencoded, is there any java library that can do a conversion from JSON to an urlencoded string?
We are currently using the org.json lib, but we can change it if there would be a need for it.
Example:
This JSON string:
{"data":{"description":"test","occurredOnDateTime":"2013-10-24 01:44:50"}}

Should be converted into this:
data%5Bdescription%5D=test&data%5BoccurredOnDateTime%5D=2013-10-24+01%3A44%3A50

Java code:
We translated rasmushaglunds javascript code to java and wrapped it, here is the result if anybody else stumbles upon this problem.
public static String jsonToURLEncoding(JSONObject json) {
    String output = "";
    String[] keys = JSONObject.getNames(json);
    for (String currKey : keys)
        output += jsonToURLEncodingAux(json.get(currKey), currKey);

    return output.substring(0, output.length()-1);
}

private static String jsonToURLEncodingAux(Object json, String prefix) {
    String output = "";
    if (json instanceof JSONObject) {
        JSONObject obj = (JSONObject)json;
        String[] keys = JSONObject.getNames(obj);
        for (String currKey : keys) {
            String subPrefix = prefix + "[" + currKey + "]";
            output += jsonToURLEncodingAux(obj.get(currKey), subPrefix);
        }
    } else if (json instanceof JSONArray) {
        JSONArray jsonArr = (JSONArray) json;
        int arrLen = jsonArr.length();

        for (int i = 0; i < arrLen; i++) {
            String subPrefix = prefix + "[" + i + "]";
            Object child = jsonArr.get(i);
            output += jsonToURLEncodingAux(child, subPrefix);
        }
    } else {
        output = prefix + "=" + json.toString() + "&";
    }

    return output;
}

A: public static String objectToUrlEncodedString(Object object, Gson gson) {
    return jsonToUrlEncodedString((JsonObject) new JsonParser().parse(gson.toJson(object)));
}

private static String jsonToUrlEncodedString(JsonObject jsonObject) {
    return jsonToUrlEncodedString(jsonObject, "");
}

private static String jsonToUrlEncodedString(JsonObject jsonObject, String prefix) {
    String urlString = "";
    for (Map.Entry<String, JsonElement> item : jsonObject.entrySet()) {
        if (item.getValue() != null && item.getValue().isJsonObject()) {
            urlString += jsonToUrlEncodedString(
                    item.getValue().getAsJsonObject(),
                    prefix.isEmpty() ? item.getKey() : prefix + "[" + item.getKey() + "]"
            );
        } else {
            urlString += prefix.isEmpty() ?
                    item.getKey() + "=" + item.getValue().getAsString() + "&" :
                    prefix + "[" + item.getKey() + "]=" + item.getValue().getAsString() + "&";
        }
    }
    return urlString;
}

A: As noted below, it's not a Java library but you should be able to translate it :)
Here's how you could do it in javascript:
var jsonArrayToUrl = function (obj, prefix) {
  var urlString = "";
  for (var key in obj) {
    if (obj[key] !== null && typeof obj[key] == "object") {
      prefix += "[" + key + "]";
      urlString += jsonArrayToUrl(obj[key], prefix);
    }else{
      urlString += prefix + "[" + key + "]=" + obj[key] + "&";
    }
  }
  return encodeURIComponent(urlString);
};

Then call it with
jsonArrayToUrl(test["data"], "data");

By the example string you gave above it returns
"data%5Bdescription%5D%3Dtest%26data%5BoccurredOnDateTime%5D%3D2013-10-24%2001%3A44%3A50%26"

It should work recursively on nested arrays. You might also consider writing a wrapper for the function so that you only need one argument.

A: There is an easier way now, and that is to use the URLEncoder.encode method.
Import the URLEncoder package:
import java.net.URLEncoder;

and then:
URLEncoder.encode(objectMapper.writeValueAsString(<yourClass>), StandardCharsets.UTF_8.toString());

You can test your result here:
https://onlinejsontools.com/url-decode-json


text:
Q: Hash with 'nil' value when using `group` and `count` in query In Rails, I get a hash using includes:
<% @teste = UserProfile.includes(:mobile_models).group(:name).count  %>

The problem is that includes generates a hash like the following:
{nil=>4774, "2610"=>7, "2626"=>4, "2630"=>5, "2760"=>4, "3250"=>3, "355"=>5, "3I607 BlackJack"=>5, "5230"=>13, "5235"=>4, "5310"=>5, "5500"=>5, "5800 Xpress Music"=>16, "6020"=>4, "6120c"=>4, "6131"=>4, "7210"=>5, "A1200r"=>5, "A1900"=>5, "AIKO 70"=>5, "B3410W Ch@t"=>4, "beTouch E100"=>4, "BlackBerry 8320 (Curve)"=>10,....

In my database, I don't find any mobile record with the name "nil". Checking my database, I can't find what might be producing this nil.
The other goal is to sum all values, like this:
 <%= sum = @teste.values.sum %>

But when I do this, the 'nil' is added too.
---Update
models/UserProfile
class UserProfile < ActiveRecord::Base
  has_and_belongs_to_many :mobile_models, join_table: 'user_profiles_mobile_models', order: 'name'

models/MobileModel
class MobileModel < ActiveRecord::Base
  belongs_to :mobile_maker

A: Because you are grouping by :name, some of the MobileModel or UserProfile objects have the name attribute set to nil. You will need to check both as without seeing the model definition, I can't tell which model has the :name property you are grouping on. If you can share the model code, I can be more explicit.
If both models have a name attribute, you can be more explicit in your group statement:
UserProfile.includes(:mobile_models).group('mobile_models.name')

or...
UserProfile.includes(:mobile_models).group('user_profiles.name')

Also, if a number of your users do not have any mobile_models to include, I believe they will get dumped into the nil grouping as well.

A: You are getting that hash because of group(:name).
That means you have 4774 records who's name is nil.


text:
Q: explicitly lay out UI I'm finding the need to lay out a fairly complex UI manually, by giving the dimensions and position of most all of the sub views.  My plan is to code the XML initially for a 480x320 display, get it all working right to demo for the client on a given device, then modify it for production by programmatically adjusting the size and position of the views to adapt it to whatever screen size it's running on.
First...I know this is not the recommended approach.  I have spent forever trying to get the automated layouts to work right (along with animations).  Honestly I don't think they were made for the way the client wants this, and I just don't have any more time to mess around with it. (nor to learn to make a flexible custom layout)
Given that, where should I do the measuring/positioning?  I can do onMeasure() to set the sizes (ignoring the incoming parameters and basing them instead on my knowledge of the screen resolution which is measure when the Activity starts), but where do I set the position of each the view?  In onLayout()?  Assume all views will be subclasses anyway (as opposed to using components out of the box)
Ideally, I'd like to have one place where I measure the screen res, then grab each view and set its x, y, width and height.  Is that possible?  If so how?
Edit: now offering a bounty.  Note that I also did a sketch of one simple problem I'm trying to solve -- http://karmalita.com/stuff/layout.png -- which if you can do it the "correct" way (say, using a relative layout), the bounty is yours.

A: From your diagram, the basic structure could be something like the following.  Not generally you wouldn't specify absolute values like "50dp" for layout widths and heights, instead relying on the views to report their desired size.  For example, if your top bar is a 9-patch border with text inside, you could just make this a TextView where you specify the text and set the 9-patch with android:background="@drawable/...", and let the text view compute its appropriate width and height based on the text size and padding of the 9-patch.  (And than use match_parent to ignore that size and allow it to stretch to fill its parent, or wrap_content to use its desired size.)
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
  <View
      android:layout_width="match_parent"
      android:layout_height="50dp" />
  <View
      android:layout_width="match_parent"
      android:layout_height="0px"
      android:layout_weight="1" />
  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal">
      <View
          android:layout_width="??dp"
          android:layout_height="55dp" />
      ...
  </LinearLayout>
  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal">
      <View
          android:layout_width="??dp"
          android:layout_height="60dp" />
      ...
  </LinearLayout>
</LinearLayout>

A: As Falmarri pointed out, don't create it just for 480x320 but make it sizable from the start.
Can you give some details about the UI? A sketch maybe? Using a combination of layouts it should be possible, even if it's complex.


text:
Q: store UIFont as NSDictionary? I want to create a UIFont object based on a dictionary store in a plist file.
Obviously I could create my own keys and use them to put the font name, family name, and point size, then use that to create the font.
But is there a standard way to do it?

A: I'm not sure what you mean by "standard" here. There is no "standard" API to encode a UIFont as an NSDictionary. I'd suggest you create your own category methods for UIFont. One that returns a UIFont instance as a dictionary and another (class method) that creates a UIFont instance from such a dictionary.


text:
Q: Prepare dependency property for invalid value I have created UserControl that provides few dependency properties. The value of one of them is int. Now the user has provided the null as value and an exception has been thrown:
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='<null>' ...
Which is a valid behaviour (by WPF I believe?). However I want to prepare my UserControl for such incident. I mean, if binding provides invalid value I want to catch this and provide my default value, so no exceptin is thrown.
How to achieve this? I've tried with DependencyPropertyChangedCallback, CoerceValueCallback and ValidateValueCallback callbacks but it seems none of them receive this value.

A: You can't set an int property to anything else than an int value so your dependency property in the UserControl is actually never being called and there is nothing that the UserControl can do about this as the property never gets set.
It is the responsibility of the consumer of any class including a UserControl to be able to set a property to a value of the property type.
In this case the error occurs when when the WPF runtime is trying to set your int property to a value that doesn't represent a valid integer, such as for example null.
What you could do is to use a ValidationRule to do something before the value conversion occurs and present an error message to the user if the conversion fails:
How do I handle DependencyProperty overflow situations?
Another option may be to change the type of the dependency property to Nullable<int> (int?). Then you will be able to set it to any valid integer value as well as null.

A: In your binding where you bind to that DependencyProperty u can set NullValue and FallbackValue.
Somethinkg like.
 <TextBlock  Text="{Binding SomeProperty, FallbackValue='Null not suported', TargetNullValue={x:Null}}"/>


text:
Q: How to build rs fie in AndroidStudio I am using AndroidStudio. I want to develop with RenderScript, when I create a file hello.rs and build the project,then I try to use ScriptC_hello in java file,but the compiler cannot
find ScriptC_hello class,I think ScriptC_hello.class did not create,but how to create it?

A: Make sure your .rs file is in the app/src/main/rs directory in your project.  Unlike Eclipse based projects, all your .rs files need to reside here by default rather than alongside the Java files from the same package.

A: Android Studio expects .rs files to be in app/src/main/rs, but you can also override the renderscript source directory in build.gradle.
// build.gradle

android {
    sourceSets {
        main {
            renderscript.srcDirs = ['src']
        }
    }
}


text:
Q: mysql stuck on error message for registerusers I'm having some problem with error message that won't disappear and here's my stored procedure of registerusers:
DELIMITER go Create procedure registerusers(
   Out UserID tinyint(11),
 IN iFirstName varchar(30),
  IN iLastName varchar(30),
  IN iPassword varchar(30),
  IN iEmailAddress varchar(30),
  IN iSalt varchar(40),
  IN iRoleID varchar(1))
 BEGIN

declare checkfirstnamecount int;
 select count(FirstName) into checkfirstnamecount from users where FirstName = iFirstName;

If(checkfirstnamecount!=1) then SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Fill out the First Name ';

else
     insert into users(      FirstName,  LastName ,  Password ,  EmailAddress ,  Salt ,  RoleID   ) Values ( iFirstName,  iLastName ,  iPassword ,  iEmailAddress ,  iSalt ,  iRoleID  ); set UserID = last_insert_id();    end if;

End go DELIMITER ;

when I used:
set @new_id = null;
call registerusers(@new_id,'Aaron','James','5566','aaron@gmail.com','sdfd','U');
select @new_id;

the error message I got was "
MySQL said: Documentation
#1644 - Fill out the First Name "

I was intending to pass all the parameters and expecting to work but it didn't. I also tried:
 set @new_id = null;
    call registerusers(@new_id,'','James','5566','aaron@gmail.com','sdfd','U');
    select @new_id;

the result is the same error message


text:
Q: Basic commands not working i.e: -bash: ls: No such file or directory I'm new to Unix and in the process of installing a program for my dissertation I must have played with the PATH for the basic Unix commands such as ls. Every time I type ls and the directory name I want to list the files for, it comes up as:
-bash: ls: No such file or directory

What can I do to fix this? Any help is very very much appreciated!

A: The changes you've made to PATH are likely temporary. Close the shell you're in with exit and reopen it.
In the event that you have edited a file that sets the PATH for newly opened shells, specify the full path to commands to fix whatever you've changed (eg. /usr/bin/vim).

A: Reset your path right now (i.e. before any sort of logout) with:
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

It doesn't get your full PATH restored but basic utilities will be available again.
Here's an example of the sort of thing that happens:
You had a PATH variable (referred to as $PATH when reading from it)
Something like:
$ echo $PATH
/home/durrantm/.rvm/gems/ruby-2.0.0-p247/bin:/home/durrantm/.rvm/gems/ruby-2.0.0-p247@global/bin:/home/durrantm/.rvm/rubies/ruby-2.0.0-p247/bin:/home/durrantm/.rvm/bin:/h
ome/durrantm/.autojump/bin:/usr/local/heroku/bin:/home/durrantm/bin:/home/durrantm/.autojump/bin:/usr/local/heroku/bin:/home/durrantm/.autojump/bin:/usr/local/heroku/bin:
/home/durrantm/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/durrantm/.rvm/bin:/home/durrantm/.rvm/bin:/home/durrantm
/.rvm/bin

You tried to add to it, but you accidentally used
PATH=PATH:other_dir

instead of
PATH=$PATH:other_dir

and the result was that your path became
PATH:other_dir

and then all the utilities like ls and sed don't work
You can fix the minimal set by doing
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

which is particularly useful if a login dot files is messing up your PATH
Check your .bashrc and/or .bash_profile files for any PATH changes.
As Greg says you can also just log out (or safer option, open a new window in case opening a new window is broken!) and then echo $PATH from a new window.
The same thing happens when you do path= with no values.  It 'wipes out' your current path and causes these problems.strong text
As for why, when you have these problems cd works and ls doesn't work:

*

*cd is a "built-in" command that doesn't need your PATH to find the program

*ls is a program and need to use PATH to find where it is.

You can see this with:
$ builtin ls
-bash: builtin: ls: not a shell builtin
14:47:29 mdurrant C02MH2DQFD58 /Users/mdurrant
$ builtin cd
14:47:31 mdurrant C02MH2DQFD58 /Users/mdurrant
$

No error means the command is a builtin
Before 'moving on' (or logging out)...
Make sure to test any changes (particularly those to .bashrc, .profile, etc that are doing PATH  setting commands) by opening a new window or doing source ~/.bash_profile to run it. It's also a good practice to keep the window and editor (when you are changing the .bash_profile file) open in case your changes don't work and prevent you from opening new windows to edit the file. Though you can still use TextEdit or another simple editor to change the file (avoiding command line and vi for example).  Be careful NOT to reboot if/when your shell is broken or you may not even be able to login. and that is really really bad (without another account to su from you are hosed). Has happened to me!
My 'extra account' fix was also a life saver then though and highly recommended for all (do it now!)

A: This answer is for those who logged out after editing the .bash_profile, which means you're probably in a situation where you can't use your login screen.
I can't ensure you this will work for you.
Short Answer
If, for some reason, you don't even have access to a shell,
switch to a virtual console with Ctrl+Alt+F2 and login.
Once you're at a shell prompt,
use command -p <insert_command_here> to edit the file in question,
where <insert_command_here> is something like nano .bash_profile.
Long Answer
I'm using Manjaro, but I doubt that means anything in this scenario.
I was in the login screen. I typed my credentials and then nothing happened. As nothing was working anymore, I had no prompt to work with. I could move my cursor just fine, but none of the login screen buttons worked.
I pressed Ctrl+Alt+F2. I now had a console terminal to work with. I could go back to the previous screen with Ctrl+Alt+F1, but that wasn't necessary.
I was met with a login prompt and filled in my credentials.
I tried using the commands am used to working with, but nothing worked. I'd get the default:
-bash: something_something: command not found.

But, I found that I COULD use cd, but I couldn't list directory contents with ls. I did some research and found out that cd is a built-in command. I wanted to confirm that I could work with built-in commands and found a way to display all of them:
compgen -b

I was now met with a lot of commands I could work with. I had no idea what most of them do. I could recognize commands such as source, cd, echo and exit. I couldn't find any good material explaining how to use these built-in commands. Maybe I just didn't search well enough. Anyway, since help is also a built-in command, I tried using it on some of the built-in commands. Eventually I did:
help command

one of the options was:

command -p
*
Use a default value for PATH
that is guaranteed to find all of the default utilities.

That sounded pretty useful, so I went ahead and tried to do:
command -p ls

And it worked. Now I figured that I just needed to edit the .bash_profile file and so I did:
cd ~
command -p nano .bash_profile

I then deleted the few lines I had added that had messed up my path. If you don't know which lines that is, then I suppose you'd be safe with some sort of default path. I can imagine that's a thing. If it wasn't .bash_profile that caused the issue for you, then I suppose you can try editing the file that did.
I then rebooted the system and everything was back to normal.

A: This happend to me when after i installed Andriod Stuido, and wrote the wrong path to SDK. Got multiple export error: not a valid identifier. And all commands did not work. I had to open bash_profile in Notepad (outside the terminal) and remove the wrong PATH.


text:
Q: Apoll server prop 'body' does not exist on type 'IncomingMessage' I am working on an apollo node server in typescript. After migrating to Apollo V4 every req.body i call returns the error " property 'body' does not exist on type 'IncomingMessage'"
small snippet of example code
context: async ({ req }) => {
    let storedContent = {
      uid: "",
      originalAccess: "",
      originalRefresh: "",
      NewAccess: "",
      NewRefresh: "",
    };
    try {
      //Catch uid from playgorund headers and log path
      if (req.headers.uid) req.body["uid"] = req.headers.uid;

      console.log("UID", req.body.uid);


text:
Q: AutoHotKey Send Hotkey key I'm trying to make a hotkey that sets the value of a variable and presses itself.
Hotkey, %UserBuild1% , Build1
Build1:
    HotbarStatus := UserBuild1
    send {%UserBuild1%}
return

I've tried putting a $ sign in front like you do with $9:: for example but that dosen't work.

A: this work for me.
;Define your hotkey - Example: Control + Alt + m
UserBuild1 = ^!m

Hotkey %UserBuild1% , Build1
Return ;don't forget or Build1 will be executed on start

Build1:
    HotbarStatus := UserBuild1
    send %UserBuild1%
    MsgBox %HotbarStatus% ;just for debugging purposes...
return


text:
Q: Error parser python read csv data using numpy I have this kind of error in jupyter notebook, is there something needs to be done?

ParserError                               Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_15164\57077545.py in
----> 1 pd.read_csv('datawisata.csv', skip_blank_lines=False)
apparently i have blank data from my travel.csv.

ParserError: Error tokenizing data. C error: Expected 1 fields in line 54, saw 2
any suggestions how to parse it ??
or maybe it can't be done so i need to change it into 'blank' words first?

A: first thing this is pandas not numpy :p
second, you can keep blanck cells in pandas as empty string with the parameter keep_default_na=False as you can see in this answer here
you can do similarly in numpy as answere here


text:
Q: How to make double underscore display as two separate underscores in Pycharm? I don't know how to make a double underscore, i.e. a dunder, display as two single underscores in Python in PyCharm.
I have disabled font ligatures in
Editor -> Font,

Editor -> Color Scheme -> Color Scheme Font,

Editor -> Color Scheme -> Console Font

For all three of these, I use Consolas.
Basically, I want to achieve something like this:
 _ _class_ _ (without the spaces, of course).

What I have right now is this:
__class__.
I was expecting this to be easy, but I can't seem to find a straightforward answer to my question online.

A: You can install a theme called predawn. The format of its font shows dunder separated from each other like:


text:
Q: Don't know how to set a Boolean workitem field in Azure DevOps Server to display Yes/No instead of True/False I'm running Azure DevOps Server 2019 and I added a Boolean field to my User Story work item. The description for Boolean fields says "Boolean: Adds a True/False or Yes/No field.". It defaults to displaying a True/False toggle. I can't find how to change it to display a Yes/No toggle instead.

A: Sorry for confusion. The value "Yes/No" is actually not supported for a Boolean field type by default. An a workaround, you can use String type instead of Boolean type, which render a dropdown box for Yes/No:
<FieldDefinition name="MyField" refname="My.Field" type="String">
  <ALLOWEDVALUES expanditems="true">
    <LISTITEM value="Yes" />
    <LISTITEM value="No" />
  </ALLOWEDVALUES>
</FieldDefinition>


text:
Q: IO Exception while connecting to the url at the connect() While running an App to check the json string, I have the following Async Task.It gives an IO Exception when it reaches the "urlconnection.connect()". The Logcat just displays this Exception without any more explanation.Please help me where I am going wrong.
public class FetchWeatherTask extends AsyncTask<Void,Void,Void>
{

    private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        // Will contain the raw JSON response as a string.
        String forecastJsonStr = null;

        try {

            URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");

            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            forecastJsonStr = buffer.toString();

            Log.v(LOG_TAG,"Forecast JSON string"+forecastJsonStr);

        } catch (IOException e) {
            Log.e("PlaceholderFragment", "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            return null;
        } finally{
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceholderFragment", "Error closing stream", e);
                }
            }
        }

        return null;
 }

LogCat is as follows:
08-18 20:12:14.608: E/PlaceholderFragment(15407): Error
08-18 20:12:14.608: E/PlaceholderFragment(15407): java.io.IOException
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at       libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:87)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at  com.example.sunshineapp.ForecastFragment$FetchWeatherTask.doInBackground(Forecas    tFragment.java:121)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at  com.example.sunshineapp.ForecastFragment.onOptionsItemSelected(ForecastFragment.    java:55)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at  android.app.Fragment.performOptionsItemSelected(Fragment.java:1801)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at  android.app.FragmentManagerImpl.dispatchOptionsItemSelected(FragmentManager.java :1959)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.app.Activity.onMenuItemSelected(Activity.java:2569)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:350)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.support.v7.app.ActionBarActivity.onMenuItemSelected(ActionBarActivity.java:155)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.support.v7.app.ActionBarActivityDelegate$1.onMenuItemSelected(ActionBarActivityDelegate.java:74)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.support.v7.app.ActionBarActivityDelegateBase.onMenuItemSelected(ActionBarActivityDelegateBase.java:556)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:802)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:949)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.support.v7.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:169)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.widget.AdapterView.performItemClick(AdapterView.java:298)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.widget.AbsListView.performItemClick(AbsListView.java:1128)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.widget.AbsListView$PerformClick.run(AbsListView.java:2815)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.widget.AbsListView$1.run(AbsListView.java:3574)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.os.Handler.handleCallback(Handler.java:800)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.os.Handler.dispatchMessage(Handler.java:100)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.os.Looper.loop(Looper.java:194)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at android.app.ActivityThread.main(ActivityThread.java:5371)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at java.lang.reflect.Method.invokeNative(Native Method)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at java.lang.reflect.Method.invoke(Method.java:525)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
08-18 20:12:14.608: E/PlaceholderFragment(15407):   at   dalvik.system.NativeStart.main(Native Method)

Line 121 in the logcat is the "urlconnection.connect()".
EDIT:
While running the app I came across the error :
Network on main thread exception
strictmode android block guard policy on network exception

These exceptions occur when there is a network intensive call on the UI thread.The answer can be found here.In order to avoid that I added the following code in the oncreate method of the main activity:
if (android.os.Build.VERSION.SDK_INT > 9) {
  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  StrictMode.setThreadPolicy(policy);
}

Also in addition it is recommended to do the network intensive calls using Async Task.
This solved the issue. Thanks all for your help!!

A: Add the INTERNET permission to your manifest file.
<uses-permission android:name="android.permission.INTERNET" />

A: Remove the urlConnection.connect(); line, I think urlConnection = (HttpURLConnection) url.openConnection(); is already enough

A: Try doing this:
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();

A: Try the following:
...
urlConnection.setDoInput(true);
...
urlConnection.connect();
InputStream inputStream = null;
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
     inputStream = urlConnection.getInputStream();
} else {
     inputStream = urlConnection.getErrorStream();
}
...

Moreover, use e.printStackTrace(); instead of Log.e("PlaceholderFragment", "Error ", e); for full logcat
UPDATE:
Replace
FetchWeatherTask f = new FetchWeatherTask();
            f.doInBackground(null);
by
new FetchWeatherTask().execute();
Hope this helps!

A: While running the app I came across the error :
Network on main thread exception
strictmode android block guard policy on network exception

These exceptions occur when there is a network intensive call on the UI thread.The answer can be found here.In order to avoid that I added the following code in the oncreate method of the main activity:
if (android.os.Build.VERSION.SDK_INT > 9) {
 StrictMode.ThreadPolicy policy = new     StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy);
 }

Also in addition it is recommended to do the network intensive calls using Async Task.
This solved the issue. Thanks all for your help!!


text:
Q: Looping through IEnumerable using ForEach in C# I'm trying to loop through an IEnumerable but for some reason it is not going through the foreach loop, as the values for each ChartClass was not modified.
public IEnumerable<ChartClass> get(string ID, string buildname, string placeholder)
    {
        var context = new Entities();
        var metrics = from c in context.VSTS_CODE_METRICS
                      where c.BUILD_NAME == buildname && c.OBJECT_TYPE == "Namespace"
                      group c by c.BUILD_ID into g
                      select new ChartClass
                      {
                          Build_ID = g.Key,
                          BuildTrim = g.Key,
                          Index = g.Average(c => c.MAINTAINABILITYINDEX_).Value
                      };
        foreach (var i in metrics)
        {
            int num = i.BuildTrim.LastIndexOf('_');
            i.BuildTrim = "2";
        }
        return metrics;
    }

I'm trying to change each ChartClass' BuildTrim field to "2" but it's not happening for some reason

A: Why don't you just set the BuildTrim equal to "2" in the query?
public IEnumerable<ChartClass> get(string ID, string buildname, string placeholder)
    {
        var context = new Entities();
        var metrics = from c in context.VSTS_CODE_METRICS
                      where c.BUILD_NAME == buildname && c.OBJECT_TYPE == "Namespace"
                      group c by c.BUILD_ID into g
                      select new ChartClass
                      {
                          Build_ID = g.Key,
                          BuildTrim = "2",//g.Key,
                          Index = g.Average(c => c.MAINTAINABILITYINDEX_).Value
                      };
        /*foreach (var i in metrics)
        {
            int num = i.BuildTrim.LastIndexOf('_');
            i.BuildTrim = "2";
        }*/
        return metrics;
    }

A: metrics is an IQueryable.  Every single time you iterate the object it is going to to to the database, query the items that you're asking for, put them into the objects that you specified, and then allow those objects to be iterated.  You're modifying the objects that are being returned, but those same in-memory objects won't be used if you iterate the sequence again.  Instead it's going back to the database a second time and pulling back a fresh query that doesn't have your changes.
As mentioned in the other answer, if you simply modify your first Select call to set BuildTrim to the desired value to begin with, rather than modifying an object that is just about to be thrown away, your query will work as intended.


text:
Q: java.lang.IllegalStateException: Result has already been consumed I'm currently studying ways to sync data between an Android device to Google Drive and stumbled upon the sample code at https://github.com/googledrive/android-quickeditor , but I'm encountering an issue when opening an existing file and then tapping on 'Save Changes'. Basically the problematic code is here:
@Override
protected com.google.android.gms.common.api.Status doInBackground(DriveId... params) {
    R await;

    DriveFile file = params[0].asDriveFile();
    PendingResult<DriveContentsResult> openDriveContentsResult = file.open(mClient, DriveFile.MODE_WRITE_ONLY, null);

    if (!openDriveContentsResult.await().getStatus().isSuccess()) {
        return openDriveContentsResult.await().getStatus();
    }

    Changes changes = edit(openDriveContentsResult.await().getDriveContents());
    PendingResult<MetadataResult> metadataResult = null;
    PendingResult<com.google.android.gms.common.api.Status> closeContentsResult = null;

    if (changes.getMetadataChangeSet() != null) {
        metadataResult = file.updateMetadata(mClient, changes.getMetadataChangeSet());
        if (!metadataResult.await().getStatus().isSuccess()) {
            return metadataResult.await().getStatus();
        }
    }

    if (changes.getDriveContents() != null) {
        closeContentsResult = changes.getDriveContents().commit(mClient, null);
        closeContentsResult.await();
    }
    return closeContentsResult.await().getStatus();
}

The exact line throwing the error is:
Changes changes = edit(openDriveContentsResult.await().getDriveContents());

The Error is java.lang.IllegalStateException: Result has already been consumed. I referred to the PendingResult class reference and it clearly states that "After the result has been retrieved using await() or delivered to the result callback, it is an error to attempt to retrieve the result again." Fair enough I guess.
The problem is, how am I supposed to fix this properly? I have commented out
if (!metadataResult.await().getStatus().isSuccess()) {...}

for now to avoid calling await() twice (for sake of debugging), BUT (as expected) then results into the same error at
return closeContentsResult.await().getStatus();

So...how can I fix this? Pretty please?

A: Solved. For anyone that's getting frustrated over this:
@Override
protected com.google.android.gms.common.api.Status doInBackground(DriveId... params)
{
    R await;
    DriveFile file;
    Changes changes;
    PendingResult<DriveContentsResult> openDriveContentsResult;
    DriveContentsResult driveContentsResult;
    PendingResult<MetadataResult> updateMetadataResult;
    MetadataResult metaDataResult;
    PendingResult<com.google.android.gms.common.api.Status> commitResults;
    com.google.android.gms.common.api.Status closeContentResults = null;

    file                    = params[0].asDriveFile();
    openDriveContentsResult = file.open(mClient, DriveFile.MODE_WRITE_ONLY, null);

    driveContentsResult     = openDriveContentsResult.await();
    if (!driveContentsResult.getStatus().isSuccess())
    {
        return driveContentsResult.getStatus();
    }

    changes                 = edit(driveContentsResult.getDriveContents());
    updateMetadataResult    = null;
    commitResults           = null;

    if (changes.getMetadataChangeSet() != null)
    {
        updateMetadataResult = file.updateMetadata(mClient, changes.getMetadataChangeSet());
        metaDataResult       = updateMetadataResult.await();

        if (!metaDataResult.getStatus().isSuccess())
        {
            return metaDataResult.getStatus();
        }
    }

    if (changes.getDriveContents() != null)
    {
        commitResults = changes.getDriveContents().commit(mClient, null);
        closeContentResults = commitResults.await();
    }

    if (null == commitResults)
    {
        return commitResults.await().getStatus();
    }
    else
    {
        return closeContentResults.getStatus();
    }
}


text:
Q: "unexpected EOF while parsing" I'm trying to implement this part of code.
The error "unexpected EOF while parsing" occurs in the last line. I tried various things but can't seem to find what is wrong (T^T)
def simpsonsumme(f, a, b, N):
    X = np.linspace(a, b, N)
    if N%2 == 0:
        return ((b-a)/(3*(N)) * ( f(0) + 4*np.sum(f(X[1:-1:2])) + 2*np.sum(f(X[2:-2:2])) + f(N)))

(I'm trying to implement the simpsons rule. f is a function; [a,b] the intervall of the integration and N the number of sections in [a,b], maybe that is somewhat helpful context)
Thank you in advance!


text:
Q: Group the data based on binary, and calculate mean, sd I have df looks like this
        options(scipen=999)
        df = data.frame(imei = c(35745407328, 35745407328, 35745407328,
                                 35745407328, 35745407328, 35745407328,
                                 35745407328, 35745407328, 35745407328,
                                 35745407328, 35745407328, 35745407328),
                        ign = c("Off", "Off", "Off", "On",
                                "On", "Off", "Off", "On",
                                "On", "On",  "On",  "On" ),
                        unixTime =  c(1514313014000, 1514313074000, 1514313134000, 1514313194000,
                                      1514313254000, 1514313314000, 1514313374000, 1514313434000,
                                      1514313494000, 1514313554000, 1514313614000, 1514313674000))

df
        ----------------------------------
        imei            ign unixTime
        ----------------------------------
        35745407328     Off 1514313014000
        ----------------------------------
        35745407328     Off 1514313074000
        ----------------------------------
        35745407328     Off 1514313134000
        ----------------------------------
        35745407328     On  1514313194000
        ----------------------------------
        35745407328     On  1514313254000
        ----------------------------------
        35745407328     Off 1514313314000
        ----------------------------------
        35745407328     Off 1514313374000
        ----------------------------------
        35745407328     On  1514313434000
        ----------------------------------
        35745407328     On  1514313494000
        ----------------------------------
        35745407328     On  1514313554000
        ----------------------------------
        35745407328     On  1514313614000
        ----------------------------------
        35745407328     On  1514313674000
        ----------------------------------

I want to group the above data based on 'ign' and then
I want to calculate mean, the standard deviation of unixTime.
And based on first and last values in the group difference
of unixTime
Grouping based on which mean, sd and diff will be calculated
        ----------------------------------
         imei           ign unixTime
        ----------------------------------
        35745407328     Off 1514313014000
        ----------------------------------
        35745407328     Off 1514313074000
        ----------------------------------
        35745407328     Off 1514313134000
        ----------------------------------

        ----------------------------------
        35745407328     On  1514313194000
        ----------------------------------
        35745407328     On  1514313254000
        ----------------------------------

        ----------------------------------
        35745407328     Off 1514313314000
        ----------------------------------
        35745407328     Off 1514313374000
        ----------------------------------

        ----------------------------------
        35745407328     On  1514313434000
        ----------------------------------
        35745407328     On  1514313494000
        ----------------------------------
        35745407328     On  1514313554000
        ----------------------------------
        35745407328     On  1514313614000
        ----------------------------------
        35745407328     On  1514313674000
        ----------------------------------

Please help me with this
If the answer is already available. Please, provide me the link. thankyou

A: A solution using data.table.
library(data.table)

setDT(df)

df2 <- df[, Group := rleid(ign)][
  , c("Mean", "SD", "Diff") := list(mean(unixTime),
                                    sd(unixTime),
                                    first(unixTime) - last(unixTime)),
  by = Group]

df2[]
#            imei ign      unixTime Group          Mean       SD    Diff
#  1: 35745407328 Off 1514313014000     1 1514313074000 60000.00 -120000
#  2: 35745407328 Off 1514313074000     1 1514313074000 60000.00 -120000
#  3: 35745407328 Off 1514313134000     1 1514313074000 60000.00 -120000
#  4: 35745407328  On 1514313194000     2 1514313224000 42426.41  -60000
#  5: 35745407328  On 1514313254000     2 1514313224000 42426.41  -60000
#  6: 35745407328 Off 1514313314000     3 1514313344000 42426.41  -60000
#  7: 35745407328 Off 1514313374000     3 1514313344000 42426.41  -60000
#  8: 35745407328  On 1514313434000     4 1514313554000 94868.33 -240000
#  9: 35745407328  On 1514313494000     4 1514313554000 94868.33 -240000
# 10: 35745407328  On 1514313554000     4 1514313554000 94868.33 -240000
# 11: 35745407328  On 1514313614000     4 1514313554000 94868.33 -240000
# 12: 35745407328  On 1514313674000     4 1514313554000 94868.33 -240000

Or a solution using dplyr and data.table
library(dplyr)
library(data.table)

df2 <- df %>%
  group_by(Group = rleid(ign)) %>%
  mutate(Mean = mean(unixTime), SD = sd(unixTime),
         Diff = first(unixTime) - last(unixTime)) %>%
  ungroup()
df2
#           imei    ign      unixTime Group          Mean       SD    Diff
#          <dbl> <fctr>         <dbl> <int>         <dbl>    <dbl>   <dbl>
#  1 35745407328    Off 1514313014000     1 1514313074000 60000.00 -120000
#  2 35745407328    Off 1514313074000     1 1514313074000 60000.00 -120000
#  3 35745407328    Off 1514313134000     1 1514313074000 60000.00 -120000
#  4 35745407328     On 1514313194000     2 1514313224000 42426.41  -60000
#  5 35745407328     On 1514313254000     2 1514313224000 42426.41  -60000
#  6 35745407328    Off 1514313314000     3 1514313344000 42426.41  -60000
#  7 35745407328    Off 1514313374000     3 1514313344000 42426.41  -60000
#  8 35745407328     On 1514313434000     4 1514313554000 94868.33 -240000
#  9 35745407328     On 1514313494000     4 1514313554000 94868.33 -240000
# 10 35745407328     On 1514313554000     4 1514313554000 94868.33 -240000
# 11 35745407328     On 1514313614000     4 1514313554000 94868.33 -240000
# 12 35745407328     On 1514313674000     4 1514313554000 94868.33 -240000


text:
Q: What is deps="low" on Travis I have been google this for hours, could someone please tell me what's the meaning of deps="low" env var on a Travis-CI Build ?

A: It essentially tells composer to update to the lowest possible version that still meets dependency requirements.
Check this: http://evertpot.com/testing-composer-prefer-lowest/
also, in Travis.yml:
- if [ "$deps" = "no" ]; then composer --prefer-source install; fi;
- if [ "$deps" = "high" ]; then composer --prefer-source update; fi;
- if [ "$deps" = "low" ]; then composer --prefer-source --prefer-lowest --prefer-stable update; fi;


text:
Q: Assistance with javascript algorithm I can't seem to understand why index is returning undefined. The goal is to place a number in a ordered array, in the correct position. I start by findind the position, but it's returning undefined.
var arr = [3,7,9,12,16,20,31,43,50,55];
var value;
var i=0;
var index;

value = Number(prompt("Enter a value [3,7,9,12,16,20,31,43,50,55]"));
document.write( arr+"
");

while(value > arr[i]){

    if (value < arr[i])
    {
        index=i;
    }
    i++;
}

document.write(index+"
");

for (i=arr.length-1 ; i>=index; i--){
     arr[i+1] = arr[i];
}

arr[index]=value;
document.write(arr+"
");

A: For example, if you select 9, the loop goes up to 7 and this is the last value where the while condition is true. The nested check is never reached.
For getting a result, you could take the loop and increment only the index an take the check outside and if the value is smaller or equal, take the index.

var arr = [3, 7, 9, 12, 16, 20, 31, 43, 50, 55];
var value;
var i = 0;
var index;

value = Number(prompt("Enter a value [3,7,9,12,16,20,31,43,50,55]"));
console.log(...arr);

while (value > arr[i]) i++;

if (value <= arr[i]) index = i;

console.log(index);


text:
Q: Laravel insert array to DB and associate another array with it's id's I am looping through an array and generate 3 arrays. One that goes to Event table, one for address table and another for geoloc table. Problem is that geoloc + address table needs event_id which is a foreign key linked to id in event table.  I am doing a bulk insert because there are a lot of records in the array, roughly about 1500. Is it possible to associate address and geoloc with event id when $event is a bulk insert?
foreach ($facebookEvents as $facebookEvent) {
    if (!empty($facebookEvent['event_times'][0]['start_time'])) {
        foreach ($facebookEvent['event_times'] as $recurrence) {
            $eventsArray[] = [
                'type' => 'Facebook Event',
                'startdate' => date('Y-m-d', strtotime($recurrence['start_time'])),
                'endate' => date('Y-m-d', strtotime($recurrence['end_time'])),
                'startime' => date('H:i:s', strtotime($facebookEvent['start_time'])),
                'endtime' => date('H:i:s', strtotime($facebookEvent['end_time'])),
                'title' => $facebookEvent['name'],
                'description' => $facebookEvent['description'],
                'entity_id' => $event,
            ];
            $addressArray[] = [
                'town' => $facebookEvent['place']['location']['city'],
                'address' => $facebookEvent['place']['location']['street'],
                'postcode' => $facebookEvent['place']['location']['zip'],
                            // also event id from each $eventsarray
            ];
            $geolocArray[] = [
                'lat' => $facebookEvent['place']['location']['latitude'],
                'lng' => $facebookEvent['place']['location']['longitude'],
                            // also event id from each $eventsarray saved
            ];
        }
    }
}
} catch (Exception $e) {
    $error = $e->getMessage();
    $env = config('app.name');
    $command = 'Facebook Recalculate';
    Notification::route('slack', 'https://hooks.slack.com/services/T30BGA1EW/B7A9TEC3F/N0FqRyzdsdsdsDN5SVxiN')
    ->notify(new JobErrorNotification($error, $env, $command));
}
}
$event = Event::insert($eventsArray);
    //save address array and add $event->id for each one
    // same for geoloc
$algolia = Event::all()->searchable();
}


text:
Q: Not Playing Sound in Android 9 I create a record file in MP3 format, but this file does not run in Android 9 and above, while it runs in Android 7, another problem is that this file does not open with any other application on the Android phone, but when the file I upload the desired file to the server or run the desired file via USB in Windows. This file will run
MediaPlayer player = new MediaPlayer()
String filePath = Environment.getExternalStorageDirectory() + "/Audio/20210907144451.mp3"
try {
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
           player.setAudioAttributes(new AudioAttributes.Builder()
                 .setUsage(AudioAttributes.USAGE_MEDIA)
                 .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                 .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                 .build());
       } else {
             player.setAudioStreamType(AudioManager.STREAM_MUSIC);
       }

       //filePath: /storage/emulated/0/Audio/20210907144451.mp3

       player.setDataSource(filePath);
       player.prepare();
       player.start();
} catch (Exception ex) {
    LOG(ex.getMessage());
}

Permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Error text

Prepare failed.: status=0x1

A: Try this:
MediaPlayer mediaPlayer = new MediaPlayer();
FileInputStream fis = null;
try {
    File directory = new File("/storage/emulated/0/Audio/20210907144451.mp3");
    fis = new FileInputStream(directory);
    mediaPlayer.setDataSource(fis.getFD());
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.prepare();
}   finally {
    if (fis != null) {
        try {
            fis.close();
        } catch (IOException ignore) {
        }
    }

}


text:
Q: Compiz not doing anything I am trying to get the launcher icons to be a smaller size, the launcher to be less opaque, and the launcher to be fixed and never disappear off the left of the screen.
But...when I go into Compiz-->Ubuntu Unity Plugin (enabled)-->Experimental move the "Panel Opacity" and "Launcher Icon Size" icons left and right doesn't do anything.
Any suggestions? Thanks!

A: *

*After changing the options in Compiz, logout the system and login again to make the changes.

*Or you can use Ubuntu Tweak which does the same things and which is very much reliable.


text:
Q: How to put sessions on all pages without putting the session code on all views in pyramid? I think my problem is related on the way I structured my pyramid project.
What I want to accomplish is to make my code runs on all views, I don't want to paste same codes on all views. Its like I will include the code in all views by just simply calling it. This is my code.
my wizard module
from pyramid.view import view_config, view_defaults
from .models import *
from datetime import datetime
from pyramid.response import Response
from bson import ObjectId
from pyramid.httpexceptions import HTTPFound
import json

class WizardView:

def __init__(self, request):
    self.request = request

@view_config(route_name='wizard', renderer='templates/wizard.jinja2')
def wizard(self):
    session = self.request.session
    if session:
        return {'fullname':session['name'],'userrole':session['userrole']}
    else:
        url = self.request.route_url('login')
        return HTTPFound(location=url)

my bill module
from pyramid.view import view_config, view_defaults
from .models import *
from datetime import datetime
from pyramid.response import Response
from bson import ObjectId
from pyramid.httpexceptions import HTTPFound

class BillView:

def __init__(self, request):
    self.request = request

@view_config(route_name='bills', renderer='templates/bills.jinja2')
def bills(self):
    session = self.request.session
    if session:
        return {'fullname':session['name'],'userrole':session['userrole']}
    else:
        url = self.request.route_url('login')
        return HTTPFound(location=url)

As you can see I have to paste this code twice (this code checks if session exist, if not, then redirect user to login page)
session = self.request.session
if session:
    return {'fullname':session['name'],'userrole':session['userrole']}
else:
    url = self.request.route_url('login')
    return HTTPFound(location=url)

I've tried to search and I think what I need is some sort of auto loader? How can I apply this on pyramid? Or should I stick with this process?

A: If you wish to return exactly the same thing from both (many) views, then the best way is to use inheritance.
class GenericView:
    def __init__(self, request):
    self.request = request

    def generic_response(self):
        session = self.request.session
        if session:
            return {'fullname':session['name'],'userrole':session['userrole']}
        else:
            url = self.request.route_url('login')
            return HTTPFound(location=url)

Use generic_response in WizardView and BillView
class WizardView(GenericView):

    def __init__(self, request):
        super().__init__(request)
        # Do wizard specific initialization

    @view_config(route_name='wizard', renderer='templates/wizard.jinja2')
    def wizard(self):
        return self.generic_response()

class BillView(GenericView):

    def __init__(self, request):
        super().__init__(request)
        # Do bill specific initialization

    @view_config(route_name='bills', renderer='templates/bills.jinja2')
    def bills(self):
        return self.generic_response()

If you want to just check (and redirect) when session does not exists and otherwise proceed normally you could use custom exceptions and corresponding views.
First define custom exception
class SessionNotPresent(Exception):
    pass

And view for this exception
@view_config(context=SessionNotPresent)
def handle_no_session(context, request):
     # context is our custom exception, request is normal request
     request.route_url('login')
     return HTTPFound(location=url)

Then just check if session exists in parent constructor
class SessionView:
    def __init__(self, request):
        self.request = request
        if not self.request.session:
            raise SessionNotPresent() # Pyramid will delegate request handilng to handle_no_request

In views simply extend SessionView and non existing sessions will be handeled by handle_no_session.
class WizardView(SessionView):

    def __init__(self, request):
        super().__init__(request)
        # Do wizard specific initialization

    @view_config(route_name='wizard', renderer='templates/wizard.jinja2')
    def wizard(self):
        session = self.request.session
        return {'fullname':session['name'],'userrole':session['userrole']}

class BillView(SessionView):

    def __init__(self, request):
        super().__init__(request)
        # Do bill specific initialization

    @view_config(route_name='bills', renderer='templates/bills.jinja2')
    def bills(self):
        session = self.request.session
        return {'fullname':session['name'],'userrole':session['userrole']}

You could easily add additional parameters to exception (redirect_url, ...)
For exception handling see http://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/pylons/exceptions.html

A: You can use events: http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/events.html
Example:
from pyramid.events import subscriber, NewRequest
@subscriber(NewRequest)
def check_session(event):
    if not event.request.session:
        raise HTTPFound(location=event.request.route_path('login'))


text:
Q: Ionic v4 - how do I autofocus on a Input? I have a view with an input <ion-input #codigobarras></ion-input>
How can I auto focus on this input?
What have I tried
@ViewChild('codigobarras') input_codigobarras: Input;

...

ionViewDidEnter() {
    this.input_codigobarras.focus(); // didn't work = temp2.focus is not a function
    this.input_codigobarras.focus.emit(); // didn't work = do nothing, just returns undefined
    this.input_codigobarras.getElementRef().nativeElement.focus() // didn't work = do nothing, just returns undefined
    this.input_codigobarras.setFocus(); // didn't work = do nothing, just returns undefined
}

<ion-input [autofocus]></ion-input> <!-- Didn't work -->

A: After the loading of your items you can try to trigger your ElementRef with ngOnChanges()
 @ViewChild('test') test: ElementRef;

 ngOnChanges(changes: SimpleChanges){
     if(changes.items) {
     this.test.nativeElement.firstChild['autofocus'] = 'true';
   }
}

and your html
<div #test>
  <ion-input ></ion-input>
</div>

A: I had an conflict of focus regarding with ion-input inside a ion-modal. In fact, after using a timeout, i realized that my ion-input was focus and unfocused instantly.

setTimeout(() => this.ionInput.setFocus(), 100);

So, I console log the activeElement (the one that is focused) with:

document.activeElement

And the console output ion-modal.
Hence, I had to wait the ion-modal to be "fully loaded" to use the setFocus with as mentioned above.

A: This should work
<ion-input autofocus="true"></ion-input>

A: A more generic solution to do this when and where you want could be:
<ion-input ... #inputId></ion-input>

So with a ViewChild in your controller you can easily set the focus on:
@ViewChild('inputId', {static: false}) ionInput: { setFocus: () => void; };
...
setFocusOnInput() {
   this.ionInput.setFocus();
}

A: Ionic 4/5
HTML
<ion-input ... #inputId></ion-input>

TS
export class SomePage {
....
@ViewChild('inputId', {static: false}) inputEl: IonInput;
....

focusOnElement() {
    this.tipDesc.setFocus();
}

Ionic 3
@ViewChild('inputId') inputEl: TextInput;

Call focusOnElement() when you want to focust on input

A: Using Ionic 6 :

  HTML :
    <ion-input type="text" #autofocus>

    TS File :
    import { Component, ViewChild } from '@angular/core';

    @ViewChild('autofocus', { static: false }) inputBox!: IonInput;

    ionViewWillEnter() {
        setTimeout(() => this.inputBox.setFocus(), 300);
      }


text:
Q: JavaFX directory file list Has anybody know with what command I can get all files names in directory ?
I can`t find in tutorials.
pls, Help me

A: Do you know that you can, in JavaFX scripts, directly use Java classes ? As a consequence, getting all file names in a directory in JavaFX works exactly like in Java (as JavaFX does not contains those kind of classes, focusing as it is on UI creation)j, that's to say by calling File#listFiles()


text:
Q: @Category in AutoBean Am totally lost trying to understand the @Category annotation of AutoBean. Can somebody please  tell me how exactly it can be used?
I went through the example in wiki as well. My doubt is like this.
Say I am having a proxy interface in the client side which extends entity proxy, and I want to insert a non setter/getter method in that interface, how can I do that?
@ProxyFor( value = CacheStrategy.class )
public interface CacheStrategyProxy extends EntityProxy
{
// setters and getters

   CacheStrategyProxy  fetchObject(int id);
}

@Category(CacheStrategyProxyCategory.class)
interface MyFactory extends AutoBeanFactory {
          AutoBean<CacheStrategyProxy> fetchObject();
}

class CacheStrategyProxyCategory {
      public static CacheStrategyProxy fetchObject (AutoBean<CacheStrategyProxy> instance, int id) {
                 // return data
    }
}

Am writing all this in my CacheStrategyProxy file. But I still get the error "Only setters and getters allowed". Pardon me if I have done something silly here. I am totally new to this world.

A: @Category cannot be used with Request Factory (at least not currently).
Request Factory makes use of AutoBeans (and your proxies will be AutoBean instances) but the AutoBeanFactory (factories actually) is/are internal to the RequestFactory, and you cannot tweak them.


text: Q: Counting the number of k-term arithmetic progressions with fixed gap of 2m from [1,n] Following the proof of finding a lower bound using the probabilistic method for van der Waerden numbers, I'm trying to find the lower bound of a different family. The previously mentioned proof can be found here. Specifically, I'm looking at Lemma 3.2. So, my question is: if I'm looking at the family of arithmetic progressions with fixed gap of 2m, as opposed to the family of all arithmetic progressions, how can I count the number of k-term arithmetic progressions from [1,n], similar to this example?