text:
Q: OTA for FreeRTOS for device in deep sleep from AWS Background
I have a small battery powered system running on freeRTOS. I need to periodically run OTA updates, as per any proper internet connected device. The problem is that, being battery powered, the device spends 99.9% of it's life in deep sleep.
When the device is awake, it's possible to post an OTA update from AWS, by publishing to the device's OTA/update topic. From the console, you can only use QOS = 0. But from inside, say a lambda, I believe it's possible to use QOS = 1.
{
"state": {
        "desired": {
            "ota_url":"https://s3-ap-southeast-2.amazonaws.com/my.awesome.bucket/signed_binary_v21.bin"
        }
    }
}

Questions

*

*How can I modify this approach to successfully update a device that sleeps for 15 minutes at a time, and wakes for maybe 10 s. During the waking period, it sends a message. Is there some way of leaving the desired OTA/update in the shadow that somehow is included in the response from AWS. I've not managed to figure out how shadows really work. OR can you specify a retry period and time to keep trying perhaps?

*Is this approach essentially consistent with the most recent best practice from a security perspective : signed binary, encrypted flash & secure boot etc.

Many thanks.

A: IDF comes with an OTA example that is pretty straight forward.  As suggested in the comments on your question, the example downloads the firmware update, and it will automatically revert to the previous image if the updated version has errors that cause a reset.  This is the operative part of the example:
extern const uint8_t server_cert_pem_start[] asm("_binary_ca_cert_pem_start");
extern const uint8_t server_cert_pem_end[] asm("_binary_ca_cert_pem_end");
esp_err_t _ota_http_event_handler(esp_http_client_event_t* evt);
#define FIRMWARE_UPGRADE_URL "https://yourserver.com/somefolder/somefirmware.bin"

void simple_ota_task(void* pvParameter)
{
    esp_http_client_config_t config = {
        .url = FIRMWARE_UPGRADE_URL,
        .cert_pem = (char*)server_cert_pem_start,
        .event_handler = _ota_http_event_handler,
    };
    esp_err_t ret = esp_https_ota(&config);
    if (ret == ESP_OK)
        ESP_LOGW("ota", "Upgrade success");
    else
        ESP_LOGE(TAG, "Upgrade failure");

    esp_restart();
}

void foo()
{
    // after initializing WiFi, create a task to execute OTA:
    //
    xTaskCreate(&simple_ota_task, "ota_task", 8192, NULL, 5, NULL);
}

// event handler callback referenced above, it has no functional purpose
// just dumps info log output
esp_err_t _ota_http_event_handler(esp_http_client_event_t* evt)
{
    switch (evt->event_id) {
    case HTTP_EVENT_ERROR:
        ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
        break;
    case HTTP_EVENT_ON_CONNECTED:
        ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED");
        break;
    case HTTP_EVENT_HEADER_SENT:
        ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT");
        break;
    case HTTP_EVENT_ON_HEADER:
        ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value);
        break;
    case HTTP_EVENT_ON_DATA:
        ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
        break;
    case HTTP_EVENT_ON_FINISH:
        ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH");
        break;
    case HTTP_EVENT_DISCONNECTED:
        ESP_LOGD(TAG, "HTTP_EVENT_DISCONNECTED");
        break;
    }
    return ESP_OK;
}

To setup embedding the cert, obtain the public key by examining the SSL cert for the site on which the bin file will reside, with a web browser, save it, then convert it to Base64, aka PEM format. (I used some web page.)  In my case I created a directory at the same level as the /main directory, called /server_certs, and saved the Base64 conversion in that directory as ca_cert.pem.  (That was way too pedantic, wasn't it?)
Then added these lines to CMakeFiles.txt in the /main directory:
# Embed the server root certificate into the final binary
set(COMPONENT_EMBED_TXTFILES ${IDF_PROJECT_PATH}/server_certs/ca_cert.pem)
register_component()

The thing that was unclear to me was how to determine that a newer version is available, if there is a built-in way I couldn't discern it, and did not want to download the update for nothing, ever.  So I rolled my own, embedded a version string in the firmware, created a WebAPI entry point on my server that returns the current version (both maintained by hand until I can think of a better way... that I feel like implementing) and call the OTA functionality when the strings don't match.  It looks a lot like this:
// The WebAPI returns data in JSON format,
// so if a method returns a string it is quoted.
#define FW_VERSION "\"00.09.015\""

// the HTTP request has just completed, payload stored in recv_buf
//
// tack a null terminator using an index maintained by the HTTP transfer
recv_buf[pos + 1] = 0;
// test for success
if (strncmp(recv_buf, "HTTP/1.1 200 OK", 15) == 0)
{
    // find the end of the headers
    char *p = strstr(recv_buf, "\r\n\r\n");
    if (p)
    {
        ESP_LOGI("***", "version: %s  content %s", FW_VERSION, (p + 4));
        if (strcmp((p + 4), FW_VERSION) > 0)
        {
            // execute OTA task
            foo();
        }
        else
        {
            // Assumes the new version has run far enough to be
            // considered working, commits the update.  It doesn't
            // hurt anything to call this any number of times.
            esp_ota_mark_app_valid_cancel_rollback();
        }
    }
}

If you're not using the CMake/Ninja build tools, consider checking it out, it's way, way faster than the MingW32-based tool set.

A: As you have mentioned, you do not fully understand how shadows work, let me explain how using shadows may fit in scenario similar to yours.
Normally, a device that sleeps for long and wakes up for a short duration, usually makes a request to device shadow at wake up. If the shadow contains

{"state": {"desired":{"ota_url": "xxx", "do_ota": true, ...}}},

In this case, device should initiate ota update code inside device.
Further, the approach mentioned here has nothing to do with security and best practices (signed binary, encrypted flash and secure boot). All these three things should be handled by ota update program. Shadows are only used to indicate that there is a ota update available. Using shadow help you avoid making unnecessary GET Request to OTA server, in turn saving precious power and compute resources.


text:
Q: Проблемы с наследованием в Java Доброго времени суток всем. Хочу поднять свой уровень и научится делать кастомные вьюхи. Думал сначала взять TabLayout и просто переопределить метод onDraw допустим, но тут же столкнулся с проблемой(скорее всего нехваткой знаний). В общем проблема в том что после наследования и переопределения метода onDraw в моем классе(MyTabLayout), я хочу что бы все остальные методы супер класса(TabLayout) остались как были, так что в чем мой косяк и как это сделать?
П.С. Простите за глупый вопрос.
 */
public class MyTabLeyout extends TableLayout {

private int mIndicatorLeft = -1;

private int mIndicatorRight = -1;

private int mSelectedIndicatorHeight;

private final Paint mSelectedIndicatorPaint;

private static final Pools.Pool<TabLayout.Tab> sTabPool = new Pools.SynchronizedPool<>(16);

private final ArrayList<TabLayout.Tab> mTabs = new ArrayList<>();

public MyTabLeyout(Context context, Paint mSelectedIndicatorPaint) {
    super(context);
    this.mSelectedIndicatorPaint = new Paint();
}
public int getTabCount() {
    return mTabs.size();
}

private void setIndicatorPosition(int left, int right) {
    if (left != mIndicatorLeft || right != mIndicatorRight) {
        // If the indicator's left/right has changed, invalidate
        mIndicatorLeft = left;
        mIndicatorRight = right;
        ViewCompat.postInvalidateOnAnimation(this);
    }
}
void setSelectedIndicatorColor(int color) {

    if (mSelectedIndicatorPaint.getColor() != color) {
        mSelectedIndicatorPaint.setColor(color);
        ViewCompat.postInvalidateOnAnimation(this);
    }
}
void setSelectedIndicatorHeight(int height) {
    if (mSelectedIndicatorHeight != height) {
        mSelectedIndicatorHeight = height;
        ViewCompat.postInvalidateOnAnimation(this);
    }
}

@Override
public void draw(Canvas canvas) {
    super.draw(canvas);

    // Thick colored underline below the current selection
    if (mIndicatorLeft >= 0 && mIndicatorRight > mIndicatorLeft) {
        canvas.drawCircle(mIndicatorLeft,getHeight() - mSelectedIndicatorHeight,10,mSelectedIndicatorPaint);
        // canvas.drawRect(mIndicatorLeft, getHeight() - mSelectedIndicatorHeight,
        //      mIndicatorRight, getHeight(), mSelectedIndicatorPaint);
    }
}
 }

A: Вы просто опечатались. Вы хотели расширить TabLayout, а расширили TableLayout.
Будьте внимательны)

redpajama_set_name: RedPajamaStackExchange


text:
Q: What gets constructed first? I am just wondering about the order of constructions here.
 What will be constructed here first is it theInstanceOfA`or the constructor of B which will call A already?
class A {
    public:
    A() { cout << "A ctor" << endl; }
    A(const A& a) { cout << "A copy ctor" << endl; }
    virtual ~A() { cout << "A dtor" << endl; }
    virtual void foo() { cout << "A foo()" << endl; }
    virtual A& operator=(const A& rhs) { cout << "A op=" << endl; }
};

class B : public A {
    public:
    B() { cout << "B ctor" << endl; }
    virtual ~B() { cout << "B dtor" << endl; }
    virtual void foo() { cout << "B foo()" << endl; }
    protected:
    A mInstanceOfA; // don't forget about me!
    };

int main() {
    B X;
}

A: The order of constructors is:
Base - Members - Derived


text:
Q: Framework to test STUN/TURN/ICE protocols? I need to test STUN/TURN/ICE protocols, is there any existing testing framework for this.
Like SIPp is there to test SIP scenarios, suggest anything similar to this for STUN/TURN/ICE protocols.

A: SIP scenarios can't be compared with ICE connections scenarios.
However, if you want to check that a browser is able to connect to a STUN, or a TURN server (retrieving ICE candidates), there is the Trickle ICE Demo.


text:
Q: ODE solver using Lobatto IIIA with table of coefficients So I'm trying to figure out how to solve a given equation y'=-y+2te^(-t+2) for t in [0,10], step of 0.01 and y(0)=0.
I am supposed to solve it using the Lobatto IIIA method following a Butcher tableau:
Coefficients table
So far, this is what I got:
function lob = Lobatto_solver()
     h = 0.01;
     t = 0:h:10;
     y = zeros(size(t));
     y(1) = 0;

     f = @(t,y) -y + (2*t*(exp(-t+2)));

     % Lobatto IIIA Method
     for i=1:numel(y)-1
         f1 = f(t(i), y(i));
         f2 = f(t(i)+(1/2)*h, y(i) + (5/24)*h*f1 + (1/3)*h*f2 + (-1/24)*h*f3);
         f3 = f(t(i)+h, y(i) + (1/6)*h*f1 + (2/3)*h*f2 + (1/6)*h*f3);
         y(x) = y(i) + h*((-1/2)*f1 + (2)*f2 + (-1/2)*f3);
     end
 end

It obviously makes no sense from the point when I equal f2 to itself, when the variable is still undefined.
Any help would be much appreciated :)
Cheers

A: You will need a predictor-corrector loop, in the simple case the corrector uses the slope-equations as basis of a fixed-point iteration. In the code below I use also the value of an explicit Euler step, in principle you could initialize all slopes with f1.
function lob = Lobatto_solver()
    h = 0.01;
    t = 0:h:10;
    y = zeros(size(t));
    y(1) = 0;

    f = @(t,y) -y + (2*t*(exp(-t+2)));

    % Lobatto IIIA Method
    for i=1:numel(y)-1
        f1 = f(t(i), y(i));
        f3 = f(t(i)+h, y(i)+h*f1)
        f2 = (f1+f3)/2;
        for k=1:3
          f2 = f(t(i)+(1/2)*h, y(i) + (5/24)*h*f1 + (1/3)*h*f2 + (-1/24)*h*f3);
          f3 = f(t(i)+h, y(i) + (1/6)*h*f1 + (2/3)*h*f2 + (1/6)*h*f3);
        end;
        y(i+1) = y(i) + h*((-1/2)*f1 + (2)*f2 + (-1/2)*f3);
    end
    plot(t,y,t,0.05+t.^2.*exp(-t+2))
end

The graph shows that the result (blue) is qualitatively correct, the exact solution curve (green) is shifted so that two distinct curves can be seen.


text:
Q: how to create margin moving image view android please give me sample moving image to my margin destination
ilustration
image        x (margin move image)

if image moving with drag image stoped moving to my margin
imageView.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                int eid = event.getAction();
                switch (eid) {
                case MotionEvent.ACTION_MOVE:
                    RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
                    int x = (int) event.getRawX();
                    //int y = (int) event.getRawY();
                    TextView text = (TextView) findViewById(R.id.editText1);
                    text.setText("1");
                   mParams.setMargins(0, 0, 70, 0);
                    mParams.leftMargin = x+0;
                    //mParams.

                    imageView.setLayoutParams(mParams);

                    break;
                default:
                    break;
                }
                return true;
            }
        }

A: FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
        Gravity.NO_GRAVITY);

the 3rd param(Gravity.NO_GRAVITY) that I missed. use it you can position views at anywhere with setting width/height.
Refered from Android. How to move the imageview(set position/margin) when it is created


text:
Q: I keep getting perhaps a missing \item error I'm having problems with my LaTeX code. I keep getting an error:
Underfull \vbox (badness 10000) has occurred while \output is active [13]

! LaTeX Error: Something's wrong--perhaps a missing \item.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.461 \end{algorithmic}

LaTeX code:
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{pifont}

\begin{document}
\begin{algorithm}
\caption{ glavna\_zanka }%function
\begin{algorithmic}[1]
\While{ končaj $\not=$ false }
\State $ rotiraj\_robota()$
 \State obrobje o = $izberi\_raziskovalni\_cilj()$
\If { o $\neq$ null }
    \State $ premakni\_do\_cilja(o)$
\Else
    \State  končaj = true
\EndIf
\EndWhile
\end{algorithmic}
\end{algorithm}

\begin{algorithm}
\caption{ izberi\_raziskovalni\_cilj() }
\begin{algorithmic}[1]
\end{algorithmic}
\end{algorithm}

\end{document}

I would appreciate any insight into the problem.

A: There are some lines of a code in the body of algorithmic expected. Please compare a compilable example:
\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{pifont}

\begin{document}
\begin{algorithm}
\caption{ glavna\_zanka }%function
\begin{algorithmic}[1]
\While{ končaj $\not=$ false }
\State $ rotiraj\_robota()$
 \State obrobje o = $izberi\_raziskovalni\_cilj()$
\If { o $\neq$ null }
    \State $ premakni\_do\_cilja(o)$
\Else
    \State  končaj = true
\EndIf
\EndWhile
\end{algorithmic}
\end{algorithm}

\begin{algorithm}
\caption{ izberi\_raziskovalni\_cilj() }
\begin{algorithmic}[1]
\While
\EndWhile
\end{algorithmic}
\end{algorithm}

\end{document}

BTW: LaTeX Error: Something's wrong--perhaps a missing \item. rarely means, that there is a missing item; at least according to my experience. :-)

A: It seems the algorithmic environment requires to have a content:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{pifont}

\begin{document}
%
\begin{algorithm}
  \caption{ glavna\_zanka }%function
  \begin{algorithmic}[1]
    \While{ končaj $\not=$ false }
    \State $ rotiraj\_robota()$
    \State obrobje o = $izberi\_raziskovalni\_cilj()$
    \If { o $\neq$ null }
    \State $ premakni\_do\_cilja(o)$
    \Else
    \State končaj = true
    \EndIf
    \EndWhile
  \end{algorithmic}
\end{algorithm}

\begin{algorithm}
  \caption{izberi\_raziskovalni\_cilj()}
  \begin{algorithmic}[1]
    \State Lalala…
  \end{algorithmic}
\end{algorithm}

\end{document}


text:
Q: Sharing components right with Angular Modules I would like to use some components in different modules. Currently my modular system is structured as follows

*

*app.modules.shared

*

*footerModules

*AdministrationModule

*profileModule

Now one wants to create a component, e.g. InputControlComponent, which I can use in components of AdministrationModule as well as in the ProfileModule.
My first idea was this

*

*app.modules.shared

*

*footerModules

*AdministrationModule

*profileModule

*SharedModules

Shared Modules
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { InputControlComponent } from './form/inputControl.component';

@NgModule({
    declarations: [
        InputControlComponent

    ],
    providers: [
    ],
    imports: [
        CommonModule,

    ],
    exports: [
        InputControlComponent
    ]
})
export class SharedModule {
    constructor(
    ) {
    }

}

app.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

[...]

import { SharedModule } from './shared/shared.module';

@NgModule({
    declarations: [
        AppComponent,
        [...]

    ],

    providers: [
        [...]

    ],
    imports: [
        CommonModule,
        [...]
        AdministrationModule,
        SharedModule,
        RouterModule.forRoot([
            { path: 'home', component: HomeComponent },
            { path: '**', component: PageNotFoundComponent },
        ]),

    ]

})
export class AppModuleShared {
    constructor(
    ) {
    }

}

But my InputControlComponent cannot be found.

A: I would divide it a bit differently.
At the level of your app.module you can create "modules" folder where you will put your main components like admin module or profile module - each in separate file.
If you have blocks of code which are shown almost everywhere like header or footer you can create blocks folder ( same level as app.module ) and put it there.
About MyButton I think it's good idea to create another file called Shared and put it there so you can easily import it where you need it.
So basically it would look like

*

*blocks = header -> header.component.ts + footer -> footer.component.ts ( and all kinds of your menu components )

*modules = profile -> profile.component.ts and all other files connected to it +
admin -> admin.component.ts and same as profile

*shared = myButton and all reusable stuff here declared and exported in shared.module

You can easily import shared.module in all modules where you would like to make use of your button component.

A: It seems that you are going in right direction, find the link in the end of this post and verify your logic. The whole logic should be :-
We cannot share a component to different modules by just importing that component inside all the modules, because Angular 2 doesn't allow us to import single component to different modules, if you try to do this then Angular will throw an error:
Type X(component) is part of the declarations of 2 modules

So, for solving this problem we create a Shared Module instead of sharing a component, now we share this module in all other modules for this we use import statement and import the shared module in all other modules after this the component will gets automatically shared to all the modules.
You can find detailed description here:-
https://www.oodlestechnologies.com/blogs/How-to-share-component-to-multiple-modules-in-Angular2


text:
Q: emberjs: Testing with Pavlov/QUnit produces TypeError: Object # has no method 'getHandler' Warning: I am a newbie. Thanks in advance for any help.
Pavlov/QUnit is causing problems with the router in my ember app. When using QUnit alone, the following test passes:
test "/contacts", ->
  expect(1)
  visit('/contacts').then ->
    ok(exists(".nav"), "The navbar was rendered")

But when using Pavlov with QUnit, the following test dies:
describe 'contacts index', ->
    it 'does render index', ->
      visit('/contacts').then ->
        assert(exists(".nav")).isTrue('The navbar was rendered')

and produces a "has no method 'getHandler'" error in the collectObjects method when the following is executed:

var handler = router.getHandler(result.handler);

Stack trace is below:
TypeError: Object #<Object> has no method 'getHandler'
    at collectObjects (http://localhost:3000/assets/test_helper.js:37674:28)
    at Object.Router.handleURL (http://localhost:3000/assets/test_helper.js:37347:9)
    at Ember.Router.Ember.Object.extend.handleURL (http://localhost:3000/assets/test_helper.js:38135:17)
    at Ember.Application.Ember.Namespace.extend.handleURL (http://localhost:3000/assets/test_helper.js:41451:12)
    at http://localhost:3000/assets/test_helper.js:18367:19
    at Object.Ember.handleErrors (http://localhost:3000/assets/test_helper.js:14228:17)
    at invoke (http://localhost:3000/assets/test_helper.js:18365:16)
    at Object.tryable (http://localhost:3000/assets/test_helper.js:18550:14)
    at Object.Ember.tryFinally (http://localhost:3000/assets/test_helper.js:15023:24)
    at Object.Ember.run (http://localhost:3000/assets/test_helper.js:18554:16)

A: Set up the Ember-testing/QUnit tests like this:
App.setupForTesting();
App.injectTestHelpers();

module("Integration Tests", {
  setup: function() {
    App.reset();
    Ember.run(App, App.advanceReadiness);
  }
});

Of course, replace App with your app's name.
The new Testing guide currently suggests this, but does not show the code.

A: I just had the same problem with QUnit. The tests were starting before my Ember application was ready, so calls to visit() would fail.
Try turning the QUnit autostart flag to false (http://api.qunitjs.com/QUnit.config/) and call QUnit.start() from your application ready callback. That fixed it for me, if you need more help you can look at this repo: https://github.com/remichaignon/ember-boilerplate


text:
Q: cannot show in data from database in edittext i am making a form FVPI.java. in the form i'm taking data from database but cannot show in form. this is source code form FVPI.java. please help..
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    View v = inflater.inflate(R.layout.fvpi, null);
      dataSource = new DBDataSource(getActivity());
      dataSource.open();

      edtsales= (EditText) v.findViewById(R.id.txtsales);
      edttglpros= (EditText) v.findViewById(R.id.txttgl);
      edtnamacustomer= (EditText) v.findViewById(R.id.txtnamacustomer);
      edtalamat= (EditText) v.findViewById(R.id.txtalamat);
      edtarea= (EditText) v.findViewById(R.id.txtarea);
      edtcp= (EditText) v.findViewById(R.id.txtcp);
      edtnotelp= (EditText) v.findViewById(R.id.txtphone);
      edtemail= (EditText) v.findViewById(R.id.txtemail);
      edtowner= (EditText) v.findViewById(R.id.txtowner);
      edtdirector= (EditText) v.findViewById(R.id.txtdirector);
      edtgroupcompany= (EditText) v.findViewById(R.id.txtgroupcompany);

        Customer customer = dataSource.getCustomer(customerid);
        if(Globals.customerpros==null){
            Globals.customerpros=customer;
        }
        edtnamacustomer.setText(customer.getname());
        edtalamat.setText(customer.getAddress());
        edtarea.setText(customer.getArea());
        edtcp.setText(customer.getContactperson());
        edtnotelp.setText(customer.getPhoneno());
        edtemail.setText(customer.getCustomeremail());
        edtowner.setText(customer.getOwner());
        edtdirector.setText(customer.getDirector());
        edtgroupcompany.setText(customer.getGroupcompany());
        edkapasitaspros.setText(customer.getCapacity());

and this is DBdatasource.java
public Customer getCustomer(String customerid){
        Customer Customer = new Customer();
        Cursor cursor = database.query(DBHelper.CUSTOMER, allCustomer, DBHelper.CUSTOMER_ID +"='cus1' ", null, null, null, null);
        cursor.moveToFirst();
        Customer = cursorToCustomer(cursor);
        cursor.close();
        return Customer;
    }

    private Customer cursorToCustomer(Cursor cursor)
    {
        Customer Customer = new Customer();
        Log.v("info", "The getString "+cursor.getString(cursor.getColumnIndex(DBHelper.CUSTOMER_ID)));
        Log.v("info", "The setLatLng " +cursor.getString(cursor.getColumnIndex(DBHelper.NAME))+","
                                       +cursor.getString(cursor.getColumnIndex(DBHelper.ADDRESS))+","
                                       +cursor.getString(cursor.getColumnIndex(DBHelper.AREA))+","
                                       +cursor.getString(cursor.getColumnIndex(DBHelper.CONTACT_PERSON))+","
                                       +cursor.getString(cursor.getColumnIndex(DBHelper.PHONE_NO))+","
                                       +cursor.getString(cursor.getColumnIndex(DBHelper.CUSTOMER_EMAIL))+","
                                       +cursor.getString(cursor.getColumnIndex(DBHelper.OWNER))+","
                                       +cursor.getString(cursor.getColumnIndex(DBHelper.DIRECTOR))+","
                                       +cursor.getString(cursor.getColumnIndex(DBHelper.GROUP_COMPANY))+","
                                       +cursor.getString(cursor.getColumnIndex(DBHelper.CAPACITY)));
        Customer.setcustomerid(cursor.getString(cursor.getColumnIndex(DBHelper.CUSTOMER_ID)));
        Customer.setname(cursor.getString(cursor.getColumnIndex(DBHelper.NAME)));
        Customer.setAddress(cursor.getString(cursor.getColumnIndex(DBHelper.ADDRESS)));
        Customer.setCity(cursor.getString(cursor.getColumnIndex(DBHelper.CITY)));
        Customer.setZipcode(cursor.getString(cursor.getColumnIndex(DBHelper.ZIPCODE)));
        Customer.setArea(cursor.getString(cursor.getColumnIndex(DBHelper.AREA)));
        Customer.setContactperson(cursor.getString(cursor.getColumnIndex(DBHelper.CONTACT_PERSON)));
        Customer.setPhoneno(cursor.getString(cursor.getColumnIndex(DBHelper.PHONE_NO)));
        Customer.setMobileno(cursor.getString(cursor.getColumnIndex(DBHelper.MOBILE_NO)));
        Customer.setCustomeremail(cursor.getString(cursor.getColumnIndex(DBHelper.CUSTOMER_ID)));
        Customer.setOwner(cursor.getString(cursor.getColumnIndex(DBHelper.OWNER)));
        Customer.setDirector(cursor.getString(cursor.getColumnIndex(DBHelper.DIRECTOR)));
        Customer.setGroupcompany(cursor.getString(cursor.getColumnIndex(DBHelper.GROUP_COMPANY)));
        Customer.setCapacity(cursor.getString(cursor.getColumnIndex(DBHelper.CAPACITY)));
        Customer.setOrderestimate(cursor.getString(cursor.getColumnIndex(DBHelper.ORDERESTIMATE)));
        Customer.setComplainer(cursor.getString(cursor.getColumnIndex(DBHelper.COMPLAINER)));
        return Customer;
    }

and this error in log cat
03-04 09:53:01.805: V/info(7604): The getString cus1
03-04 09:53:01.805: V/info(7604): The setLatLng toko maju jaya,alam sutera,Banten,Warda,02153120019,toko@gmail.com,warda,warda,IMS Group,1000
03-04 09:53:01.805: W/dalvikvm(7604): threadid=1: thread exiting with uncaught exception (group=0x41610450)
03-04 09:53:01.815: E/AndroidRuntime(7604): FATAL EXCEPTION: main
03-04 09:53:01.815: E/AndroidRuntime(7604): java.lang.NullPointerException
03-04 09:53:01.815: E/AndroidRuntime(7604):     at ims.app.mobileorder.FVPI.onCreateView(FVPI.java:151)
03-04 09:53:01.815: E/AndroidRuntime(7604):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
03-04 09:53:01.815: E/AndroidRuntime(7604):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)

A: Try this way (the changes are marked)
BTW instanciating a new object and naming it the same thing as the class itself is not good practice, may lead to major errors along the way
The main problem in your code was that and the fact that you were receiving a String called "customerid" but in your cursor you search for this "cus1"
public Customer getCustomer(String customerid){
    Customer customer = new Customer();  //<--
    Cursor cursor = database.query(DBHelper.CUSTOMER, allCustomer, DBHelper.CUSTOMER_ID +"=" + customerid, null, null, null, null); //<--
    cursor.moveToFirst();
    customer = cursorToCustomer(cursor); //<--
    cursor.close();
    return customer; //<--
}


text:
Q: Should we compare 'sub' claim in Access Token and ID Token? If we get Id token and access token like below in an OIDC flow:
Id token:
{
 "iss": "https://server.example.com",
 "sub": "24400320",
 "aud": "s6BhdRkqt3",
 "nonce": "n-0S6_WzA2Mj",
 "exp": 1311281970,
 "iat": 1311280970,
 "auth_time": 1311280969,
 "acr": "urn:mace:incommon:iap:silver"
 "amr": ["mfa", "pwd","otp"]
}

Access token:
{
    "iss": "https://cas.nhs.uk",
    "sub": "https://fhir.nhs.uk/Id/sds-role-profile-id"|[SDSRoleProfileID]",
    "aud": "https://provider.thirdparty.nhs.uk/GP0001/STU3/1",
    "exp": 1469436987,
    "iat": 1469436687,
    "reason_for_request": "directcare",
    "requested_scope": "patient/*.read",
    "requesting_system": "https://fhir.nhs.uk/Id/accredited-system|[ASID]",
    "requesting_organization": "https://fhir.nhs.uk/Id/ods-organization-code|[ODSCode]",
    "requesting_user": "https://fhir.nhs.uk/Id/sds-role-profile-id"|[SDSRoleProfileID]"
}

Is it a valid assumption that the 'sub' claim from Id token should match with the 'sub' claim in the Access token? Or are they both separate representations?
Do we even perform such validations at resource server to make sure both of them form a pair and are issued for the same user session?

A: Per Okta's documentation, the 'sub' claim in the access token is, by default, either the user's ID (if using an OAuth flow with a user scope available, like Authorization Code flow) in Okta OR the application's client ID (if using Client Credentials flow) in Okta. However, if you are using a custom authorization server, the value for 'sub' can be configured.
Similarly, the 'sub' claim in the ID token will be the user's ID in Okta. Unlike the access token, this value cannot be modified as OIDC standard requires that this value be locally unique within the issuer.
Why would your resource server interact with the ID token? ID tokens are used for Authentication use cases, while access tokens are used for Authorization use cases, as mentioned here: https://developer.okta.com/docs/guides/validate-access-tokens/go/overview/#access-tokens-vs-id-tokens. If you are looking to protect a resource server with OAuth tokens, you will want to rely on the access tokens.


text:
Q: Periodic billiard paths in hyperbolic triangles It is a theorem of Masur that all rational triangles in the Euclidean plane posses a periodic billiard path,
one obeying the reflection law that the angle of incidence equals the angle of reflection. A rational triangle has angles that are rational multiples of $\pi$.
It remains an open question of whether all triangles have a periodic billiard path.

Q. Is there some analogous theorem for hyperbolic triangles in the hyperbolic plane?

A billiard path in a hyperbolic triangle consists of geodesics which reflect
from the sides of the triangle by the same reflection law. Here is a possible start of
a billiard path inside a triangle drawn in the Poincare half-plane model,
where the geodesics are circular arcs and vertical line segments:

Is there some analog of the Euclidean rational angle condition that yields a theorem for hyperbolic triangles?

A: If the triangle is a fundamental domain for a discrete group, a periodic orbit corresponds to a closed geodesic in the quotient surface, which gives you boat-loads of periodic orbits (to be precise, $\sim \exp(L)/L$ of them of length bounded above by $L.$ I think that if all the angles are rational, the triangle is a fundamental domain for a cone-metric, and while a lot of the closed geodesics will go through the vertices, an entropy computation (that is, the set of geodesics passing through the vertices have smaller entropy than the entire geodesic flow) will give you a similar result.


text:
Q: Using imaplib to get headers of emails? Here is my code:
    conn = imaplib.IMAP4_SSL('imap.gmail.com')
    conn.login('username', 'password')
    conn.select()
    typ, data = conn.search(None, "ALL")
    parser1 = HeaderParser()
    for num in data[0].split():
        typ, data = conn.fetch(num, '(RFC822)')
        header_data = str(data[1][0])
        msg = email.message_from_string(header_data)
        print(msg.keys())
        print(msg['Date'])

Why am i getting "[]" for the printout of msg.keys() and "None" for the msg['Date']. No error messages. However, if i comment out the last 4 lines of code, and type print(data), then all the headers get printed? Im using python 3.4

A: conn.fetch returns tuples of message part envelope and data. For some reason -- I'm not sure why -- it may also return a string, such as ')'. So instead of hard-coding data[1][0], it's better (more robust) to just loop through the tuples in data and parse the message parts:
typ, msg_data = conn.fetch(num, '(RFC822)')
for response_part in msg_data:
    if isinstance(response_part, tuple):
        msg = email.message_from_string(response_part[1])

For example,
import imaplib
import config
import email

conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login(config.GMAIL_USER2, config.GMAIL_PASS2)
try:
    conn.select()

    typ, data = conn.search(None, "ALL")
    print(data)
    for num in data[0].split():
        typ, msg_data = conn.fetch(num, '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                part = response_part[1].decode('utf-8')
                msg = email.message_from_string(part)
                print(msg.keys())
                print(msg['Date'])
finally:
    try:
        conn.close()
    except:
        pass
    finally:
        conn.logout()

Much of this code comes from Doug Hellman's imaplib tutorial.


text:
Q: Loading language model twice in Rasa training? Large amount of temporary memory usage We have the following config.yml file for training a Rasa bot with rasa OS:
language: "../../language_models/nb_core_news_lg"
recipe: default.v1

# Read the following docs on how to fine-tune a model using config.
# https://rasa.com/docs/rasa/tuning-your-model#component-lifecycle
pipeline:

  ## Required pipeline components ##
  - name: SpacyNLP
    # note: this path is relative to ./live-bots/bot_name, where it's imported.
    model: "../../language_models/nb_core_news_lg"
    case_sensitive: False

On running the model (using rasa shell for example), then the following output is seen:
2022-07-27 10:43:46 INFO     root  - Starting Rasa server on http://0.0.0.0:5005
2022-07-27 10:43:48 INFO     rasa.core.processor  - Loading model models/20220725-101216-quick-game.tar.gz...
2022-07-27 10:43:49 INFO     rasa.nlu.utils.spacy_utils  - Trying to load SpaCy model with name '../../language_models/nb_core_news_lg'.
2022-07-27 10:43:54 INFO     rasa.nlu.utils.spacy_utils  - Trying to load SpaCy model with name '../../language_models/nb_core_news_lg'.

This process however requires about 2Gb of RAM. This is strange as the Rasa model 20220725-101216-quick-game.tar.gz only takes up about 50Mb of data, and the language model nb_core_news_lg takes up about 600Mb of data. Where is the extra ~1.3Gb of data coming from? Am I loading in the model twice in the config.yml file?


text:
Q: Can I call a block inside a block, with both blocks being inside a method in iOS? In my iOS project i call a method that contains 2 blocks say A & B.
Both blocks perform 2 different network calls, A goes first and based on some network response, executes block B. I've done so for tidiness since both do a lot of stuff & I've seen this work in my project but I'm not sure if it is correct to do so. Some illustration:
// somewhere in code
...
[self methodThatContainsTwoBlocks];
...

- (void)methodThatContainsTwoBlocks {

    Block B ^(responseFromSingletonOperation) {
       // do another network operation
       [MyNetworkManagerSingleton performAnotherOperationAsynchronouslyWithCompletion:^{
       // call some method when done
       [self wereDone];
       }
    }

    [MyNetworkManagerSingleton performAnOperationAsynchronouslyWithCompletion:^{
      // do a network operation
      // call block B with response
      B(responseFromNetworkOperation);

    }
}

The phrasing of my question may not be correct since the networking singleton instance takes a completion block, hence my saying, two blocks. I hope the illustration makes my question clearer though as I've only just started iOS programming and still dabbling my way with blocks since senior devs recommend them a lot.
Thanks.


text:
Q: google map markers infowindows with style I try to make the map that has many markers and each has itsown infowindow. I want infowidow display onload and since there're many markers so original infowindow will block the others marker, so I want infowindow with style like in the top one in http://hadeerfolio.com/map/ref.php but when I try to do that then it becomes like this http://hadeerfolio.com/map/ every infowindow has the same content. Please advise Thankyou
Here's the code for first link
<!DOCTYPE html>

<title>Creating and Using an InfoBox</title>

InfoBox as an easily customizable replacement for an InfoWindow. Click on the marker to see the infobox generated with custom html & css.

        contents.

and this one is for second link
    <!DOCTYPE html>

<title>Creating and Using an InfoBox</title>

InfoBox as an easily customizable replacement for an InfoWindow. Click on the marker to see the infobox generated with custom html & css.

        content

        content1

        content2

        content3

        content4

        content5


text:
Q: How to mark particular dates in react-calender How do I highlight specific Dates in react-calendar?
This is my code:
<Calendar
    style={{ height: 500 }}
    onChange={this.onChange}
    value={this.state.date}
    tileContent={d}
    hover={'2020-02-29'}

    tileDisabled={({ date }) => date.getDay() === 0}

    minDate={
        new Date()
    }
></Calendar>

A: I solved the issue........I modified my code
CSS code
  .highlight {
                color:red;
             }

I have created an array of multiple dates
const mark = [
      '04-03-2020',
      '03-03-2020',
      '05-03-2020'
  ]

And finally, the calendar will look like this
<Calendar
    style={{ height: 500 }}
    onChange={this.onChange}
    value={this.state.date}
    tileClassName={({ date, view }) => {
      if(mark.find(x=>x===moment(date).format("DD-MM-YYYY"))){
       return  'highlight'
      }
    }}

    tileDisabled={({ date }) => date.getDay() === 0}

    /*maxDate={new Date(2020, 1, 0)}</div>*/
     minDate={
      new Date()
    }
  >
</Calendar>

Output

A: Here is a common way to find out how to adjust styles with some libs which you are not familiar with.
If you look at the DOM tree, you would find each date button have class like below
<button class="react-calendar__tile react-calendar__month-view__days__day ...">
...
</button>

By change the style of it, we find that's the element we want to handle.

Notice the className react-calendar__tile
If we checkout their document by searching that class name's tile. You would find:

tileClassName
Class name(s) that will be applied to a given calendar item (day on month view, month on year view and so on).

By providing css class to it, you can customize your styles.
For example, make it blue
<Calendar
  tileClassName="content"
  ...
/>

.content {
  font-size: 20px;
  color: blue;
}

You can try it yourself here

A: You are using react-calendar. You can highlight a date very easily.

*

*create a class highlight (name can be anything).

*Import that style file (.css or .scss)

*It have a props called tileClassName. Send a callback like below.
    <Calendar
      tileClassName={({ date, view }) => {
       // date will return every date visible on calendar and view will view type (eg. month)
       if(// your_condititon ){
         return 'highlight'; // your class name
        }

      }}
      onChange={this.onChange}
      value={this.state.date}
    />

A: This will helps you.Working code source code
Demo:evenfy

Code:
dateArray=[{date:"2021-06-11T09:47:17.456000Z",colorName: "pink"},{date:"2021-06-12T09:47:17.456000Z",colorName: "blue"}.{date:"2021-06-16T09:47:17.456000Z",colorName: "blue"}]

  <Calendar
    tileClassName={({ activeStartDate, date, view }) => this.setClass(date)}
  />

setClass = (date) => {
const dateobj =
  dateArray.find((x) => {
    return (
      date.getDay() === new Date(x.date).getDay() &&
      date.getMonth() === new Date(x.date).getMonth() &&
      date.getDate() === new Date(x.date).getDate()
    );
  });
return dateobj ? dateobj.colorName : "";}


text:
Q: send remote shell command and retrieve its output Because I am unable to find a library that does the following I started heading out to write my own. I'm unable to find a solution for some problems, though, and hope that here maybe someone has a suggestion.
What I want is this. I send a normal shell command like ls -al <some path> and I want its output (stdout and stderr) in the same fashion and order as it would appear in my terminal emulator when writing that command. The catch is, that I don't want to run this shell command on the computer I'm currently using, but remotely via ssh or serial connection. To put it another way, when calling ls -al <some path> 2>&1 >/tmp/out I want to remotely receive the contents of /tmp/out without interruption or changes.
The problem is, with the serial connection always, with the ssh connection depending on your choice of library, that you get terminal command chars like \x1b[K mixed into your output. I am currently unable to find what exactly is creating these commands, why nothing is consuming them already, and I also don't know how I would go about consuming all of them myself (there are a lot, naive approaches won't work).
Why is it a problem to get special characters in your output? Well often you want to compare in your python code if the output has a string ala if expected_output == output, or at least use regular expressions. But there is nothing regular about when and why these characters appear. Sometimes a very simple command like ls -al <something> might result in the whole ssh connection breaking down (supposely because of these characters, but at least for sure because I don't know enough about all this to even understand what's the problem).
How would you go about solving the ultimate goal of sending commands remotely and receiving their output? How would you solve one of the mentioned subproblems (ssh connection that speaks to me like I would be a terminal, consuming randomly appearing special characters without interpreting them, etc)?
PS: There are many things I've already tried, but while writing I found them too many to list them all here. Nothing led to a desired end result, though. This really is a quite complex problem, especially because there seem to be things involved that are not traceable (like how many (pseudo-)terminals are actually involved) and others were never documented (some of the terminal handling seems to come from a time, where an actual typewriter was connected to the computer).

A: You already have this type of library.Try
Pexpect.
You just need to spawn a pexpect child by making a ssh connection to the computer you want to make connection to.Then you can send commands and see ouput using .before functionality.
Example:
child = pexpect.spawn('ssh admin@192.168.33.40')
child.expect ('Password:')
child.sendline (mypassword)
child.expect('#') # or expect `$`.
child.sendline('<your command>')
child.expect('#')
print child.before

Ref:http://pexpect.sourceforge.net/pexpect.html
P.S there's also Paramiko for the same though i havent used it.


text:
Q: Removing link from :before items in menu So I have the following code:

LINK 1

LINK 2

LINK 3

Or if you prefer:
https://jsfiddle.net/f64z4tp8/1/
As you can see I have three links, and in between are an icon (star). However, I would like it so that the stars (before items) are not links. Can this be done ?

A: Your markup is incorrect: you cannot nest other elements except for
 directly within
 (or
 too, for the sake of completeness). If you update your markup to reflect that changes, i.e.:

...

and slightly modify your selectors by changing this:
.menu ul a:not(:first-child):before

...to this:
.menu ul li:not(:first-child):before

and you are good to go:

.menu {
  padding: 30px 50px;
  padding-bottom: 0px;
}

.menu ul {
  list-style-type: none;
}

.menu ul li {
  display: inline-block;
}

.menu ul a {
  text-transform: uppercase;
  font-size: 20px;
}

.menu ul li:not(:first-child):before {
  padding-right: 15px;
  padding-left: 15px;
  content: '\2605';
}

LINK 1

LINK 2

LINK 3

A: You must change html code,  a element must be inside li element.
Like this:

LINK 1

and also
:before for li

 .menu {
        grid-area: menu;
        justify-self: right;
        align-items: center;
        padding: 30px 50px;
        padding-bottom: 0px;
}

.menu ul {
  list-style-type: none;
  font-family: 'LemonReg', sans-serif;
}

.menu ul a {
  display: inline-block;
  color: $yellowish;
  text-transform: uppercase;
  font-size: 20px;
}

.menu ul li {
  display: inline-block;
  color: $yellowish;
  text-transform: uppercase;
  font-size: 20px;
}

.menu ul li:not(:first-child):before {
  padding-right: 15px;
  padding-left: 15px;
  content: '\2605';
  color: blue;
}

LINK 1

LINK 2

LINK 3

A: In order to achieve this you'll need to add the stars outside of the list links. You should also follow the HTML specs as much as possible, where   are not valid
 child elements.
So the quickest solution would be something like this:
https://jsfiddle.net/f64z4tp8/8/
HTML:
You can fix the HTML structure and use it according to the official specs by making the  elements children of the
 items, like so:

LINK 1

LINK 2

LINK 3

CSS:
Since you changed the HTML structure, you'll also need to update the CSS selectors ensure you're still styling the stars and list items correctly, so change the rules that target .menu a li to just .menu li or just .menu a.
For example, on the selector where the star is added, change from .menu ul a to .menu ul li, ending up with something like this:
.menu ul li:not(:first-child):before {
  padding-right: 15px;
  padding-left: 15px;
  content: '\2605';
  color: $primaryRed;
}

EXAMPLE SOLUTION:

.menu {
  grid-area: menu;
  justify-self: right;
  align-items: center;
  padding: 30px 50px;
  padding-bottom: 0px;
}

.menu ul {
  list-style-type: none;
  font-family: 'LemonReg', sans-serif;
}

.menu ul a {
  display: inline-block;
  color: $yellowish;
  text-transform: uppercase;
  font-size: 20px;
}

.menu ul li {
  display: inline-block;
  color: $yellowish;
  text-transform: uppercase;
  font-size: 20px;
}

.menu ul li:not(:first-child):before {
  padding-right: 15px;
  padding-left: 15px;
  content: '\2605';
  color: $primaryRed;
}

LINK 1

LINK 2

LINK 3

A: I've added display:inline-block; to the .menu ul a:not(:first-child):before css class. At this point the text-underline goes away and the stars become red.
This is because the CSS specs say:

When specified on or propagated to an inline element, it affects all the boxes generated by that element, and is further propagated to any in-flow block-level boxes that split the inline (see section 9.2.1.1). […] For all other elements it is propagated to any in-flow children. Note that text decorations are not propagated to floating and absolutely positioned descendants, nor to the contents of atomic inline-level descendants such as inline blocks and inline tables.

A:

.menu {
  padding: 30px 50px;
  padding-bottom: 0px;
}

.menu ul {
  list-style-type: none;
}

.menu ul li a {
  display: inline-block;
  text-transform: uppercase;
  font-size: 20px;
}

.menu ul li a {
  display: inline-block;
  text-transform: uppercase;
  font-size: 20px;
}

.menu ul li:not(:first-child):before {
  padding-right: 15px;
  padding-left: 15px;
  content: '\2605';
}

LINK 1

LINK 2

LINK 3

A: Put as CSS selector:
.menu ul a:not(:first-child):before {
  padding-right: 15px;
  padding-left: 15px;
  content: '\2605';

  text-decoration: none;
  pointer-events: none;
}

pointer-events: none; remove any pointer interaction with the ::before element.
text-decoration: none; remove any default UI effect like underline.


text:
Q: Java How to make "Static" variable name to be dynamic Suppose I have a Class Child
public class child{
  public static int age = 1;
}

And I am using class child static variable age in class School
public class school{
 int var_age;
  public school(){     //school constructor
   var_age = child.age;
 }
}

Value in age of class child could be any of these below depending on some logic:
public static int age = 1;
public static int age = 2;

How could i achieve this where should i apply that logic? Also it is mandatory for class school code to remain same.

A: You provided very little information about what kind of logic this would be, but in any case it should be inside the class Child. Depending on what kind of logic it is I would probably put it inside the constructor.

Suppose you have the following:
    public class Child(){
       public static int age = 1;

       public Child(){
       }
    }

    public class School(){
       int var_age;

       public School(){
          var_age = Child.age;
       }
    }

With this code the variable var_age in the class School will always be assigned to the same value. That would be 1 in this case. If you want to make it depend on your logic you will have to implement it somewher (in class Child, since you're not allowed to edit class School). There are two obvious ways to do this;

*

*First way of doing it - The Constructor-way:
public class Child(){
   public static int age = 1;

   public Child(){
      age = yourLogic(); // Assign age depending on your logic here!
   }
}

With this way of doing it, your variable age will have a default value, 1, and as soon as an object of type Child is being created, it will take on the value defined by your logic. Judging from your feedback however, what you probably need is the second version.

*

*The second way of doing it - The field-way:
public class Child(){
   public static int age = yourLogic(); // Assign age to logic here!

   public Child(){
   }
}

This way, the variable age will have the value defined by your logic as a default value, so even if no instance of class Child is being created. This is probably what you were looking for. However note:
Depending on how computationally complicated your logic is, this can be a very bad practice.

By the way, DO NOT confuse the java static with the antonym of "dynamic". static in a java sense merely means that the variable is bound to the type instead of the instance / Object. That means it can be accessed without having to call or create an instance of the surrounding class. If you want the opposite of dynamic, that would be final in java.


text:
Q: Linking pthread disables lock-free shared_ptr implementation The title pretty much conveys all relevant information, but here's a minimal repro:
#include <atomic>
#include <cstdio>
#include <memory>

int main() {
    auto ptr = std::make_shared<int>(0);
    bool is_lockless = std::atomic_is_lock_free(&ptr);
    printf("shared_ptr is lockless: %d\n", is_lockless);
}

Compiling this with the following compiler options produces a lock-free shared_ptr implementation:
g++ -std=c++11 -march=native main.cpp

While this doesn't:
g++ -std=c++11 -march=native -pthread main.cpp

GCC version: 5.3.0 (on Linux, using libstdc++), tested on multiple machines that should have the necessary atomic instructions to make this work.
Is there any way to force the lock-free implementation (I'd need the lock-free version, regardless of performance)?

A: If you use shared_ptr in a threaded environment, you NEED to have locks [of some kind - they could be implemented as atomic increment and decrement, but there may be places where a "bigger" lock is required to ensure no races]. The lockless version only works when there is only one thread. If you are not using threads, don't link with -lpthread.
I'm sure there is some tricky way to convince the compiler that you are not REALLY using the threads for your shared pointers, but you are REALLY in fragile territory if you do - what happens if a shared_ptr is passed to a thread? You may be able to guarantee that NOW, but someone will probably accidentally or on purpose introduce one into something that runs in a different thread, and it all breaks.

A: There are two separate things:

*

*Manipulation of the reference counter in the control block (or equivalent thing) is typically implemented with lock-free atomics whenever possible. This is not what std::atomic_is_lock_free tells you.

*

*libstdc++'s __shared_ptr is templated on the lock policy, so you can explicitly use
template<typename T>
using shared_ptr_unsynchronized = std::__shared_ptr<T, __gnu_cxx::_S_single>;

if you know what you are doing.

*std::atomic_is_lock_free tells you whether the atomic access functions (std::atomic_{store, load, exchange, compare_exchange} etc.) on shared_ptr are lock-free. Those functions are used to concurrently access the same shared_ptr object, and typical implementations will use a mutex.


text:
Q: buttons vs checkboxes behaviour in ipyvuetify different. Why? I am arranging some ipyvuetify components as follows:
import ipyvuetify as vue
vue.Col(children=[vue.Checkbox(label='A'),vue.Checkbox(label='C'),vue.Checkbox(label='D')])
#and
vue.Col(children=[vue.Btn(label='A', children=['A']),vue.Btn(label='CS', children=['C']),vue.Btn(label='D', children=['D'])])

the appear as follows:

Why is that so if both are columns (vue.Col) and only the checkboxes appear actually in a column?
thanks

A: The buttons are inline elements, not blocks. If you specify that these buttons should behave as HTML blocks, then they also display as column:
vue.Col(
    children = [
        vue.Btn(
            block=True,
            label='A',
            children=['A']
        ),
        vue.Btn(
            block=True,
            label='CS',
            children=['C']
        ),
        vue.Btn(
            block=True,
            label='D',
            children=['D']
        )
    ]
)


text:
Q: Twitter4j counting the number of tweets found Here's my method for finding a hashtag:
void getNewTweets()
{
  //try the search
  try
  {
    Query query = new Query(searchString);
    //get the last 50 tweets
    query.count(2);
    QueryResult result = twitter.search(query);
    tweets = result.getTweets();

    System.out.println(tweets);
  }
  //if there is an error then catch it and print it out
  catch (TwitterException te)
  {
    System.out.println("Failed to search tweets: " + te.getMessage());
    System.exit(-1);
  }
}

I'm using the Twitter4j library. How would I count the number of tweets found?

A: You can also use the QueryResult.getCount() function.
Query query = new Query(searchString);
QueryResult result = twitter.search(query);

int count = results.getCount();
System.out.println("tweet count: " + count);

A: Store the tweets in an ArrayList and fetch the size of the ArrayList to display the number of tweets.
ArrayList tweets = (ArrayList) result.getTweets();
System.out.println(tweets.size());


text:
Q: Can FileInfo.Length be cast as an integer? I am using FileInfo.Length in order to get the size of a file and then post it to a GoogleDoc. The problem is that I am getting negative values from FileInfo.Length....
I have looked around online for some solutions and can't find any other reason...besides the fact that FileInfo.Length should be a Long and I was casting it to an Int.....could this have something to do with it?
Here is my code:
                int size = (int)file.Length;
                string name = file.Name;
                googleBot.insertArchiveRow(name, size);
                progressBar.Value++;
                this.UpdateLayout();

Would casting cause me problems here?
Thanks!

A: Yes. Casting could cause you problems.
How big is the File?

"FileInfo.Length should be a Long and I was casting it to an Int....."

If greater than 2^31 - 1  then casting to an int could be negative....
e.g.
        long l = (long)Math.Pow(2, 31);
        int i = (int) l;
        Console.WriteLine("{0}", l);
        Console.WriteLine("{0}", i);

Prints:
2147483648
-2147483648

Bottom line: FileInfo.Length is a long , so treat it as such.

A: Avoid surprises like this and let the compiler generate code to perform error checking:
 int size = checked((int)file.Length);

You'll now get an OverflowException instead of a negative value.

A: Yeah, pretty easily, in fact...
int.MaxValue ==  2147483647 == 0x7FFFFFFF
int.MinValue == -2147483648 == 0x80000000

int.MaxValue is 2^31 - 1, so something like ~2GB in size; any file bigger than that would read as negative, until you cycled back around again, that is. :)


text:
Q: Qt no service found for - "org.qt-project.qt.mediaplayer" I'm using Ubuntu 16.04.
When I'm using Qt Creator with Qt 5.9.2, nothing goes wrong.
However, after I switch to Qt 5.10.0 and use static linking, the error appears:
First, qmake outputs several lines of Empty filename passed to function.
Then, after make, the application outputs several lines of defaultServiceProvider::requestService(): no service found for - "org.qt-project.qt.mediaplayer" and crashes.
Is there any solution to it?
Thanks in advance.

A: Doing sudo apt-get install libqt5multimedia5-plugins worked for me.


text:
Q: @JoinFormula and @OneToMany definition - poor documentation I have two questions concerning @JoinFormula and @OneToMany annotations:

*

*How can I limit the number of result with @JoinFormula and @OneToMany annotations?

*How can I define that id in expression author = id refers to Author.id?
Author {

    @Id
    private Long id;

    @OneToMany
    @JoinFormula(value = "SELECT a FROM Article a WHERE author = id AND schedule < CURRENT_TIMESTAMP()") // limit = 15
    private List<Article> pastArticles;
}

Like this, I keep having the pastArticles empty, even when I remove the schedule < part of the clause.
Thanks!

A: you'd be better off using the @Where annotation to limit the results

A: Answer 1 :
@Size(max=10)
private List<Comment> commentList;

Answer 2 :(just example like that)
public class A{

    @Id
    @GeneratedValue
    private Integer id;

    private String uuid;

    ...
  }

other class
public class B{
      @Id
      @GeneratedValue
      private Integer id;

      private String uuidOfA;

  @ManyToOne
  @JoinColumnsOrFormulas({
  @JoinColumnOrFormula(formula=@JoinFormula(value="(SELECT a.id FROM A a WHERE a.uuid = uuid)", referencedColumnName="id")),
  @JoinColumnOrFormula(column = @JoinColumn("uuidOfA", referencedColumnName="uuid"))
})

     private A a;
}


text:
Q: Extend a class + new parameter Ok, here's the issue!
I have a class GetStuff
public class GetStuff {

   public GetStuff(String data) {
       // stuff
   }

}

In this class I have a method getMyStuff() which calls a second method:
getAllMyStuff();

Now, I want to extend my class so I'll make a:
public class GetSecondStuff extends GetStuff {

      public GetSecondStuff(String data, int newData) {
           super(data);
      }

}

in this 2nd class I will override my getAllMyStuffMethod, but inside this method I'll need to use the newData parameter from the constructor:
private String getAllMyStuffMethod() {
   if (newData==0) // do something
}

How can I use here newData ? :(

A: Just create a new field in the GetSecondStuff class and assign it in the constructor. Then you can use newData in the overriden method.

A: save the variable newData in an instance-variable. with this u have access to it in the class GetSecondStuff.
something like:
public class GetSecondStuff extends GetStuff {
    private int newData;

    public GetSecondStuff(String data, int newData) {
      super(data);
      this.newData = newData;
    }

    private String getAllMyStuffMethod() {
      if (this.newData==0) // do something
    }
  }

Edit:
In one of the comments i read that u want to use a subclass-parameter in the super-class. so can u tell me why the new parameter is not in the super-class?

A: the class extending the first one may have its own properties, use them.
public class GetSecondStuff extends GetStuff {
  int _newData
  public GetSecondStuff(String data, int newData) {
       super(data);
       _newData = newData;
  }

   private String getAllMyStuffMethod() {
     if (_newData==0) // do something
   }
}

A: public class GetStuff {
    public GetStuff(String data) {
        System.out.println(data);
    }
}

public class GetSecondStuff extends GetStuff {
    private int newData;

    public GetSecondStuff(String data, int newData) {
        super(data);
        this.newData = newData;

        data = "GetSecondStuff";
        System.out.println(data);

        System.out.println(getAllMyStuffMethod());

    }

    private String getAllMyStuffMethod() {
        String ret=null;
          if (this.newData==0)
              ret="0";
          else
              ret="1";

        return "new data : "+ret;
    }
}

public class main {

    public static void main(String[] args) {

        GetSecondStuff gf2 = new GetSecondStuff("GetStuff",1);
    }

}

OUTPUT :
GetStuff
GetSecondStuff
new data : 1


text:
Q: How do I compare doubles using JUnit and Hamcrest? I'm writing a unit test using JUnit and Hamcrest. I have been comparing double values using:
assertThat(result, is(0.5));

However, I'm now needing to compare calculated values and I don't want to have to compare against the full double value. Instead, I want to compare for closeness.
I've discovered a class called IsCloseTo but I'm not sure how to use it in an assertThat and I can't find any examples online.
What's the correct syntax to do something like the following?
// I can't do this as I need to know what methods/classes whatever I should be using
// isCloseTo doesn't exist.
assertThat(result, isCloseTo(0.5, 0.1));

A: You can make this read better if you use
assertThat(actual, is(closeTo(expected, delta)));

with
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.is;

A: You should be able to call Matchers.closeTo(double, double). With a static import, it looks like:
assertThat(result, closeTo(0.5, 0.1));

A: Just worked it out, is actually returns an Is object, so all I needed to do was:
assertThat(result, new IsCloseTo(0.5, 0.1));

The answer from nickb is better though.


text:
Q: Selenium extensions: "blocking" commands Is it possible in selenium to write blocking commands?
I want to make a "clickAndWaitForAjax" command. It will click a button and wait until a div is filled with text from the server.
It is clear to me this can be done with two commands, but can it be done with one? How?

A: The best practise for this is to wait for elements on the page to be in the div. You can use a number of different commands like waitForElementPresent, waitForElementVisible,etc or you can write some JavaScript to check if the element in the DOM and use waitForCondition.
These are standard Selenium commands and can be ported to a programming language of your choice if you wish to run your tests running Selenium RC

A: If you write your scripts as JUnit tests, then it's all just Java code. You can easily write a single method that calls one, two, or a whole lot of different selenium methods. Or you could use your favourite language and testing framework.
This makes it much easier for testing complex systems.
See Selenium RC documentation for details.


text:
Q: Overlapping periods - Merging in a continous time series Recently i am dealing with a overlapping intervals problem.
I have the following situation:
Input:
I have one DB table which contains monthly data like that:
StartDate   |   EndDate   |  Value

31.07.2010  |  31.08.2010 |  4500
31.08.2010  |  30.09.2010 |  6500

And one table which contains from - to data like that:
StartDate   | EndDate    |  Value

16.08.2010  | 29.09.2010 |  9500

Output: New table with continous period series like that
StartDate   | EndDate    |  Value

31.07.2010  | 15.08.2010 |  4500
16.08.2010  | 29.09.2010 |  9500
30.09.2010  | 30.09.2010 |  6500

How you would solve such problem?
My idea would be to make an union of the two tables and sort them by startdate.
Identify the overlapping periods and adjust them.
Is there already an algorithm which i can use for that purpose? Or someone approached already a similar problem?
Thanks,
Patric

A: I think, in general, this problem could be solved by selecting all possible start dates into one dataset, and then for each start date get date from next row as end date of the period, something like this:
;with cte(StartDate) as (
    select distinct StartDate from Table1
    union
    select distinct EndDate from Table1
    union
    select distinct StartDate from Table2
    union
    select distinct dateadd(dd, 1, EndDate) from Table2
), cte2 as (
    select
        StartDate,
        row_number() over(order by StartDate asc) as rn
    from cte
)
select
    c.StartDate,
    case
        when c2.rn = max(c2.rn) over() then c2.StartDate
        else dateadd(dd, -1, c2.StartDate)
    end as EndDate
from cte2 as c
    inner join cte2 as c2 on c2.rn = c.rn + 1

sql fiddle demo
This code is for SQL Server, and the answer is also depends on if it's possible for end of period to be equal to start of next period or not, but you can get general idea.


text:
Q: Printing a List with Newlines in TKinter Popup I've got this list:
runner.sublist = [["one","two","three"],["red","black","blue]]

and this class definition
class popupWindow(object):
    def __init__(self, master, txt):
        top = self.top = Toplevel(master)
        self.l = Label(top, text=txt)
        self.l.pack()
        self.b = Button(top, text='Fine....', command=self.cleanup)
        self.b.pack()

def popup(self,txt):
    self.w=popupWindow(self.master, txt)
    self.master.wait_window(self.w.top)

And I'm trying to get this button to make a popup window that has the runner.sublist list printed in the popup with newlines after every group of elements (one two three on the first line, red black blue on the second, etc.)
def print_it(op):
    out = '\n'.join(op)
    return out

class mainWindow(object):
    def __init__(self,master):
        self.master=master
        self.b2=Button(master,text="print value",command=lambda: self.popup(print_it(runner.sublist)))
        self.b2.pack()

However, this code returns the following error:
TypeError: sequence item 0: expected string, list found

Clearly, I'm passing a list where I should have a string, but I'm totally stumped as to why it's getting a list!  I've tried to coerce some of the values into strings at various places, but that had no luck.
Any ideas?  Thanks!

A: join can joins list of strings but not list of lists of strings.
(see: lambda: self.popup(print_it(runner.sublist)) )
'\n'.join( [["one","two","three"],["red","black","blue"]] ) # error

You have to change print_it(). For example:
def print_it(op):
    return '\n'.join( ' '.join(line) for line in op )

To get two lines
one two three
red black blue


text:
Q: Force checkout not working with Edit (link to edit item) column in SP2010 Could someone be so kind as to check the following in their 2010 environments.

*

*Create a doc library

*Turn on force check-out

*Turn on versioning.

*Add the "Edit (link to edit item)" column to the default view.

*Now upload a document and check it in.

*Use the Edit column to edit the properties.

You should see:

You must check out this item before making changes. Do you want to
  check out this item now?

Clicking OK, would normally check the document out and take you to the edit form (in a dialog in sp2010 if dialogs set to yes for library).
However in two environments of mine, nothing happens anymore!!!!
On live I tested tested a new library in an existing site, a new library in a new site, and an existing library in a migrated site (from 2007).
Strangely I found one document library in a migrated site which DOES STILL WORK but why this one library works is puzzling me!! The issue is new libraries don't work and that seems to confuse me more!
Again, I tried new libraries in two SharePoint environments and same behaviour.
Anyone?

A: I had the same problem on my environment. I found a solution for it - you need to edit the xsl template for the 'Edit' column.
Here is part of the original code:
<xsl:when test="$hasRight = '1'">

</xsl:when>

And here is the one I am using:
<xsl:when test="$hasRight = '1'">

</xsl:when>

Notice how the 5th parameter in the javascript function EditItemWithCheckoutAlert in my version is $thisNode/@FileRef.urlencodeasurl while the orginal is just $thisNode/@FileRef.urlencode
Here is the difference in rendering (example):
original:   %2FLibrary%2FBSORU%2FMDM%2Fsb%20avatar%2Epng
my version: /Library/BSORU/MDM/sb%20avatar.png
I did not test this very thoroughly, but it worked for a few check-ins/outs. Hopefully this will work on your environment too.
EDIT: I saw this solution had some problems with non-latin characters and changed the parameter to just $thisNode/@FileRef - this doesn't encode the location or filename.


text:
Q: Android SortedList drag and re Order Items throwing IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolde I'm facing an issue with recycler-view implementation with sortedList.I need to implement the drag and re-order feature for this recycle view, I used the " ItemTouchHelper.Callback()" to handle the up/down move
 class SimpleItemTouchHelperCallback(private val mAdapter: ItemTouchHelperAdapter) :
        ItemTouchHelper.Callback() {

    override fun onMove(
            recyclerView: RecyclerView,
            source: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            if (source.itemViewType != target.itemViewType) {
                return false
            }

            val fromPosition = source.adapterPosition
            val toPosition = target.adapterPosition
            dragFrom = fromPosition
            dragTo = toPosition

            Timber.d(">> SimpleItemTouchHelperCallback ->>> onMove fromPosition = $fromPosition | toPosition = $toPosition")

            // Notify the adapter of the move
            mAdapter.onItemMove(dragFrom, dragTo)
            return true
        }

        override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {

            super.clearView(recyclerView, viewHolder)
            viewHolder.itemView.alpha = ALPHA_FULL
            if (viewHolder is ItemTouchHelperViewHolder) {
                // Tell the view holder it's time to restore the idle state
                val itemViewHolder = viewHolder as ItemTouchHelperViewHolder
                itemViewHolder.onItemClear()

                // To detect when an interaction with an element is over
                if (dragFrom != -1 && dragTo != -1 && dragFrom != dragTo) {
                    mAdapter.dragAndDropCompleted(dragFrom, dragTo)
                }
                dragFrom = -1
                dragTo = -1
            }
        }

    }

//===========
class ShoppingListRecyclerListAdapter(
    private val onItemClickListener: OnItemClickListener,
    private val userCheckedInToStore: Boolean
) : RecyclerView.Adapter<BaseShoppingListViewHolder>(), ItemTouchHelperAdapter {

    private var sortedItemList: SortedList<ShoppingListEntry>

 override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
  var dragFromItem = sortedItemList[fromPosition]
        var dragToItem = sortedItemList[toPosition]

        if (dragFromItem is UnCheckedFreeTextItem && dragToItem is UnCheckedFreeTextItem) {

 val dragFromItemSortIndex = dragFromItem.freeTextShoppingItem.sortIndex
            val dragFromItemName = dragFromItem.freeTextShoppingItem.itemName

            dragFromItem.freeTextShoppingItem.sortIndex =
                dragToItem.freeTextShoppingItem.sortIndex

            dragToItem.freeTextShoppingItem.sortIndex = dragFromItemSortIndex

            dragToItem.modify = true
            dragFromItem.modify = true

            dragFromItem.freeTextShoppingItem.itemName =
                dragToItem.freeTextShoppingItem.itemName

            dragToItem.freeTextShoppingItem.itemName = dragFromItemName

            dragItemSet.add(dragToItem)
            dragItemSet.add(dragFromItem)

            sortedItemList.beginBatchedUpdates()
            //sortedItemList.recalculatePositionOfItemAt(fromPosition)
            sortedItemList.updateItemAt(fromPosition, dragFromItem)

            //sortedItemList.recalculatePositionOfItemAt(toPosition)
           sortedItemList.updateItemAt(toPosition, dragToItem)

             //sortedItemList.recalculatePositionOfItemAt(fromPosition)
             //sortedItemList.recalculatePositionOfItemAt(toPosition)
            //sortedItemList.updateItemAt(fromPosition, dragToItem)
            sortedItemList.endBatchedUpdates()

}

 }
}

Exception getting when user long press on an item and start Moving
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{c026f4 position=6 id=39, oldPos=6, pLpos:-1 scrap [attachedScrap]
tmpDetached no parent} androidx.recyclerview.widget.RecyclerView{1991c2a VFED.V... ......ID 0,364-1080,1980 #7f0a01db app:id/shoppingListView},
adapter:com.adingk.lib.ui.shoppinglist.ShoppingListRecyclerListAdapter@741fa1b, layout:androidx.recyclerview.widget.LinearLayoutManager@d2de7b8,
context:com.adingk.lib.ui.shoppinglist.ManageShoppingListActivity@76ea334
      at androidx.recyclerview.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5715)
      at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5898)
      at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
      at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
      at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
      at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
      at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
      at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
      at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3875)
      at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3639)
      at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4194)
      at android.view.View.layout(View.java:21927)
      at android.view.ViewGroup.layout(ViewGroup.java:6260)

A: Instead of using updateItemAt try to use notifyItemMoved(fromPosition, toPosition) which is method provided by RecyclerView.Adapter.
override fun onItemMove(fromPosition: Int, toPosition: Int) {
    notifyItemMoved(fromPosition, toPosition)
}


text:
Q: PHP: How can I detect incorrect number of arguments in a function? If I have the following class:
class MyClass
{
    public function hello($name)
    {
        echo 'Hello ' . $name;
    }
}

If I use the following code to call the function (the name of the function and parameters are determined based on user input):
$className = 'MyClass';
$func = 'hello';
$params = ['John', 'Another Param'];
$myClass = new $className();

$myClass->$func(...$params);

The function is called and the extra parameter is ignored. What I would like to do, is ensure that the number of parameters in $params matches that of the function and have and throw an ArgumentCountError if the number of arguments do not match.
I have been searching but have not found any solutions. How may I achieve this?


text:
Q: Infinite source rectangle to drawImage method Why do i always get this log, Infinite source rectangle to drawImage method, is this such an error or there's something wrong with the code algorithm. I don't really understand about this, and i can't find any useful information on google. Hope i can find the answer on this site.
sorry, this is my drawRect method :
- (void)drawRect:(NSRect)rect {
    // Drawing code here.

    // drawBackground
    [[NSColor colorWithCalibratedRed:0 green:0 blue:0 alpha:1.0] set];
    [NSBezierPath fillRect:[self bounds]];

    if (myCIImage != nil) {

        //Create the CIContext
        CIContext *context =  [[NSGraphicsContext currentContext] CIContext];

        //scale to fit in view rect
        CIImage *drawnImage;
        if (previewFilter == YES) {
            drawnImage = [previewImage imageByApplyingTransform:[self imageTransformToFitView]];
        } else {
            drawnImage = [myCIImage imageByApplyingTransform:[self imageTransformToFitView]];
        }

        // center in view rect
        NSRect viewBounds = [self bounds];
        CGRect sRect = [drawnImage extent];
        CGRect dRect = sRect;
        dRect.origin.x = viewBounds.origin.x + (viewBounds.size.width - sRect.size.width)/2;
        dRect.origin.y = viewBounds.origin.y + (viewBounds.size.height - sRect.size.height)/2;

        [context drawImage:drawnImage
                    inRect:dRect
                  fromRect:sRect];

    }

}

thanks -

A: I think that means the dimensions of sRect contain some infinite numbers.  Have you run this under the debugger and inspected the values in sRect?
Probably the transform you apply to the image is wrong.


text:
Q: Delivering data between two viewControllers via "NSKeyedArchiver " causes double "import" error? I am a new iOS developer. These days, I have been stuck in a problem : delivering data between two viewControllers via "NSKeyedArchiver " causes double "import", by which I mean both the two viewControllers import each other.

A: The simplest way to share/stored data, if you don't want to use the methods you mentioned above, is to use NSUserDefaults. This is a local store that you can use to save off your data to.  See docs here


text:
Q: Python split function shows some wrong result currently I am developing a program which helps user to adjust the significant figures. Hereby, I used following codes to split decimal numbers by [integer, ., decimal] format using split('.')
len_number1 = (str(number1)).split('.')

when I enter the value of 1.3333 it successfully separate numbers into ['1', '.', '3333'] but when I enter the value of 0.000043 it shows the result of ['4', '3e-05'] whereby I need to get the result of ['0', '.', '000043']
Is there any ways to solve such problem?

A: First, when you do str(0.43).split('.') you will get ['0','43'] not ['0','.', '43']. The problem is the casting function str(), because the string format of these decimal numbers, as @MarkMeyer said, is in a scientific notation, that means str(0.000043) will return you '4.3e-05'.
Even print(0.000043) will give you something like 4.3e-05 too. You can try something like this to replace that function:
import decimal

dec = decimal.Context()

dec.prec = 20  #this gives us a precition of 20 decimals

def num_to_str(n):

    dec1 = dec.create_decimal(repr(n))
    return format(dec1, 'n')

print(num_to_str(0.0000043).split('.'))
>>>['0','0000043']

If you want to get ['0','.', '0000043'], you could use insert(), since you will only add one '.' at index 1. You could try
num = num_to_str(0.0000043).split('.')
num.insert(1,'.')
print(num)
>>>['0','.', '0000043']

Checkout the documentation of decimal, repr() and split() for more info.


text:
Q: Adding evenlistener to header of div I have multiple eventlisteners to my div: dragstart, dragenter, dragover, dragleave, drop and dragend.
To attach them to my div, I use the body onload function:
function addListeners()
{
    var cols = document.querySelectorAll('#columns .column');
    [].forEach.call(cols, function(col) {
      col.addEventListener('dragstart', handleDragStart, false);
      col.addEventListener('dragenter', handleDragEnter, false);
      col.addEventListener('dragover', handleDragOver, false);
      col.addEventListener('dragleave', handleDragLeave, false);
      col.addEventListener('drop', handleDrop, false);
      col.addEventListener('dragend', handleDragEnd, false);
    });
}

but this code adds the eventlistener to the whole div. I only want the header of the div to respond to these events:

Now I can click on any part of the div and drag it, but I only want to be able to click on the black part (header) of the div to move it. The black part is a simple header in CSS.
HTML

ATextual information inside div A

BTextual information inside div B

CTextual information inside div C

A JSFiddle of my full page can be found here.
How can this be done?

A: You need to add EventListeners to your header elements.
but those event listeners will work only when your headers are draggable=true
so by adding EventListeners to the header and making it draggable=true you can start to drag it.
But there is one problem now, you don't want to drag just the header, but its entire content i.e its parent div. and you want to swap it with the  parentNode.innerHTML of the other header(upon which you are dropping).
so, you need to do this:

*

*add events to the header element,

*perform all the other operation i.e. grabbing and then swapping innerHTML on the parent of the header i.e. this.parentNode

*also when you perform the innerHTML swap, all the event listeners are lost,because now, the very draggable element is recreated, so you will have to call your event binding function addListeners() again.

working fiddle


text:
Q: get row with same id but different value and display different value into different label asp.net this work but i want to display if value exist, so user can see the value username and last_update in each label based on each process_id but they have same request_id. this code only display username and last_update for the one that based on username login only.how i can do that ?
 using(SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["MESTrans"].ConnectionString))
        {
            //bool exists = false;
            int exists;
            con.Open();

                foreach (GridViewRow row in GridView2.Rows)
                {

                    int req_id = Convert.ToInt32(GridView2.DataKeys[row.RowIndex].Values[0]);
                    using (SqlCommand cmd = new SqlCommand("select count(*) from [CutPanelConfirmation] where req_id=@req_id and process_id=@process_id", con))
                    {
                        cmd.Parameters.AddWithValue("@process_id", Session["process_id"].ToString());
                        cmd.Parameters.AddWithValue("@req_id", req_id);
                        exists = (int)cmd.ExecuteScalar();
                    }
                    if (exists > 0)
                    {
                        query = "select * from CutPanelConfirmation where req_id=@req_id and process_id=@process_id";
                        cmd = new SqlCommand(query, con);
                        cmd.Parameters.AddWithValue("@process_id", Session["process_id"].ToString());
                        cmd.Parameters.AddWithValue("@req_id", req_id);
                        SqlDataReader dr = cmd.ExecuteReader();

                       while (dr.Read())
                        {

                            if ((string)dr["process_id"] == "marker")
                            {

                                LabelNameMarker.Text = LabelNameMarker.Text + " " + dr[1].ToString();
                                LabelDateMarker.Text = LabelDateMarker.Text + " " + dr[3].ToString();

                            }
                            if ((string)dr["process_id"] == "fabric")
                            {
                                LabelNameFabric.Text = LabelNameFabric.Text + " " + dr[1].ToString();
                                LabelDateFabric.Text = LabelDateFabric.Text + " " + dr[3].ToString();
                            }
                            if ((string)dr["process_id"] == "cutting")
                            {
                                LabelNameCutting.Text = LabelNameCutting.Text + " " + dr[1].ToString();
                                LabelDateCutting.Text = LabelDateCutting.Text + " " + dr[3].ToString();
                            }
                            if ((string)dr["process_id"] == "SPP")
                            {
                                LabelNameSPP.Text = LabelNameSPP.Text + " " + dr[1].ToString();
                                LabelDateSPP.Text = LabelDateSPP.Text + " " + dr[3].ToString();
                            }
                            if ((string)dr["process_id"] == "kitting")
                            {
                                LabelNameKitting.Text = LabelNameKitting.Text + " " + dr[1].ToString();
                                LabelDateKitting.Text = LabelDateKitting.Text + " " + dr[3].ToString();
                            }
                            if ((string)dr["process_id"] == "sew")
                            {
                                LabelNameSew.Text = LabelNameSew.Text + " " + dr[1].ToString();
                                LabelDateSew.Text = LabelDateSew.Text + " " + dr[3].ToString();
                            }

                        }
                        dr.Close();

                    }

                con.Close();
            }
        }

A: posting [https://stackoverflow.com/users/7892938/nfh][NFH] answer
i just delete@process id from this query and it works as what i want! :
query = "select * from CutPanelConfirmation where req_id=@req_id and process_id=@process_id"; cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@process_id", Session["process_id"].ToString()); cmd.Parameters.AddWithValue("@req_id", req_id); SqlDataReader dr = cmd.ExecuteReader();


text:
Q: Equation with floor function How would one solve an equation with a floor function in it:
$$a - (2x + 1)\left\lfloor{\frac {a - 2x(x + 1)}{2x + 1}}\right\rfloor - 2x(x + 1) = 0$$
$a$ is a given and can be treated as a natural number, and all $x$ other than integers can be discarded. At least one non-trivial solution would be sufficient.
Maybe an algorithmic method could be used?

A: Rearranging we get,
$$\frac{a - 2x(x + 1)}{(2x + 1) } =\left\lfloor{\frac {a - 2x(x + 1)}{2x + 1}}\right\rfloor $$
This means,$\frac{a - 2x(x + 1)}{(2x + 1) }$ is an integer.
$$\frac{a - 2x(x + 1)}{(2x + 1) }=k$$
$$a=2xk+k+2x^2+2x$$
$$2x^2+2(k+1)x+k-a=0$$
Applying the quadratic formula,
$$x = \frac{-2(k+1)\pm\sqrt{4(k+1)^2-8(k-a)}}{4}$$
$a$ is known, now we substitute integers in place of $k$ to obtain solutions.


text:
Q: Getting a plot to show when plot function is imported into mainscript I made a simple function for a plot - it works, but when i import the function into my mainscript, it does not show before inside my "menu" while the while loop is running. Normally i use plt.show() but, we've made the plot with a pd.DataFrame. Any ideas?
def plotGrades(newGrades):

    t = newGrades['Final Grade'].value_counts().sort_index().plot("bar",title="Final grades",x="jfh")
    return t


text:
Q: Advice on simple exercise; dividing rational expression I'm looking into rational expressions to clarify some doubts that i have. I'm solving the exercises at the end of the chapter and I'm stuck with one of them. This is it:
$$\frac{(x-y)^2-z^2}{(x+y)^2-z^2}\div\frac{x-y+z}{x+y-z}$$
I have been solving several of this type by:
1.- Factoring out the largest common factor if possible.
2.- Factoring.
3.- Removing factors of 1.
In this case, i'm trying to find a way of solving this without expanding the hole thing, but i have not found the way jet.
I start by expanding both square binomials of the dividend.
$$\frac{x^2-2xy+y^2-z^2}{x^2+2xy+y^2-z^2}\div\frac{x-y+z}{x+y-z}$$
Then, multiplying the dividend by the reciprocal of the divisor and rewriting.
$$\frac{x^2-2xy+y^2-z^2}{x^2+2xy+y^2-z^2}\times\frac{x+y-z}{x-y+z}$$
$$({x^2-2xy+y^2-z^2})({x+y-z})\over({x^2+2xy+y^2-z^2})({x-y+z})$$
Expanding the expression and grouping i got
$$x^3 - x^2(y + z) - x(y - z)^2 + y^3 - y^2z - yz^2 + z^3 \over x^3 + x^2(y + z) - x(y - z)^2 - y^3 + y^2z + yz^2 - z^3$$
The problem is that i don't know what to do now.  I know that the result is:
$$\frac{x - y - z}{x + y + z}$$
I want to belive that there's an easy way from the beggining (to avoid expanding all the thing) but i would like your help.

A: Yuck. You seem to have missed a trick early on. Notice that $x^2 - y^2 = (x+y)(x-y)$. That should help out a lot - before you do anything like expand brackets.

A: Expanding the first term gives
$$
\frac{x^2-2xy+y^2-z^2}{x^2+2xz-y^2+z^2}.
$$
Now it easy to see that this is equal to
$$
\frac{x-y-z}{x+y+z}.
$$


text:
Q: Can I add comments to a pip requirements file? I'd like to add comments for a few packages in a pip requirements file. (Just to explain why that package is on the list.) Can I do this?
I'm imagining something like
Babel==0.9.5 # translation
CherryPy==3.2.0 # web server
Creoleparser==0.7.1 # wiki formatting
Genshi==0.5.1 # templating

A: Sure, you can, just use #
pip docs:

A line that begins with # is treated as a comment and ignored. Whitespace followed by a # causes the # and the remainder of the line to be treated as a comment.


text:
Q: IEnumerable to string delimited with commas? I have a DataTable that returns
IDs
,1
,2
,3
,4
,5
,100
,101

I want to convert this to single string value, i.e:
,1,2,3,4,5,100,101

How can i rewrite the following to get a single string
var _values = _tbl.AsEnumerable().Select(x => x);

A:  String.Join(
      ",",
      _tbl.AsEnumerable()
          .Select(r => r.Field<int>("ID").ToString())
          .ToArray())

A: Try this:
var _values = _tbl.AsEnumerable().Select(x => x);
string valueString = _values.ToList().Aggregate((a, b) => a + b);

A: You can use MoreLINQ extension
var singleString = _values.ToDelimitedString(",");

A: I had a similar issue with general Array type and i solved it as follows
string GetMembersAsString(Array array)
{
    return string.Join(",", array.OfType<object>());
}

Note that call OfType<object>() is mandatory.

A: var singleString = string.Join(",", _values.ToArray() );

A: Write an extension method such as
public static String AppendAll(this IEnumerable<String> collection, String seperator)
{
    using (var enumerator = collection.GetEnumerator())
    {
        if (!enumerator.MoveNext())
        {
            return String.Empty;
        }

        var builder = new StringBuilder().Append(enumerator.Current);

        while (enumerator.MoveNext())
        {
            builder.Append(seperator).Append(enumerator.Current);
        }

        return builder.ToString();
    }
}

and assuming the result of your previous expression is IEnumerable<String>, call:
var _values = _tbl.AsEnumerable().Select(x => x).AppendAll(String.Empty);

A: You can cheat with this:
String output = "";
_tbl.AsEnumerable().Select(x => output += x).ToArray();
// output now contains concatenated string

Note ToArray() or similar is needed to force the query to execute.
Another option is
String output = String.Concat(_tbl.AsEnumerable().Select(x=>x).ToArray());


text:
Q: I am trying to take user inputs and add them together then comparing them to a variable I made 4 classes.
first class
public void bust(String[] args) {

        @SuppressWarnings("resource")
        Scanner user_input = new Scanner(System.in);

        System.out.print("Enter your Bust Size: ");
        int bust_size1 = user_input.nextInt();

        int y = bust_size1;

        if (y>=33 & y<=34.5) {
            System.out.println("You are Small Bust" );
        } else if (y>=35 & y<37 ) {
            System.out.println("You are Medium Bust");
        } else if (y>=37 & y<=40.5) {
            System.out.println("You are Large Bust");
        } else {
            System.out.println("sorry you entered a incorrect number,");
        }
}

// all of the classes look similar
then my main class that takes these 3 classes together-
    public static void main(String[] args) {
        bust bustmain = new bust();
        hip hipmain = new hip();
        waist waistmain = new waist();

        bustmain.bust(args);
        waistmain.waist(args);
        hipmain.hip(args);
    }

What i am trying to achieve is this exactly: I want users to input their numbers for their bust size, waist, then hips. If they input a number such as 33, they will be in the small category, which i set the small category to a value such as 1. The values then will be added to determine what they will be.

A: Looks like you want to pass args to the functions
    bustmain.bust(args[0]);
    waistmain.waist(args[1]);
    hipmain.hip(args[2]);

and then
public void bust(int input) {

    int bust_size1 = input;

A: You either need your bust() method to return something, or store the input as a field in the class itself that can be accessed by your main.


text:
Q: number of tables in database always returns 1 everybody is suggesting to use SELECT COUNT(*) FROM information_schema.tables
if I do the following, I always get '1' returned:
$res=mysql_query("SELECT COUNT(*)
                  FROM information_schema.tables WHERE table_schema = 'usr_web275'");
$number_of_tables_in_database=mysql_num_fields($res);
echo $number_of_tables_in_database;

A: Do the following:
$res=mysql_query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'usr_web275'");

//Check if any row is returned or not.
if (!$res) {
    echo "No data found";
}

else
{
    $row = mysql_fetch_assoc($res);  //Returns the row of the result
    $number_of_tables_in_database = $row["count(*)"];
    echo $number_of_tables_in_database;
}


text:
Q: Find out the time when handle signals I am using WINAPI.
DWORD dwRc = ::WaitForMultipleObjects(3, aHandles, FALSE, pRedir->m_dwWaitTime);

My aHandles[2] signals before pRedir->m_dwWaitTime runs the required stuff and again runs the instruction:
DWORD dwRc = ::WaitForMultipleObjects(3, aHandles, FALSE, pRedir->m_dwWaitTime);

and process continues.
I want to modify the value of m_dwWaitTime.
I want to determine the time between the start of aHandles[2] and when it signaled.
How do I do that?


text:
Q: Why does github show me "Your recently pushed branches"? I fast-forwarded a couple of development branches to be up-to-date with master, and pushed them to a private repository. The private repo is owned by the client's github account and I am a collaborator.
Now, github shows me two links under "Your recently pushed branches:", each containing "Pull request" and "Compare". When I click on "Pull request" out of curiosity, it shows me:
Oops! master  is already up-to-date with feature  Try a different branch?. It's the same story for any other branch because they are all fast-forward updated. So what is the point of these links?

A: What I did to remove those messages was to actually create the pull request and then after that, I labeled the pull request as closed. It didn't affect my repository in any sort of way and it did remove the message.

A: In my situation this message disappeared themself after about 2 hours.

A: Those links let you quickly compare or open a pull request from one your branch.
They're displayed when a recently pushed branch is ahead of the remote HEAD. Most of the time, the remote HEAD points to master (this can be changed by tweaking the "default branch" of the repository in the Admin section).
As it looks like your remote HEAD points to master, those links should not be displayed indeed. The good move would be to send a mail support@github.com..

A: The message will be removed after 2 hours. And this message will only be visible to the author, not all the contributors.


text:
Q: Date value did not match format specified [YYYY-MM-DD] Error in Psycopg2 while COPY i have an issue while copying a csv file from s3 to redshift, i'm getting error with the format of a specific column
This is the create table statement
"create table public.prueba_06_2020 (fecha DATE , hora TIMESTAMP , cantidad BIGINT , codrpta VARCHAR(165), respuesta VARCHAR(165), codtrn VARCHAR(165), codnuevo VARCHAR(165), descripcion_transaccion VARCHAR(165), descripcion_respuesta VARCHAR(165), respnueva VARCHAR(165));"

and this is the copy statement
"copy public.prueba_06_2020 from 's3://plink-redshift-dev/tiempo_real_app/Transaccion Real.csv' iam_role 'arn:aws:iam::XXXXXXXXXXX:role/XXXXXXXXXx' csv dateformat as 'YYYY-MM-DD';"

i also try the same code without dateformat. and if i look at the column in the csv it's like this
df.fecha.unique()
Out[25]: array(['2020-06-03'], dtype=object)

the stl_load_error table is throwing this error
"Invalid Date Format - length must be 10 or more   "
---or in case i use dateformat---
"Date value did not match format specified [YYYY-MM-DD] "

Thanks for the help