Q: Click the imageview that is in the listview to go to another activity There is a imageview and a textview in a listview.
I want to click the imageview to go to another activity with the value of the hashmap. I uesed setOnItemClickListener is as below:
    lvAll.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                long arg3) {
            testBadgeMap = (HashMap<String, Object>) parent.getItemAtPosition(position);
        }
    });

But I can't set the listener for the imageview in order I can't click the imageview.
How can I click the imageview to go to another activity with the value of hashmap?

A: You have to use Adapter code to handle the click within the list items.
@Override
public View getView(int position, View convertView,
        ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) con
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.yourlayout, parent, false);

    Button row = (Button) rowView.findViewById(R.id.btnSample);

    final int n = position;
    row.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent next = new Intent(context, NextActivity.class);
                startActivity(next);

        }
    });

    return rowView;
}

A: you can use image.setOnClickListener()
but i suggest to use ImageButton,it's extends from imageView ,it will Interception click event,then you can click it

A:     public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        RecordHolder holder = null;

        if (row == null) {
            LayoutInflater inflater = ((Activity)mcontext).getLayoutInflater();
            row = inflater.inflate(R.layout.custom_layout, parent, false);
            holder = new RecordHolder();

            holder.tv_name=(TextView) row.findViewById(R.id.tv_name);

    holder.btn_custom_delete=(Button) row.findViewById(R.id.btn_custom_delete);

    holder.btn_custom_insert=(Button) row.findViewById(R.id.btn_custom_insert);

           row.setTag(holder);
         } else {
           holder = (RecordHolder) row.getTag();
         }

                    holder.tv_name.setTag(position);
                    holder.btn_custom_delete.setTag(position);

                    holder.tv_name.setText(getItem(position));

                    holder.tv_name.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            int pos = (Integer) view.getTag();

                            Intent intent = new Intent(mcontext , ActionActivity.class);
                            // Here You can also get you position of arraylist or hashmap by pos i.e integer variable value.

                            startActivity(intent);
                        }
                    });

                    return row;
}


Q: Column added to table but does not show up I'm new to Postgres.  I created a database and a table, then I added columns to the table:
ALTER TABLE NDQ01
ADD COLUMN Date, date

To verify, I did:
\d+ ndq01

and the output is:
Table "public.ndq01"
 Column | Type | Collation | Nullable | Default | Storage | Stats target | Description

--------+------+-----------+----------+---------+---------+--------------+-------------

My new column name "Date" does not show up.  What did I do wrong?
Thanks very much.

UPDATE:
This is the error from Putty:
dbfinance01-# alter table ndq01 add column Date date;

ERROR:  syntax error at or near "alter"

LINE 2: alter table ndq01 add column Date date;

A: Looks like the alter table did not succeed. Try removing the comma:
alter table NDQ01 add column Date date;

Check out \h alter table in psql for more information.
To clarify based on other answers, according to the current docs, date is not a reserved word in Postgres, and can be set as a column name (tested on version 11.2):
=# \d+ ndq01;
                                 Table "public.ndq01"
 Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
--------+------+-----------+----------+---------+---------+--------------+-------------
 date   | date |           |          |         | plain   |              |

SQL Key Words docs


Q: Deploying NextJS front end and Expresss back end to Heroku Here is my directory structure

*

*app

*

*frontend

*backend

I don't have a package.json file in the main directory but both the frontend and backend have package.json files.
The frontend is a fully functional NextJS app and the backend is an Express server handling api/data requests.
I have one repository for the entire app. My goal is to push this app in its current structure to Heroku, set up whatever environment variables I need, and have Heroku deal with the build details. I have yet to find any tutorials or any SO questions that target my instance specifically.
So far I just tried to push the whole repo but this is there error message I'm getting:
remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:                         HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:                         See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed

I'm assuming this is because there is no package.json file in the root directory to tell Heroku what to do. I don't have enough experience to know if this really is my problem or not. Unfortunately, I don't really know the direction I need to go here and I'm having a really hard time finding tutorials or any help when I search about this. I'm coming to understand the process and details a little more as I go along but I could definitely use a good explanation as to what I need to do, how I need to do it, and why I need to do it. I know I'm asking for a lot but anything helps. Thank you.

A: I would suggest restructuring the project so that it has a package.json in the root folder. A simple way to make it work is by letting the Express app serve the NextJS app.
I was having the same issue as you. I realized that deploying a NextJS app isn't as straight-forward as deploying a Create-React-App app. I ended up following the official recommendation of the NextJS team for deployment, which is to let Vercel serve it.
It was actually incredibly easy. I managed to deploy the NextJS app in a matter of minutes. Create a Vercel account, add a new app and deploy it.
The downside of this is that you will use Heroku for deploying your backend, and Vercel for deploying your frontend. But if you are using GitHub for example, Vercel will automatically re-deploy your NextJS app everytime you push to your main branch. So, in actuality you won't even have to do much in Vercel after deploying it the first time.
There are probably other ways and workarounds, but according to Vercel (who by the way are the creators of NextJS), deploying it with Vercel is the easiest way.


Q: Out of a set of data returned grouped by months, only the initial month is returning incorrect data I am trying to return data for the last 24 months as of the end of last month.  Only the initial month returns incorrect data, while all the other months are correct.  I believe the issue is in the strBeginDate = section of the code.  Any ideas what would be causing partially returned data for the initial month?  Thank you very much.
Sub GetStaticApprovalRates_Slide6()

    Dim strBeginDate
    Dim strEndDate

    strEndDate = Sheets("Instructions").Range("EndDate").Value
    strBeginDate = DateAdd("m", -23, strEndDate) + 1

    Sheets("Slide6Data").Select

A: It's hard to say exactly what's wrong based only on what you posted.  But I do see that you are calculating the start date based on the end date, by only subtracting months.   There is no allowance for days.  So you might be missing some of that first month by not allowing for the early days of that first month.
That is , if end date occurs mid-month, I think your algorithm would cause start date to be mid-month also.  Perhaps missing days 1-x of that first month.


Q: Unable to access merge field values inside visualforce component in angularJs View:

        {{key}}  {{value}} //this is printing correct result
        <c:FieldSetComponent objectAPIName="'{{key}}'" fieldSet="'{{value}}'" cid="'{{key}}'"
                             sectionTitle="Section 1" columns="2" textAlign="center"></c:FieldSetComponent>

Controller:
$scope.ObjectApiFieldsetMap = {
 Applications__c: "Application_FieldSet_One",
 clcommon__Collateral__c: "Collateral_FieldSet_One"
};

Now when I'm trying to access {{key}},{{value}} inside c:FieldSetComponent  ,its only passing string as {{key}} and {{value}} and not the converted result. How can I access values stored inside key, value inside component?

A: Posting the solution which I implemented as a work around.
Turns out that you cannot access angular merge field values inside visualforce components. So instead of manipulating(segregating input into key-value pair) values inside angular controller, I have to push the logic to apex controller.
<apex:component controller="RegistrationController" access="global">
   <apex:repeat value="{!ObjectApiFieldsetMap}" var="apiName">
          <c:FieldSetComponent objectAPIName="{!apiName}" fieldSet="{!ObjectApiFieldsetMap[apiName]}"
             cid="{!apiName}{!ObjectApiFieldsetMap[apiName]}"
              columns="1" textAlign="center">
          </c:FieldSetComponent>

   </apex:repeat>
</apex:component>

And in my apex controller i.e RegistrationController , I have set the logic to segregate key values from a map input which I'm using inside visualforce component
global class RegistrationController {

global Map<String,String> ObjectApiFieldsetMap {
                              get {
                                   ObjectApiFieldsetMap = arrangeApiFieldSetsByOrder();
                                   return ObjectApiFieldsetMap;
                                   }
                                   set;
    }

    global Map<String,String> arrangeApiFieldSetsByOrder() {

        Map<String,String> ObjectApiFieldsetMap =  new Map<String,String>();
                   /* logic for segregation */
        return ObjectApiFieldsetMap;
    }
}


Q: Binding JavaScript Variables to HTML Elements I've got this system whereby a Bootstrap table is created. In each cell in the each row, a numerical value appears representing the number of, say, customers in that region. Something like,
-----------------------------------
     Region     |     Number
-----------------------------------
New York        |        5
New England     |        8
Florida         |        3
-----------------------------------

The number is calculated in JavaScript when the DOM loads. The JavaScript receives all customers in an unorganized array, which I then sorted out into a proper matrix called customers[region], where each element in customers is itself an array of objects, like this:
var customers = {
   0 : ["customer1","customer2","customer3"],
   1 : ["customer4","customer5","customer6"],
   2 : ["customer7","customer8","customer9"]
}

The table cells are filled in dynamically with some JS code looking like
var cell = "" + customers[0].length + "	"
$("#row1").append(string); // Gets one of the rows, and appends to it

Now, however, I want to load a modal window when the user clicks one of the numbers. The modal window will show a table of all of the customers in that region. I am able to turn each of the numbers into a link that opens the modal window, but I can't find a good way to pass the modal window the data. So I want to bind customers[0] to one link, bind customers[1] to another link, etc, so that when the link is clicked, the modal window receives that specific JavaScript object.
$(document).ready(function() {
    $('a#testLink0').click(function(e) {
        $.get('template.html', function(data){
            modal.open({content: data});
    });
});

How can I pass the JavaScript object to some JavaScritp code in template.html? Note that the number of links is actually much, much greater, so much greater that it would be best to assign the links dynamically. Any suggestions?

A: It seems to be a better approach simply to generate the ids (or any other attributes of those links) dynamically but in a way that you're able to map the given generated attribute value (for instance an id of customers1) to the hash key of your object connected to that link (customers1 would lead you to the key 1 in your hash, for instance) so you're able to get that attribute value from the click event -> e (by examining the value of e.target - http://api.jquery.com/category/events/event-object/) passed to your .click(function(e) {...})and then simply read the hash property you want to populate your modal.


Q: Randomly sample rows based on year-month data = {'date':['2019-01-01', '2019-01-02', '2020-01-01', '2020-02-02'],
        'tweets':["aaa", "bbb", "ccc", "ddd"]}

df = pandas.DataFrame(data)

df['daate'] = pandas.to_datetime(df['date'], infer_datetime_format=True)

So I have an object type date and a datetime64[ns] type date. Image that I have 100 rows in each year-month. How can I randomly sample 10 rows in each year-month and put them into a data frame? Thanks!

A: Use DataFrame.groupby per years and months or month periods and use custom lambda function with DataFrame.sample:
df1 = (df.groupby([df['daate'].dt.year, df['daate'].dt.month], group_keys=False)
         .apply(lambda x: x.sample(n=10)))

Or:
df1 = (df.groupby(df['daate'].dt.to_period('m'), group_keys=False)
         .apply(lambda x: x.sample(n=10)))

Sample:
data = {'daate':pd.date_range('2019-01-01', '2020-01-22'),
        'tweets':np.random.choice(["aaa", "bbb", "ccc", "ddd"], 387)
        }

df = pd.DataFrame(data)

df1 = (df.groupby([df['daate'].dt.year, df['daate'].dt.month], group_keys=False)
         .apply(lambda x: x.sample(n=10)))
print (df1)
          date tweets      daate
9   2019-01-10    bbb 2019-01-10
29  2019-01-30    ddd 2019-01-30
17  2019-01-18    ccc 2019-01-18
12  2019-01-13    ccc 2019-01-13
20  2019-01-21    ddd 2019-01-21
..         ...    ...        ...
381 2020-01-17    bbb 2020-01-17
375 2020-01-11    aaa 2020-01-11
373 2020-01-09    bbb 2020-01-09
368 2020-01-04    aaa 2020-01-04
382 2020-01-18    bbb 2020-01-18

[130 rows x 3 columns]

A: import pandas as pd

data = {"date": ["2019-01-01", "2019-01-02", "2020-01-01", "2020-02-02"], "tweets": ["aaa", "bbb", "ccc", "ddd"]}
df = pd.DataFrame(data)
df["daate"] = pd.to_datetime(df["date"], infer_datetime_format=True)

# Just duplicating row
df = df.loc[df.index.repeat(100)]

# The actual code
available_dates = df["daate"].unique()
sampled_df = pd.DataFrame()
for each_date in available_dates:
    rows_with_that_date = df.loc[df["daate"] == each_date]
    sampled_rows_with_that_date = rows_with_that_date.sample(5)  # 5 samples
    sampled_df = sampled_df.append(sampled_rows_with_that_date)

print(len(sampled_df))


Q: Check that number of received calls is within range with NSubstitute Is there a way to check with NSubstitute that number of received calls falls within certain range?
I would like to do something like:
myMock.Received(r => r > 1 && r <= 5).MyMethod();

Alternatively, if I could get the exact number of received calls that would do the job as well. I am unit testing retries and timeouts and based on system load and other tests running number of retries can vary during unit test execution.

A: The NSubstitute API does not currently support this exactly (but it's a nice idea!).
There is a hacky-ish way of doing it using the unofficial .ReceivedCalls extension:
var calls = myMock.ReceivedCalls()
    .Count(x => x.GetMethodInfo().Name == nameof(myMock.MyMethod));
Assert.InRange(calls, 1, 5);

The better way to do this using a custom Quantity from the NSubstitute.ReceivedExtensions namespace:
// DISCLAIMER: draft code only. Review and test before using.
public class RangeQuantity : Quantity {
    private readonly int min;
    private readonly int maxInclusive;
    public RangeQuantity(int min, int maxInclusive) {
        // TODO: validate args, min < maxInclusive.
        this.min = min;
        this.maxInclusive = maxInclusive;
    }
    public override string Describe(string singularNoun, string pluralNoun) =>
        $"between {min} and {maxInclusive} (inclusive) {((maxInclusive == 1) ? singularNoun : pluralNoun)}";

    public override bool Matches<T>(IEnumerable<T> items) {
        var count = items.Count();
        return count >= min && count <= maxInclusive;
    }

    public override bool RequiresMoreThan<T>(IEnumerable<T> items) => items.Count() < min;
}

Then:
myMock.Received(new RangeQuantity(3,5)).MyMethod();

(Note you will need using NSubstitute.ReceivedExtensions; for this.)


Q: Android Retrofit NetworkBoundResource returns null I am trying to retrieve data from a third-party API using Retrofit and NetworkBoundResource (https://developer.android.com/jetpack/guide#addendum). However when this NetworkBoundResource runs it returns null.
The JSON I'm trying to fetch is as follows:
    {
        "id":93
        "name":"Business"
        "total":587
        "has_next":true
        "podcasts":[]
    }

Hoping someone can help! Relevant code below.
Podcasts.kt
@Keep
@Entity(
    tableName = "podcasts"
)
@Parcelize
data class Podcast(
    @PrimaryKey
    @ColumnInfo(name = "id")
    val id: String,
    @ColumnInfo(name = "title")
    val title: String,
    @ColumnInfo(name = "publisher")
    val publisher: String,
    @ColumnInfo(name = "image")
    val image: String,
    @ColumnInfo(name = "thumbnal")
    val thumbnail: String,
    @ColumnInfo(name = "url")
    val url: String,
    @ColumnInfo(name = "total_episodes")
    @Json(name = "total_episodes")
    val total: Int,
    @ColumnInfo(name = "favourite")
    var favourite: Boolean = false,
) : Parcelable

@Entity(
    tableName = "best_podcasts",
    indices = [Index(
        value = ["id"],
        unique = true
    )]
)
data class BestPodcasts(
    @PrimaryKey
    @ColumnInfo(name = "id")
    val id: String,
    @ColumnInfo(name = "podcasts")
    val podcasts: List<Podcast>
)

NetworkBoundResource
    abstract class NetworkBoundResource<ResultType, RequestType>
    @MainThread constructor(private val appExecutors: AppExecutors) {
        //
        private val result = MediatorLiveData<Resource<ResultType>>()

        init {
            result.value = Resource.loading(null)
            @Suppress("LeakingThis")
            val dbSource = loadFromDb()
            result.addSource(dbSource) { data ->
                result.removeSource(dbSource)
                if (shouldFetch(data)) {
                    fetchFromNetwork(dbSource)
                } else {
                    result.addSource(dbSource) { newData ->
                        setValue(Resource.success(newData))
                    }
                }
            }
        }

        @MainThread
        private fun setValue(newValue: Resource<ResultType>) {
            if (result.value != newValue) {
                result.value = newValue
            }
        }

        private fun fetchFromNetwork(dbSource: LiveData<ResultType>) {
            val apiResponse = createCall()
            // we re-attach dbSource as a new source, it will dispatch its latest value quickly
            result.addSource(dbSource) { newData ->
                setValue(Resource.loading(newData))
            }
            result.addSource(apiResponse) { response ->
                result.removeSource(apiResponse)
                result.removeSource(dbSource)
                when (response) {
                    is ApiSuccessResponse -> {
                        appExecutors.diskIO().execute {
                            saveCallResult(processResponse(response))
                            appExecutors.mainThread().execute {
                                // we specially request a new live data,
                                // otherwise we will get immediately last cached value,
                                // which may not be updated with latest results received from network.
                                result.addSource(loadFromDb()) { newData ->
                                    setValue(Resource.success(newData))
                                }
                            }
                        }
                    }
                    is ApiEmptyResponse -> {
                        appExecutors.mainThread().execute {
                            // reload from disk whatever we had
                            result.addSource(loadFromDb()) { newData ->
                                setValue(Resource.success(newData))
                            }
                        }
                    }
                    is ApiErrorResponse -> {
                        onFetchFailed()
                        result.addSource(dbSource) { newData ->
                            setValue(Resource.error(response.errorMessage, newData))
                        }
                    }
                }
            }
        }

        fun asLiveData() = result as LiveData<Resource<ResultType>>

        @WorkerThread
        protected open fun processResponse(response: ApiSuccessResponse<RequestType>) = response.body

        @WorkerThread
        protected abstract fun saveCallResult(item: RequestType)

        @MainThread
        protected abstract fun shouldFetch(data: ResultType?): Boolean

        @MainThread
        protected abstract fun loadFromDb(): LiveData<ResultType>

        @MainThread
        protected abstract fun createCall(): LiveData<ApiResponse<RequestType>>

        protected open fun onFetchFailed() {
            Log.d("AHHHH", "Fetch failed")
        }
    }

RemoteDataSource
    class RemoteDataSource {
        private val podcastApiService = PodcastApi.retrofitService

        fun downloadBestPodcasts(): LiveData<ApiResponse<BestPodcasts>> {
            return podcastApiService.downloadBestPodcasts()
        }
    }

DataRepository
    class DataRepository(
        private val localDataSource: LocalDataSource,
        private val remoteDataSource: RemoteDataSource,
        private val appExecutors: AppExecutors
    ) {
        fun downloadBestPodcasts(shouldFetch: Boolean): LiveData<Resource<BestPodcasts>> {
            return object :
                NetworkBoundResource<BestPodcasts, BestPodcasts>(appExecutors) {
                override fun saveCallResult(item: BestPodcasts) {
                    localDataSource.insertBestPodcasts(item)
                }

                override fun shouldFetch(data: BestPodcasts?) = data == null || shouldFetch

                override fun loadFromDb(): LiveData<BestPodcasts> =
                    localDataSource.getBestPodcasts()

                override fun createCall() = remoteDataSource.downloadBestPodcasts()
            }.asLiveData()
        }
    }

WebService
    private val retrofit = Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(LiveDataCallAdapterFactory())
        .baseUrl(BASE_URL)
        .build()

    interface WebService {
        @GET("best_podcasts")
        fun downloadBestPodcasts(
            @Header("X-ListenAPI-Key") apiKey: String = BuildConfig.API_KEY,
            @Query("genre") genreId: Int? = null
        ): LiveData<ApiResponse<BestPodcasts>>
    }


Q: How to flatten bigquery record with multiple repeated fields? I'm trying to query against app-engine datastore backup data.  In python, the entities are described as something like this:
class Bar(ndb.Model):
    property1 = ndb.StringProperty()
    property2 = ndb.StringProperty()

class Foo(ndb.Model):
    bar = ndb.StructuredProperty(Bar, repeated=True)
    baz = ndb.StringProperty()

Unfortunately when Foo gets backed up and loaded into bigquery, the table schema gets loaded as:
bar             |  RECORD  |  NULLABLE
bar.property1   |  STRING  |  REPEATED
bar.property2   |  STRING  |  REPEATED
baz             |  STRING  |  NULLABLE

What I would like to do is to get a table of all bar.property1 and associated bar.property2 where baz = 'baz'.
Is there a simple way to flatten Foo so that the bar records are "zipped" together?  If that's not possible, is there another solution?

A: As hinted in a comment by @Mosha, it seems that big query supports User Defined Functions (UDF).  You can input it in the UDF Editor tab on the web UI.  In this case, I used something like:
function flattenTogether(row, emit) {
  if (row.bar && row.bar.property1) {
    for (var i=0; i < row.bar.property1.length; i++) {
      emit({property1: row.bar.property1[i],
            name: row.bar.property2[i]});
    }
  }
};

bigquery.defineFunction(
  'flattenBar',
  ['bar.property1', 'bar.property2'],
  [{'name': 'property1', 'type': 'string'},
   {'name': 'property2', 'type': 'string'}],
  flattenTogether);

And then the query looked like:
SELECT
  property1,
  property2,
FROM
  flattenBar(
  SELECT
    bar.property1,
    bar.property2,
  FROM
    [dataset.foo]
  WHERE
    baz = 'baz')

A: Since baz is not repeated, you can simply filter on it in WHERE clause without any flattening:
SELECT bar.property1, bar.property2 FROM t WHERE baz = 'baz'


Q: shell script triggering through control-m Generally, i have a shell script which run in Control-m with certain parameters like:
sh shell_script_program.sh 'param_1' 'param_2' 'param_3'

But, in order to test the program i have to change the parameter values passing to the shell script. So i was editing whole time when ever i want to run the program.
sh shell_script_program.sh 'value_1' 'value_2' 'value_3'
sh shell_script_program.sh 'value_1' 'value_3' 'value_4'

Is there any way to automate the different set of parameters passed as arguments to the script.
Could you please provide a hint for any solution.

A: You can create a file with a different set of paramaters like
$cat input_param.txt
'param_1' 'param_2' 'param_3'
'value_1' 'value_2' 'value_3'
'value_1' 'value_3' 'value_4'
$

and call script in loop
while read param;
do
   echo ./shell_script_program.sh  ${param} | sh  ;
done < input_param.txt

A: You can create a wrapper script for this.
Create an environment file with the parameters value.
For eg a .env file with the param values. You can modify the param value by making changes to .env file.
cat .env
param_1=value1
param_2=value2
In the wrapper load the environment file.
Wrapper script Code:
cat wrapper.sh
./.env file
sh shell_script_program.sh 'value_1' 'value_2' 'value_3'
Check for exit status
echo $?
sh shell_script_program.sh 'param_1' 'param_2' 'param_3'
echo $?
You can execute wrapper script
sh wrapper.sh
Based on exit status you can decide whether to proceed or not.


Q: Google Cloud SDK Windows Installer Error: "System cannot find the path specified" When I tried install Google Cloud SDK by its own installer I get this:

"Sistem belirtilen yolu bulamiyor" means "System cannot find the path specified"
And this is my enviroment variables:

C:/HERE where my Python executable file is.
So who is going to tell me what is going on here? Also my Python version is 3.7.6
EDIT: This part is extra and a bit long but here are my log files. I hope it helps. I am tryin to make a CRM program and I need to connect it to Cloud Services. Thanks for any help!
2020-10-13 00:15:24,919 DEBUG    root            Loaded Command Group: ['gcloud', 'components']
2020-10-13 00:15:24,926 DEBUG    root            Loaded Command Group: ['gcloud', 'components', 'copy_bundled_python']
2020-10-13 00:15:24,927 DEBUG    root            Running [gcloud.components.copy-bundled-python] with arguments: []
2020-10-13 00:15:32,618 INFO     root            Display format: "value(python_location)"
2020-10-13 00:15:32,618 INFO     ___FILE_ONLY___ C:\Users\ALICEM~1\AppData\Local\Temp\tmpfffjhsuk\python\python.exe
2020-10-13 00:15:32,623 DEBUG    root            Metrics reporting process started...

2020-10-13 00:17:18,590 DEBUG    root            Loaded Command Group: ['gcloud', 'components']
2020-10-13 00:17:18,598 DEBUG    root            Loaded Command Group: ['gcloud', 'components', 'post_process']
2020-10-13 00:17:18,600 DEBUG    root            Running [gcloud.components.post-process] with arguments: []
2020-10-13 00:18:41,822 INFO     root            Display format: "none"

Last one is a bit long so i took the last bit
2020-10-13 00:17:17,480 INFO     ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗

2020-10-13 00:17:17,480 INFO     ___FILE_ONLY___ ╠═ Creating backup and activating new installation          ═╣

2020-10-13 00:17:17,480 INFO     ___FILE_ONLY___ ╚
2020-10-13 00:17:17,480 DEBUG    root            Attempting to move directory [C:\Users\Ali cem üzüm\AppData\Local\Google\Cloud SDK\google-cloud-sdk] to [C:\Users\Ali cem üzüm\AppData\Local\Google\Cloud SDK\google-cloud-sdk.staging\.install\.backup]
2020-10-13 00:17:17,498 INFO     ___FILE_ONLY___ ══════════════════════════════
2020-10-13 00:17:17,498 DEBUG    root            Attempting to move directory [C:\Users\Ali cem üzüm\AppData\Local\Google\Cloud SDK\google-cloud-sdk.staging] to [C:\Users\Ali cem üzüm\AppData\Local\Google\Cloud SDK\google-cloud-sdk]
2020-10-13 00:17:17,522 INFO     ___FILE_ONLY___ ══════════════════════════════
2020-10-13 00:17:17,522 INFO     ___FILE_ONLY___ ╝

2020-10-13 00:17:17,609 DEBUG    root            Updating notification cache...
2020-10-13 00:17:17,609 INFO     ___FILE_ONLY___

2020-10-13 00:17:17,612 INFO     ___FILE_ONLY___ Performing post processing steps...
2020-10-13 00:17:17,613 DEBUG    root            Executing command: ['C:\\Users\\ALICEM~1\\AppData\\Local\\Temp\\tmpfffjhsuk\\python\\python.exe', '-S', 'C:\\Users\\Ali cem üzüm\\AppData\\Local\\Google\\Cloud SDK\\google-cloud-sdk\\lib/gcloud.py', 'components', 'post-process']
2020-10-13 00:18:41,872 DEBUG    ___FILE_ONLY___
2020-10-13 00:18:41,873 DEBUG    ___FILE_ONLY___
2020-10-13 00:18:42,044 INFO     ___FILE_ONLY___
Update done!

2020-10-13 00:18:42,049 INFO     root            Display format: "none"

A: I recommend you double check your PATH variable.
As per:
"If your installation is unsuccessful due to the find command not being recognized, ensure your PATH environment variable is set to include the folder containing find. Usually, this is C:\WINDOWS\system32;"
I noticed that you added the logs :), I would like to mention that sometimes there are some issues with special characters in the admin user name(~),so just a quick test, could you please try to use another user without any special character in the name?
Another option is installing manually Python 2.7 and set an environment variable with "CLOUDSDK_PYTHON" with a direct path to python.exe.
For example:
C:\HERE\python.exe

Finally, I found this Stackoverflow post that could help you.


Q: Laravel Pass Data To Form on Another Page I am attempting to essentially pass a variable from one page url to another to assist in filling out a form.
I have a Script model and a Prescription model. Each script can have multiple prescriptions. So on the Scripts show page, I'm wanting to have a create button that allows users to click it, and it sends them to the Prescriptions create page, but auto-fills out the script_id for the user in the controller. This way it is definitively tagged to the correct script.
So if someone clicks on 'Create Prescription' on test.com/scripts/34/show, it takes them to test.com/prescriptions/create and automatically applies 34 as the script_id field - ideally either a hidden field, or directly passed to the controller somehow so that the user can't tamper with it.

A: You can use session, before returning prescriptions/create page you can do
Session::flash('script_id', $script_id);

and when user submits prescription creation just take it
$script_id = Session::get('script_id');


Q: Adding value of row below in R - most efficient My data:
no.att

   year  freq
1  1896   380
2  1900  1936
3  1904  1301
4  1906  1733
5  1908  3101
6  1912  4040
7  1920  4292
8  1924  5693
9  1928  5574
10 1932  3321
11 1936  7401
12 1948  7480
13 1952  9358
14 1956  6434
15 1960  9235
16 1964  9480
17 1968 10479
18 1972 11959
19 1976 10502
20 1980  8937
21 1984 11588
22 1988 14676
23 1992 16413
24 1994  3160
25 1996 13780
26 1998  3605
27 2000 13821
28 2002  4109
29 2004 13443
30 2006  4382
31 2008 13602
32 2010  4402
33 2012 12920
34 2014  4891
35 2016 13688

My goal:
from year 1992 and forwards the observation interval changes from every 4th year to every 2nd year.
I want to keep it every 4th year. so I want to ->
no.att[24,2] + no.att[25,2]

my solution is:
x <- 24
y <- 25

temp <-  no.att[x,2]
temp1 <- no.att[y,2]

no.att[y,2] <- temp + temp1

x <- x + 2
y <- y + 2

running the above once and then skipping the two top lines does the trick.
What would an alternative to this approach be?

A: Using ave to sum freq every 4 yearly,
ans <- dat
ans$freq <- ave(dat$freq, ceiling(dat$year/4), FUN=sum)
ans[ans$year %in% seq(1896,2016,4),]

output:
   year  freq
1  1896   380
2  1900  1936
3  1904  1301
5  1908  4834
6  1912  4040
7  1920  4292
8  1924  5693
9  1928  5574
10 1932  3321
11 1936  7401
12 1948  7480
13 1952  9358
14 1956  6434
15 1960  9235
16 1964  9480
17 1968 10479
18 1972 11959
19 1976 10502
20 1980  8937
21 1984 11588
22 1988 14676
23 1992 16413
25 1996 16940
27 2000 17426
29 2004 17552
31 2008 17984
33 2012 17322
35 2016 18579

data:
dat <- read.table(text="year  freq
1896   380
1900  1936
1904  1301
1906  1733
1908  3101
1912  4040
1920  4292
1924  5693
1928  5574
1932  3321
1936  7401
1948  7480
1952  9358
1956  6434
1960  9235
1964  9480
1968 10479
1972 11959
1976 10502
1980  8937
1984 11588
1988 14676
1992 16413
1994  3160
1996 13780
1998  3605
2000 13821
2002  4109
2004 13443
2006  4382
2008 13602
2010  4402
2012 12920
2014  4891
2016 13688", header=TRUE)


Q: Android not sizing Custom Dialog big enough I am using a custom Dialog that contains a text field, an image, and a button. The text can contain HTML. Sometimes the bottom of the dialog gets chopped off the bottom when the text is long enough. How can I prevent this? I want Android to determine the size of the dialog but it doesn't seem to be doing that. DO I need to size the Dialog myself in this case?
Here is the layout...
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/alert_root_incorrect"
  style="@style/AlertDialogTheme"
  android:background="@drawable/rounded_alert"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:padding="10dp"
>
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/rounded_alert"
  >

    <TableLayout
      android:stretchColumns="0"
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
    >

      <TableRow>
        <TextView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="left"
          android:textStyle="bold"
          android:text="Sorry, that's wrong!"
          android:textColor="@color/gray_dark" />

        <ImageView
          android:id="@+id/check"
          android:background="@drawable/xmark"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="right"
          android:layout_marginRight="10dp" />

      </TableRow>
    </TableLayout>

    <TextView
      android:id="@+id/alert_text"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:ellipsize="none"
      android:text="In fact, this is where the explanation will go. Something about how this passage related to the topic"
      android:textColor="#000000" />

    <Button
      android:id="@+id/okay_button"
      android:layout_width="100dp"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:layout_gravity="center_horizontal"
      android:background="@drawable/rounded_alert_button"
      android:text="Okay"
      android:textColor="@color/white"
      android:textSize="20sp" />
  </LinearLayout>
</LinearLayout>

And here is the code I am using to load it...
if ( null == layout ) {
   this.layout = inflater.inflate(R.layout.alert_incorrect, (ViewGroup) findViewById(R.id.alert_root_incorrect));
}

TextView message = (TextView) layout.findViewById(R.id.alert_text);
message.setText(Html.fromHtml(card.getConclusion()));
((Button) layout.findViewById(R.id.okay_button)).setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
      dismissDialog(INCORRECT_DIALOG);
      nextQuestion();
   }
});

layout.requestLayout();

dialog = new Dialog(this, R.style.AlertDialogTheme);
dialog.setContentView(layout);
dialog.setCancelable(false);

return dialog;

And here's a snap of what I mean..

Thanks,
John

A: This is not perfect but I've corrected it by setting the layout of the dialog relative to the default display.
dialog = new Dialog(this, R.style.AlertDialogTheme);
dialog.setContentView(layout);
Window window = dialog.getWindow();
window.setLayout(
    (int)(window.getWindowManager().getDefaultDisplay().getWidth()  * .90),
    (int)(window.getWindowManager().getDefaultDisplay().getHeight() * .90 ));

dialog.setCancelable(false);

Just tweak the ".90" values until it feels right.

A: Here is the solution:

*

*You should add a Linearlayout at the outside of your dialog's xml file

*Then set this Linearlayout's gravity as "center"

*the last step is creating a LayoutParams and set it to the dialog
android.view.WindowManager.LayoutParams lp = new android.view.WindowManager.LayoutParams();
    lp.width = android.view.WindowManager.LayoutParams.FILL_PARENT;
    lp.height = android.view.WindowManager.LayoutParams.FILL_PARENT;
    alertDialog.getWindow().setAttributes(lp);


Q: Javascript putting comma in text I'm having problems with my (javascript) API. When I use the coinmarketcap API (https://api.coinmarketcap.com/v1/ticker). As for "max_supply" for bitcoin, it gives me "16865112.0" in text. This is a problem. I want to automatically put comma's in the number like 16,865,112.0 normally I use toLocaleString() but it is marked as text and it doesnt work.
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
  for (var i = 0; i < data.length - 1; i++) {
    if (data[i].id == "bitcoin") {
     $("#total_supply").html(data[i].total_supply.toLocaleString());
     }
  }
});

Any suggestions?

A: You can still do it, just first convert string to number.

var value = "16865112.0";
value = +value; // convert to number
var fV = Number(value).toLocaleString();
console.log(fV);

A: You are calling Number.toLocaleString on String. You need to convert it to Number first by calling parseInt or Number() constructor (you can change your current locale too).

$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
  for (var i = 0; i < data.length - 1; i++) {
    if (data[i].id == "bitcoin") {
     $("#total_supply").html(Number(data[i].total_supply).toLocaleString('en-US'));
     }
  }
});


Q: Does Apple allow changing from Non-consumable IAP to Subscription? I have an iOS App with a Non-consumable In-App Purchase, now I want to change my app to subscription business model. Does Apple Review Guidelines allow this change?
Surely the old purchaser can continue to use the app without paying again.


Q: How to preserve the leading zero when changing a string into a number using Javascript? How do I convert a string such as "03" into a number and keep the zero at the beginning of the string? Using Number("03") will remove the leading 0 and return 3, but I want to keep the 0 there. How would I go about doing this?
Here's my JS function for context:
function format(input, unit) {
  if (new RegExp(unit, 'i').test('minute second')) {
    if (String(input).length === 1) return Number(`0${input}`);
    else return input;
  }
  else if (unit === 'hour') {
    return input;
  }
}

Thanks!
EDIT: What I got so far
let timer = {
  hours: 0,
  minutes: 1,
  seconds: 30,
  updateTimerDisplay() {
    document.getElementById('hour').innerHTML = this.hour;
    document.getElementById('minute').innerHTML = String(format(this.minutes, 'minute'));
    document.getElementById('second').innerHTML = String(format(this.seconds, 'second'));
  },
  startTimer() {
    const { updateTimerDisplay: updateDisplay } = this;
    let update = setInterval(_ => {
      this.seconds -= 1;
      if (this.seconds < 0) {
        this.seconds = 59;
        this.minutes -= 1;
      }
      if (this.minutes < 0) {
        this.minutes = 59;
        this.hours -= 1;
      }
      updateDisplay();
    }, 1000);
  }
};
timer.updateTimerDisplay();
timer.startTimer();

function format(input, unit) {
  if (new RegExp(unit, 'i').test('minute second')) {
    if (String(input).length === 1) return `0${input}`;
    else return String(input);
  }
}

A: Some issues:

*

*Spelling of this.hour: should be this.hours

*By calling updateDisplay you don't pass on the expected value for this. It is better to just keep the original name of the method, and use this.updateTimerDisplay.

*Don't convert the 0-prefixed string back to number: you are interested in something to display, so keep the string format.

Without changing too much else in your code, the above corrections make it work:

let timer = {
  hours: 0,
  minutes: 1,
  seconds: 30,
  updateTimerDisplay() {
    // Use textContent, not innerHTML (that is for HTML content)
    document.getElementById('hour').textContent = this.hours; // spelling!
    // The function format returns a string, so no need to call String on it:
    document.getElementById('minute').textContent = format(this.minutes, 'minute');
    document.getElementById('second').textContent = format(this.seconds, 'second');
  },
  startTimer() {
    // Don't read a function reference into a variable, as you'll lose the this-binding
    // --------- const { updateTimerDisplay: updateDisplay } = this;
    let update = setInterval(_ => {
      this.seconds -= 1;
      if (this.seconds < 0) {
        this.seconds = 59;
        this.minutes -= 1;
      }
      if (this.minutes < 0) {
        this.minutes = 59;
        this.hours -= 1;
      }
      // By having `this.` here, you pass that this-reference to the function
      this.updateTimerDisplay();
    }, 1000);
  }
};
timer.updateTimerDisplay();
timer.startTimer();

function format(input, unit) {
  // RegExp is overkill here. Just use includes:
  if (['minute', 'second'].includes(unit.toLowerCase())) {
    // Don't convert with Number: it must be a string:
    if (String(input).length === 1) return `0${input}`;
    else return String(input);
  }
}
::


Q: Error : 'Sprite' was not declared in this scope I write a game and I need to create a vector of the sprite that represents the enemies in my map struct, but because map.h include sprite.h and vice versa I have an error 'Sprite' is not declared in this scope. I heard about forward declaration; is that the solution?
#ifndef SPRITE_H
#define SPRITE_H

#include "map.h"
#include "anim.h"

struct Sprite
{
    Animation an;
    float x,y;
    int w,h;
    float vx,vy;
    bool air;
    int right, left, top, bottom;
    int sens;
};

void InitSprite(Sprite* sp,Charset* c,float x,float y,int nbstats);
int EssaiDeplacement(Map* m,Sprite *sp,float vx,float vy);
void Affine(Map* m,Sprite *sp,float vx,float vy);
void Move(Map* m,Sprite *sp,const Uint8 *keys);
void RenderSprite(Sprite* sp,Charset* c);
void Tile_Collision(Sprite* sp,Map* m);
void Evolue(Sprite* sp,const Uint8 *state);

#endif

#ifndef MAP_H
#define MAP_H

#include <string>

#include "mario.h"
#include "sprite.h"

struct Map
{
    Charset* c;
    int xtiles_level,ytiles_level;
    std::vector<std::vector<int> >tableau;
    std::vector<int> tiles;
    std::vector<std::vector<int> > limits;
    std::vector<Sprite> enemys;
};

void Load_Tiles(Map* m,Charset* c,const char* fichier,int largeur_monde,int hauteur_monde);
void Load_Level(Map* m,const char* fichier);
void AfficherMap(Map* m,SDL_Renderer* renderer);
void SaveMap(Map* m,const char* fichier);
int TileCollision(SDL_Rect *test,Map* m);

#endif

The error is in map.h.

A: Seeing cyclic redundancy in your code! Forward declaration should resolve the issue. Another way:
#ifndef COMMON_H
#define COMMON_H

#include "anim.h"

struct Sprite
{
};

struct Map
{
};

#endif

#ifndef SPRITE_H
#define SPRITE_H

#include "common.h"

void InitSprite(Sprite* sp, Charset* c, float x, float y, int nbstats);
/* ... */
#endif

#ifndef MAP_H
#define MAP_H

#include "common.h"
#include "mario.h"
#include "sprite.h"

void Load_Tiles(Map* m, Charset* c, const char* fichier, int largeur_monde, int hauteur_monde);
/* ... */
#endif


Q: How to swap first div with last div on mobile version? I have divs as follows.

How can i swap first-row div with fourth-row div on mobile devices? Is it possible to do with just css? What could be best stragety to achieve this, I can do this with javascript, but wanted to know whether it is possible with just css. I am using bootstrap 3
Expected result on mobile

A: If you use flexbox on the row, you can use the order property to do this for you. (you can use media queries for adding display: flex to target mobile devices)
See how the positions of fourth-row and first-row are swapped in the demo below:

div.row {
  display: flex;
  flex-direction: column;
}

[id$='-row'] {
  order: 2;
}
#first-row {
  order: 3;
}
#fourth-row {
  order: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

1

2

3

4

A: Use Flex property to swap elements. Here is an article about it Reverse Elements Order.
Unable to demonstrate the mobile only part, so please use the below CSS.
@media only screen and (min-width : 480px) {
    .row { display: flex; flex-direction: column-reverse; }
}

$('button').on('click', function(){
 $('.row').toggleClass('row-reverse');
})
.row-reverse { display: flex; flex-direction: column-reverse; }

first

second

third

fourth

<button>reverse/unreverse</button>

A: If you just want to change the look in different screen sizes, you can use default Bootstrap grid ordering:
https://getbootstrap.com/docs/3.3/css/#grid-column-ordering
Might be easier to see the responsive result here: https://codepen.io/anon/pen/vJQmXq

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

4

2

3

1

A: Here you go with a solution using jQuery https://jsfiddle.net/68bfxozm/1/

var updateDivOrder = function() {
  if($(document).width() < 500){
    var first = $('#first-row').clone();
    var last = $('#fourth-row').clone();
    $('.row div').first().remove();
    $('.row div').last().remove();

    $('.row div').first().before(last);
    $('.row div').last().after(first);
  } else {
    var first = $('#first-row').clone();
    var last = $('#fourth-row').clone();
    $('.row div').first().remove();
    $('.row div').last().remove();

    $('.row div').first().before(first);
    $('.row div').last().after(last);
  }
}

updateDivOrder();

$(window).resize(updateDivOrder);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

1

2

3

4

My assumption is mobile width will be less than 500px.
Hope this will help you.


Q: Making Highly Customized, Hoverable, Overlappable, Widgets I want to up my game in UI design using PyQt5. I feel like the resources for UI customization in PyQt5 are not easy to find. It is possible to try and make personalized widget, but the overall method seems non-standardized.
I need to build an arrow widget that is hoverable, overlappable with other widgets and highly customized. As I read in this tutorial and some other posts, it possible to do exactly what you need using paintEvent. Thus that is what I tried, but overall, I feel like the method is quite messy, and I'd like some guidelines on building complex Customized, general widget. Here's what I have:
Customized Shape: I built my code based on this
Hoverable property: I read everywhere that modifying the projects styleSheet is usually the way to go, especially if you want to make your Widget general and adapt to colors, the problem is that I wasn't able to find how to use properly self.palette to fetch the current colors of the QApplication styleSheet. I feel like i's have to maybe use enterEvent and leaveEvent, but I tried to redraw the whole widget with a painter in those functions and it said
QPainter::begin: Painter already active
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::setRenderHint: Painter must be active to set rendering hints

Overlappable Property: I found a previous post which seemed to have found a solution: create a second widget that is children of the main widget, in order to be able to move the children around. I tried that but it seems that it doesn't want to move, no matter the position I give the widget.
Here is my code:
import sys
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGraphicsDropShadowEffect, QApplication, QFrame, QPushButton
from PyQt5.QtCore import Qt, QPoint, QLine
from PyQt5.QtGui import QPainter, QPen, QColor, QPalette

class MainWidget(QWidget):
    def __init__(self):
        super(MainWidget, self).__init__()
        self.resize(500, 500)
        self.layout = QHBoxLayout()
        self.setLayout(self.layout)
        self.myPush = QPushButton()
        self.layout.addWidget(self.myPush)

        self.arrow = ArrowWidget(self)
        position = QPoint(-40, 0)

        self.layout.addWidget(self.arrow)
        self.arrow.move(position)

class ArrowWidget(QWidget):
    def __init__(self, parent=None):
        super(ArrowWidget, self).__init__(parent)
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.w = 200
        self.h = 200
        self.blurRadius = 20
        self.xO = 0
        self.yO = 20
        self.resize(self.w, self.h)
        self.layout = QHBoxLayout()
        # myFrame = QFrame()
        # self.layout.addWidget(myFrame)
        self.setLayout(self.layout)
        self.setStyleSheet("QWidget:hover{border-color: rgb(255,0,0);background-color: rgb(255,50,0);}")
        shadow = QGraphicsDropShadowEffect(blurRadius=self.blurRadius, xOffset=self.xO, yOffset=self.yO)
        self.setGraphicsEffect(shadow)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.begin(self)
        # painter.setBrush(self.palette().window())
        # painter.setPen(QPen(QPalette, 5))

        ok = self.frameGeometry().width()/2-self.blurRadius/2-self.xO/2
        oky = self.frameGeometry().height()/2-self.blurRadius/2-self.yO/2

        painter.drawEllipse(QPoint(self.frameGeometry().width()/2-self.blurRadius/2-self.xO/2, self.frameGeometry().height()/2-self.blurRadius/2-self.yO/2), self.w/2-self.blurRadius/2-self.yO/2-self.xO/2, self.h/2-self.blurRadius/2-self.yO/2-self.xO/2)
        painter.drawLines(QLine(ok-25, oky-50, ok+25, oky), QLine(ok+25, oky, ok-25, oky+50))
        painter.end()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    testWidget = MainWidget()
    testWidget.show()
    sys.exit(app.exec_())

If someone could help me make this work and explain along the way to help us better understand the structure of customized widgets and explain a better method that isn't messy like this one, I believe it would be a plus to the beginners like me using PyQt5 as a main Framework for UI making.

A: There is no "standard" method for custom widgets, but usually paintEvent overriding is required.
There are different issues in your example, I'll try and address to them.
Overlapping
If you want a widget to be "overlappable", it must not be added to a layout. Adding a widget to a layout will mean that it will have its "slot" within the layout, which in turn will try to compute its sizes (based on the widgets it contains); also, normally a layout has only one widget per "layout slot", making it almost impossible to make widget overlap; the QGridLayout is a special case which allows (by code only, not using Designer) to add more widget to the same slot(s), or make some overlap others. Finally, once a widget is part of a layout, it cannot be freely moved nor resized (unless you set a fixedSize).
The only real solution to this is to create the widget with a parent. This will make it possible to use move() and resize(), but only within the boundaries of the parent.
Hovering
While it's true that most widgets can use the :hover selector in the stylesheet, it only works for standard widgets, which do most of their painting by themself (through QStyle functions). About this, while it's possible to do some custom painting with stylesheets, it's generally used for very specific cases, and even in this case there is no easy way to access to the stylesheet properties.
In your case, there's no need to use stylesheets, but just override enterEvent and leaveEvent, set there any color you need for painting and then call self.update() at the end.
Painting
The reason you're getting those warnings is because you are calling begin after declaring the QPainter with the paint device as an argument: once it's created it automatically calls begin with the device argument. Also, it usually is not required to call end(), as it is automatically called when the QPainter is destroyed, which happens when the paintEvent returns since it's a local variable.
Example

I created a small example based on your question. It creates a window with a button and a label within a QGridLayout, and also uses a QFrame set under them (since it's been added first), showing the "overlapping" layout I wrote about before. Then there's your arrow widget, created with the main window as parent, and that can be moved around by clicking on it and dragging it.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class ArrowWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        # since the widget will not be added to a layout, ensure
        # that it has a fixed size (otherwise it'll use QWidget default size)
        self.setFixedSize(200, 200)
        self.blurRadius = 20
        self.xO = 0
        self.yO = 20
        shadow = QtWidgets.QGraphicsDropShadowEffect(blurRadius=self.blurRadius, xOffset=self.xO, yOffset=self.yO)
        self.setGraphicsEffect(shadow)
        # create pen and brush colors for painting
        self.currentPen = self.normalPen = QtGui.QPen(QtCore.Qt.black)
        self.hoverPen = QtGui.QPen(QtCore.Qt.darkGray)
        self.currentBrush = self.normalBrush = QtGui.QColor(QtCore.Qt.transparent)
        self.hoverBrush = QtGui.QColor(128, 192, 192, 128)

    def mousePressEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            self.mousePos = event.pos()

    def mouseMoveEvent(self, event):
        # move the widget based on its position and "delta" of the coordinates
        # where it was clicked. Be careful to use button*s* and not button
        # within mouseMoveEvent
        if event.buttons() == QtCore.Qt.LeftButton:
            self.move(self.pos() + event.pos() - self.mousePos)

    def enterEvent(self, event):
        self.currentPen = self.hoverPen
        self.currentBrush = self.hoverBrush
        self.update()

    def leaveEvent(self, event):
        self.currentPen = self.normalPen
        self.currentBrush = self.normalBrush
        self.update()

    def paintEvent(self, event):
        qp = QtGui.QPainter(self)
        qp.setRenderHints(qp.Antialiasing)
        # painting is not based on "pixels", to get accurate results
        # translation of .5 is required, expecially when using 1 pixel lines
        qp.translate(.5, .5)
        # painting rectangle is always 1px smaller than the actual size
        rect = self.rect().adjusted(0, 0, -1, -1)
        qp.setPen(self.currentPen)
        qp.setBrush(self.currentBrush)
        # draw an ellipse smaller than the widget
        qp.drawEllipse(rect.adjusted(25, 25, -25, -25))
        # draw arrow lines based on the center; since a QRect center is a QPoint
        # we can add or subtract another QPoint to get the new positions for
        # top-left, right and bottom left corners
        qp.drawLine(rect.center() + QtCore.QPoint(-25, -50), rect.center() + QtCore.QPoint(25, 0))
        qp.drawLine(rect.center() + QtCore.QPoint(25, 0), rect.center() + QtCore.QPoint(-25, 50))

class MainWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        layout = QtWidgets.QGridLayout()
        self.setLayout(layout)
        self.button = QtWidgets.QPushButton('button')
        layout.addWidget(self.button, 0, 0)
        self.label = QtWidgets.QLabel('label')
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        layout.addWidget(self.label, 0, 1)
        # create a frame that uses as much space as possible
        self.frame = QtWidgets.QFrame()
        self.frame.setFrameShape(self.frame.StyledPanel|self.frame.Raised)
        self.frame.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        # add it to the layout, ensuring it spans all rows and columns
        layout.addWidget(self.frame, 0, 0, layout.rowCount(), layout.columnCount())
        # "lower" the frame to the bottom of the widget's stack, otherwise
        # it will be "over" the other widgets, preventing them to receive
        # mouse events
        self.frame.lower()
        self.resize(640, 480)
        # finally, create your widget with a parent, *without* adding to a layout
        self.arrowWidget = ArrowWidget(self)
        # now you can place it wherever you want
        self.arrowWidget.move(220, 140)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    testWidget = MainWidget()
    testWidget.show()
    sys.exit(app.exec_())


Q: voa_class related exception while browsing through objects in DB, using Telerik libraries Edit2: this question started as a question on how to browse through tables, but it turned into a question about Telerik voa_class exception
Edit1: this question contains two ways of trying to do the same thing.
I would like to do something like:
var Obj1 = database.GetData<Class1>().First();
var Obj2 = database.GetData<Class1>().Next();

First attempt
The idea of Next() is simply to take another one. As Next() method does not exist, so I've decided to try this here:
var Obj1 = database.GetData<Class1>().First();
var Obj2 = database.GetData<Class1>().Single(o => o.Name != Obj1.Name);

This, however, generates a weird exception:
Telerik.OpenAccess.Exceptions.DataStoreException
  HResult=0x80131500
  Message=Row for OID GenericOID@87f2834a Class1 Id=2 NOTRES  is not in the hierarchy starting at <Namespace>.Class1 ('Class1s') (voa_class for row is ...)
  Source=Telerik.OpenAccess.Runtime
  StackTrace:
   at OpenAccessRuntime.ExceptionWrapper.Throw()
   at OpenAccessRuntime.storagemanager.logging.LoggingStorageManager.executeQueryAll(ApplicationContext context, ImmutableQueryDetails query, CompiledQuery compiledQuery, QueryParameters parameters, Int32 skip, Int32 take)
   at OpenAccessRuntime.DataObjects.UnsynchronizedPMProxy.getAllQueryResults(CompiledQuery cq, QueryParameters parameters, Int32 skip, Int32 take)
   at OpenAccessRuntime.DataObjects.ForwardQueryResult.Resolve()
   at OpenAccessRuntime.DataObjects.ForwardQueryResult.Initialize()
   at OpenAccessRuntime.DataObjects.ForwardQueryResult.get_Item(Int32 indexParam)
   at OpenAccessRuntime.ListEnumerator.setCurrent(Int32 _pos)
   at OpenAccessRuntime.ListEnumerator.Move(Int32 relative)
   at OpenAccessRuntime.ListEnumerator.MoveNext()
   at Telerik.OpenAccess.Query.TypedEnumerator`1.MoveNext()
   at Telerik.OpenAccess.Query.ExpressionExecution.PerformDatabaseQuerySingle[TResult,T](ChainedContext context, Expression expression, QueryableCategory before, Int32& found, Int32 elemAt, Boolean single, Boolean diffType)
   at Telerik.OpenAccess.Query.ExpressionExecution.PerformQuerySingle[T,TResult](ExpressionCutter cutter, MethodCallExpression mce, ChainedContext piece, QueryOptions options)
   at Telerik.OpenAccess.Query.Piece`1.ExecuteSingle[TResult](Expression expression)
   at Telerik.OpenAccess.Query.Piece`1.System.Linq.IQueryProvider.Execute[TResult](Expression expr)
   at System.Linq.Queryable.Single[TSource](IQueryable`1 source, Expression`1 predicate)
   at <CurrentClass>.<CurrentMethod>() in C:\...\<Source_Code>.cs:line 54
   at ...

Second attempt
(This second attempt is based on this other question.)
IQueryable<Class1> query = database.GetData<Class1>();
query.OrderBy(u => u.Id);
var Obj1 = query.First();

query = query.Skip(1);
var Obj2 = query.First(); <== this line gives me an exception.

As an exception I get a similar one than the first.
What is this about?

A: Apparently the source code is correct, but there seem to be problems with the database:
The table, corresponding with Class1, contains a column voa_class. The content of that column should be <NameSpace_of_Class1>.Class1. In case there's something else, like <Whatever_NameSpace>.<AnotherClass> or <AnotherNameSpace>.Class1 (like in my case), the mentioned exception gets generated.


Q: Eclipse: Installation failed due to invalid APK file I've got a new Android project in Eclipse, one activity and TextView, nothing else. I didn't modify anything. When I try to run the application on the usb on my phone (zte v970m with android 4.1.1), I get
In console
Installation failed due to invalid APK file!
Please check logcat output for more details.
Launch canceled!

In LogCat
09-24 12:21:01.174: D/dalvikvm(584): Not late-enabling CheckJNI (already on)
09-24 12:21:01.854: E/Trace(584): error opening trace file: No such file or directory (2)
09-24 12:21:02.684: D/gralloc_goldfish(584): Emulator without GPU emulation detected.

Pls, help me to find solution. By the way with AVD all works.
My .java
package com.example.testusbdebug;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

my .xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

and my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testusbdebug"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.testusbdebug.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

A: to make it easier for you
I would re-download the whole bundle in http://developer.android.com/sdk/index.html


Q: Data File Size Stays Same Whereas Log File Size Is Increasing I am using the following snippet to track the data and log file size increase after certain operations:
SELECT @SQL = STUFF((
    SELECT '
    USE [' + d.name + ']
    INSERT INTO #space (database_id, data_used_size, log_used_size)
    SELECT
          DB_ID()
        , SUM(CASE WHEN [type] = 0 THEN space_used END)
        , SUM(CASE WHEN [type] = 1 THEN space_used END)
    FROM (
        SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8)
        FROM sys.database_files s
        GROUP BY s.[type]
    ) t;'
    FROM sys.databases d
    WHERE d.[state] = 0
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

EXEC sys.sp_executesql @SQL

The problem is, after each write operation, log file size increases as expected but the data file size stays the same for 4 or five operations and then suddenly increases.
Why would this be?


Q: npm package.json and docker (mounting it...) I am using Docker, so this case might look weird. But I want my whole /data directory to be mounted inside my docker container when developing.
My /data folder container my package.json file, an app directory and a bunch of other stuff.
The problem is that I want my node_modules folder to NOT be persistent, only the package.json file.
I have tried a couple of things, but package.json and npm is giving me a hard time here...

*

*Mounting the package.json file directly will break npm. npm tries to rename the file on save, which is not possible when its a mounted file.

*Mounting the parent folder (/data) will mount the node_modules folder.

*I cant find any configuration option to put node_modules in another folder outside /data, example /dist

*Putting package.json in /data/conf mounting the /data/conf as a volume instead wont work. I cant find any way to specify the package.json path in npmrc.

*Putting package.json in /data/conf and symlinking it to /data/package.json wont work. npm breaks the symlink and replaces it with a file.

Copying data back and forth to/from inside the docker container is how I am doing it now.. A little tedious.. I also want a clean solution..

A: As you have already answered, I think that might be the only solution right now.
When you are building your Docker image, do something like:
COPY data/package.json /data/
RUN mkdir /dist/node_modules && ln -s /dist/node_modules /data/node_modules && cd /data && npm install

And for other stuff (like bower, do the same thing)
COPY data/.bowerrc /data/
COPY data/bower.json /data/
RUN mkdir /dist/vendor && ln -s /dist/vendor /data/vendor && cd /data && bower install --allow-root

And COPY data/ /data at the end (so you are able to use Dockers caching and not having to do npm/docker installation when there is a change to data.
You will also need to create the symlinks you need and store them in your git-repo. They will be invalid on the outside, but will happely work on the inside of your container.
Using this solution, you are able to mount your $PWD/data:/data without getting the npm/bower "junk" outside your container. And you will still be able to build your image as a standalone deployment of your service..

A: A similar and alternative way is to use NODE_ENV variable instead of creating a symlink.

RUN mkdir -p /dist/node_modules
RUN cp -r node_modules/* /dist/node_modules/
ENV NODE_PATH /dist/node_modules

Here you first create a new directory for node_modules, copy all modules there, and have Node read the modules from there.

A: I've been having this problem for some time now, and the accepted solution didn't work for me*
I found this link, which had an edit pointing here and this indeed worked for me:
volumes:
  - ./:/data
  - /data/node_modules

In this case the Engine creates a volume (see Compose reference on volumes) which is not mounted to your source directory. This was the easiest solution and didn't require me to do any symlinking, setting paths, etc.
For reference, my simple Dockerfile just looks like this:
# install node requirements
WORKDIR /data
COPY ./package.json ./package.json
RUN npm install -qq

# add source code
COPY ./ ./

# run watch script
CMD npm run watch

(The watch script is just webpack --watch -d)
Hope this is able to help someone and save hours of time like it did for me!

'*' = I couldn't get webpack to work from my package.json scripts and installing anything while inside the container created the node_modules folder with whatever I just installed (I run npm i --save [packages] from inside the container to get the package update the package.json until the next rebuild)

A: The solution I went with was placing the node_modules folder in /dist/node_modules, and making a symlink to it from /data/node_modules. I can do this both in my Dockerfile so it will use it when building, and I can submit my symlinks to my git-repo. Everything worked out nicely..

A: Maybe you can save your container, and then rebuild it regularly with a minimal dockerfile
FROM my_container
and a .dockerignore file containing
/data/node_modules
See the doc
http://docs.docker.com/reference/builder/#the-dockerignore-file


Q: return a $post with related user model after update in Laravel Is there any way to return the $post after update along the user information? Example:
public function update(Request $request, $id)
{

    //on_put, from_user, NewDesc
    // define rules
    $rules = array(

        'NewDesc' => 'max:600'

    );

    $validator = Validator::make(Input::all(), $rules);

    if ($validator->fails())
    {
        return Response()->json($validator);
    }
    else{

        $post = Post::find($id);

        $description = $request->input('NewDesc');

        $post->update(['description' => $description]);

        return Response()->json($post);

    }

}

This returns the new updated $post to my script but what if I want to send also the user data with it?

A: You haven't really given us the information about the users and how they relate, so I will guess...
Try something like...
return Response()->json($post->load('user'));

A: Try something like that:
return Response()->json(['post' => $post, 'userdata' => $userdata]);


Q: Absolute center horizontal and vertical a div with fluid width and height? how to make absolute center horizontal and vertical  a div with fluid width and height using css?
Thanks in advance for helping.

#div_parent{
 background:#ccc;
 position:relative;
}

.div_child{
  background-color:#338BC7;
  position: absolute;
  left: 50%;
  width: auto;
  height: auto;
  padding: 20px;
  top:25%;
  background: blue;
  color: white;
  text-align: center;
  border:1px solid #ccc;
}

Centered In The Middle Of The Page.

A: A couple of problems with your code:

*

*You do not have a width and height specified on your html and body, without which any of descendent elements wouldn't have a reference to set their positions and/or dimensions in percent units.

*You do not have dimensions (width/height) specified on your #div_parent, without which you cannot position its absolutely positioned child (which is relative to it) to the vertical center. Moreover, as you want to position your .div_child to the center of the page, why do you have a parent wrapped around it anyway.

Apart from fixing the above, a trick which is usually used to align elements both horizontally and vertically is to use transform: translate to shift it back by 50%.
Like this:
.div_child {
    position: absolute; left: 50%; top: 50%;
    transform: translate(-50%, -50%);
    ...
}

Fiddle: http://jsfiddle.net/abhitalks/Lnqvqnkn/
Snippet:

* { box-sizing: border-box; paddin:0; margin: 0; }
html, body { height: 100%; width: 100%; }
#div_parent{ height: 100%; width: 100%; background: #ccc; position: relative;}
.div_child {
    background-color: #338BC7;
    position: absolute; left: 50%; top: 50%;
    transform: translate(-50%, -50%);
    width: auto; height: auto;
    padding: 20px; color: white; text-align: center; border: 1px solid #ccc;
}

Centered In The Middle Of The Page.

A: When I need fluid width, I prefer using this method:
CSS
.background { display: table; width: 100%; height: 100%; position: absolute; left: 0; top: 0; }
.background > div { display: table-cell; vertical-align: middle; text-align: center; }

HTML

Centered In The Middle Of The Page.

Demo on jsfiddle.
Hope it works for you.


Q: Cannot make button non-interactable through seperate script I'm trying to make a button interactable after a certain scene (playing level) has been loaded. It's a button in a menu scene that represent the loaded scene itself (level selectable after playing it).
The problem is this: If the users passes a certain level, say level 1, level 2 gets loaded, and a static method gets called:
public static void AllowTut2()
{
    Tut2Allowed = true; //public static bool initialised in this script
    tutorial2.interactable = true; //tutorial2 is a button in the "menu scene"
}

To make it clear where the variables come from, this is part of the same script:
public class LevelSelectScript : MonoBehaviour {

public Button tutorial2;
public static bool Tut2Allowed = false;
//...some other variables

  void Start ()
  {
  tutorial2 = tutorial2.GetComponent<Button>();
  tutorial2.enabled = false;    //more later on
  ///... some other code
  }
}

Now the problem is this error: An object reference is required to access non-static member `LevelSelectScript.tutorial2' (refers to method AllowTut2).
It seems that I cannot change tutorial2.interactable trough the given static method (called in another script).
It basically says the button tutorial2 is non-static, therefore cannot use this in a static method.
Now if I make the button static, i.e. change
public Button tutorial2;

to
public static Button tutorial2;

then I have no way to assign the button object in the scene to this variable in the attached script.
Does someone perhaps know a solution to this problem?
Thanks in advance!

A: if you want to use static varaibles and also use inspector for assigning you can use singleton  , here is where you can learn it


Q: javascript form validation not working on chrome & FF here's the html/javascript code...
I've tested it on safari and it works fine but in chrome & FF it doesn't validate at all.
it directs me automatically to the action link

<form action="http://example.com/subscribe/post?u=f752d10720e6104f1" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank">

<input type="email" value="" name="EMAIL" class="text" id="mce-EMAIL" placeholder="Enter you email">

<input type="text" name="b_f752d10720e6104f109250a61_95e4fc5f29" value="">

<input type="submit" value="submit" name="subscribe" id="mc-embedded-subscribe" class="button" >

</form>

Thank you in advance.

A: function validate(){
  var email = $("#mce-EMAIL").val();
  if (!validateEmail(email)) {
    $("#mce-EMAIL").css("border-color", "red");
      return false;
  }
else{
$("#mce-EMAIL").css("border-color", "#dbdbdb");
$("form").submit();
return true;
}
}

$(document).ready(function(){
$("#mc-embedded-subscribe").on("click",function(){ validate()});
});

this might be better , binding submit with validate , would submit the form anyway !


Q: Bootstrap Carousel with previous and next image I found this example to create a bootstrap carousel with previous and next images.
https://codepen.io/glebkema/pen/RKavve
All images are 33% but I would like to have it like:
10% |     80%      | 10%.

Is it possible to modify the css to make the previous and next image 10% of the width and the center image 80% ?

A: When the item group is getting focus, it adds the active class. So you can do something like this:
.item.active .item__third:nth-child(1), .item.active .item__third:nth-child(3) {
width:10%;
}

.item.active .item__third:nth-child(2) {
width:80%;
}

Or generally on .item .item__third class:
.item .item__third:nth-child(1), .item .item__third:nth-child(3) {
width:10%;
}

.item .item__third:nth-child(2) {
width:80%;
}


Q: Insert nested object via JSON using web api with NHibernate I'm writing an application that consist of a ReadAPI and a WriteAPI. The read API contains the domain classes, and uses EF CORE code first to generate the SQL DB, and to read from it.
The write API uses NHibernate to write to the database that is generated by EF Core. So far I have inserted 'simple' object via the write API, which has worked fine.
I'm encountering a problem now. I have a domain class, Driver, that has a nested object, Address, inside. At DB level a driver can have one address and an address can belong to multiple drivers. I'm trying to POST a JSON object, a driver object, via the write API. As to now, I've solved inserting the address by creating an address record in DB in advance, and giving the address ID in the JSON.
What I want to do now is giving the complete nested JSON object and have NHibernate generate the inserts for me. I have tried so many things but I feel like I am getting nowhere. Any advice would be much appreciated.
I'm using .Net Core with NHiberate 5.3.5, which has the mapping by code functionality already. If someone can solve it using Fluent NH instead, that is fine as well since I will convert it to NH 5.3.5 notation myself then.
My code:
Domain classes:
Driver:
namespace Models
{
    public class Chauffeur : IIdentifiable
    {
        public virtual long Id { get; set; }
        public virtual string Naam { get; set; }
        public virtual string Voornaam { get; set; }
        public virtual DateTime GeboorteDatum { get; set; }
        //todo validatie
        public virtual string RijksRegisterNummer { get; set; }
        public virtual RijbewijsTypes TypeRijbewijs { get; set; }
        public virtual bool Actief { get; set; }

        //rel adres
        public virtual long AdresId { get; set; }
        public virtual Adres Adres { get; set; }

        //rel tankkaart
        public virtual long TankkaartId { get; set; }
        public virtual Tankkaart Tankkaart { get; set; }

    }
}

Address:
namespace Models
{
    public class Adres : IIdentifiable
    {
        public virtual long Id { get; set; }
        public virtual string Straat { get; set; }
        public virtual int Nummer { get; set; }
        public virtual string Stad { get; set; }
        public virtual int Postcode { get; set; }
        public virtual ICollection<Chauffeur> Chauffeurs { get; set; }
    }
}

My DriverMap so far:
namespace WriteAPI
{
    public class ChauffeurMap : ClassMapping<Chauffeur>
    {
        public ChauffeurMap()
        {
            this.Table("Chauffeurs");

            this.Id(c => c.Id, c =>
            {
                c.Generator(Generators.Native);
                c.Type(NHibernateUtil.Int64);
                c.Column("Id");
                c.UnsavedValue(0);
            });

            this.Property(c => c.Naam);
            this.Property(c => c.Voornaam);
            this.Property(c => c.GeboorteDatum);
            this.Property(c => c.RijksRegisterNummer);
            this.Property(c => c.TypeRijbewijs);
            this.Property(c => c.Actief);

            this.Property(c => c.AdresId);

            this.Property(c => c.TankkaartId);
        }
    }
}

Using this mapping i could insert the nested object, by using an existing child address ID.
How I inserted this via a post:
{
                "Naam" : "Bart",
                "Voornaam" : "Jannsses",
                "AdresId" : 4,
                "GeboorteDatum" : "1979-04-25",
                "RijksRegisterNummer" : "999-888-7777",
                "TypeRijbewijs" : 1,
                "Actief" : true
}

How I would like to insert it in the future:
{
                "Naam" : "Bart",
                "Voornaam" : "Jannsses",
                "Adres" : {
                    "Straat": "Boomstraat",
                    "Nummer": 1,
                    "Stad": "Gent",
                    "Postcode": 9000
                          },
                "GeboorteDatum" : "1979-04-25",
                "RijksRegisterNummer" : "999-888-7777",
                "TypeRijbewijs" : 1,
                "Actief" : true
}

Note that the ID of an address is auto generated at DB level.
Any help would be much appreciated.
Kind regards

A: You would need to add ManyToOne mapping in your ChauffeurMap class
 this.ManyToOne(x => x.Adres , m =>
        {
            m.Column("AdresId");
            // AdresId can be insert and update
            m.Update(true);
            m.Insert(true);
            m.Cascade(Cascade.None);
            m.Fetch(FetchKind.Join);
            m.NotFound(NotFoundMode.Exception);
            m.Lazy(LazyRelation.Proxy);
            m.ForeignKey("AdresId");
        });

And you would also need additional mapping class for Adres as AdresMap. I hope you already have it. If not, please add it as below -
public class AdresMap : ClassMapping<Adres>
{
    public AdresMap()
    {
    this.Table("Adres"); //Your table name
    this.Id(c => c.Id, c =>
        {
            c.Generator(Generators.Native);
            c.Type(NHibernateUtil.Int64);
            c.Column("Id");
            c.UnsavedValue(0);
        });

    Set(x => x.Chauffeurs, c =>
        {
            c.Key(k =>
                {
                    k.Column("Id");
                    k.ForeignKey("AdresId");
                });
            c.Inverse(true);
            c.Cascade(Cascade.None);
        },
        r => r.OneToMany(o => { }));

    this.Property(x => x.Straat );
    // ... other properties
   }
}


Q: Calling consecutive DLL's from {tmp} in Inno Setup I want to use a DLL (lets say 'A.dll'), that I created in Delphi, within my Inno Setup script that uses a bunch of other DLLs ('B.dll', 'C.dll', ...). All these dll-files are included in the Files-section as follows:
[Files]
Source:"libs\*.dll"; Flags: dontcopy

In the code section I declare methods of the used DLL as described in the Online help and add the loadwithalteredsearchpath flag:
procedure MyMethod; external 'MyMethod@files:A.dll,B.dll,C.dll stdcall loadwithalteredsearchpath';

When the installer starts, all needed files are copied into the temporary directory the constant {#tmp} is pointing to. However, MyMethod starts its execution just fine (checked it with some Showmessages), but the whole thing breaks, when the method tries to use the other DLLs.
Next to the temporary folder from {#tmp} two other temporary directories are created during the setup (all with the 'IS-xxxxx.tmp' pattern), which contain 'setup.tmp' (which is not occurent in {#tmp}). When I now manually copy all the DLL's (besides A.dll) into both these other directories at the beginning of the setup, then everything works fine. But when I let it run only as defined in my script, then A.dll doesn't seem to find the other libraries.
Does anybody know, why this is happening and how I can fix this? This seems to be a problem with the PATH, but I thought that Inno Setup adds the tmp-dir into the PATH, so that the setup can find the DLL's (which it does, but strangely only for A.dll).
Thanks in advance for your help! :)
EDIT: The actual error I get, when I use one of the 'foreign' DLL's (B.dll, C.dll, ...) by calling one of their methods inside of A.dll during the Inno Setup:
Access violation at address 00408CC7 in module 'setup.tmp'. Read of adress 00000000.

EDIT 2: I think I realized why my problem is happening: With ExtractFilePath (first link) in my own A.dll I discovered, that the setup.exe is not executed within {tmp} but one of the other two temporary dirs that are creating at the beginning of the setup. It also appears, that not {tmp} but the current working dir (thus the dir, where inno is executed) is added to the library search path (second link). This would explain, why the other libraries (B.dll, C.dll, ...) can only be accessed when manually copying to this other temp dir. I suppose that A.dll is extracted and called from {tmp} without a problem, because it is referred as the "main-library" in the external command. I thought that with loadwithalteredsearchpath the other libraries could remain in the same directory, but that doesn't seem to work.
But how can I fix this now in an nifty way? I think I could copy the DLLs manually to the setup-path (by using ExtractFilePath(ParamStr(0)), after they have been extracted to {tmp} to solve the problem. But this seems to be a dirty workaround as using DLLs in Inno Setup is supposed to work differently.

*

*How to get path where is temporary Inno setup file is located

*External function calls with multiple dependent DLLs

A: Well I'm not sure if you only load the DLLs without registering them in the system registry. However your first EDIT shows an error triggered by attempts to access some stack of the registry, so I assume you are. In that case, I simply use a batch file (which fires commands in the CMD console) to register my DLLs as I would one by one:
 @echo off
 echo Registering DevExpress DLLs
 %~dp0gacutil.exe /i %~dp0DevExpress.BonusSkins.v12.1.dll
 %~dp0gacutil.exe /i %~dp0DevExpress.Charts.v12.1.Core.dll

So, I place this in the RUN section of the iss script:
[Run]
Filename:C:\myFolder\RegisterDevExpress.bat"

Hope this helps.


Q: Clone or edit local Minimongo collection I'd like to clone a minimongo collection so I can do some calculations, get a result, then push those results back to the server.
Assuming this is a suitable pattern, how best can I clone a minimongo collection?
It appears that in the object no longer has a ._deepcopy (1.0.4), and attempting an EJSON.clone exceeds the callstack size for even tiny collections. Underscore's _.clone() only copies by reference.
Alternatively, I could just edit the local collection via collection._collection.update. But if that's the case, what would happen if on the off chance the server updated or removed a doc while it was processing? I watched this video, but am still unclear on that scenario: https://www.eventedmind.com/feed/meteor-how-does-the-client-synchronize-writes-with-the-server

A: The why behind your pattern escapes me but one solution could be to define a null collection, (docs) copy the records you need to that, do your work, and then copy back the results into the original collection for automatic sync back to the server.
 myLocalCollection = new Mongo.Collection(null);


Q: Input field validation in angular using formControl I want to tag an error message when the user touches on that particular field and and then clicks outside without entering anything. I am not sure why the below code doesnt work .
Guys Any inputs..I need some serious suggestions pls.
<form [formGroup]="personalInfoForm" novalidate [ngClass]="{submitted: formSumitAttempt}">

      First Name

                <input type="text" class="form-control" id="firstName" placeholder="Name" formControlName="firstName"  [(ngModel)]="firstName"  required>

                        Name is required

A: in your component
personalInfoForm=new formGroup({
 firstname:new FormControl('',[Validators.required])
})

your HTML
<form [formGroup]="personalInfoForm" novalidate [ngClass]="{submitted: formSumitAttempt}">

      First Name

<input type="text" class="form-control" id="firstName" placeholder="Name" formControlName="firstName"   required>

 Name is required


Q: Facebook Share Link - Share To A Page On Mobile I am wondering if anyone has a solution to a small but major problem for me. I have coded a share button for Facebook using sharer.php, however, if the button is pressed on a mobile device Facebook isn't giving the user the option to share to a page or a group, it only will post to their personal profile. Unlike on desktop/laptop you get a drop down which gives the option, like in the attached images.
So a) is there a way around this b) is there a way to set Share To A Page as default?
You can see on the first image on my iPhone there is no option to change where it's shared....

A: to share a an url, website, in facebook u can use:
https://www.facebook.com/sharer.php?u=URLHERE

so, to get the thumbnail, title and the excerpt, to show properly in anywhere, u need to set in ur website as meta-tags inside head tags. like:
<!-- FB Share -->
<meta property="og:url" content="URLHERE" />
<meta property="og:type" content="website" />
<meta property="og:title" content="TITLE HERE" />
<meta property="og:description" content="DESC HERE" />
<meta property="og:image" content="URLIMAGE" />
<meta property="og:image:width" content="800" />
<meta property="og:image:height" content="600" />
<!-- FB Share -->


Q: How can I retrieve a specific field from a map in Cloud Firestore using Android? This is a part of data saved in firebase Firestore:

How can I get (fName) from (newFriend0) in Java?
This is part of the code. It gave the entire map. I want just a specific field such as ("jem" for (fName))
Map<String, Object> map = document.getData();

for (Map.Entry<String, Object> entry : map.entrySet()){

if (entry.getKey().equals("Friends")){

f=document.getString("FName");////not worked

Log.d("TAG", entry.getValue().toString());
                                                   }
                                               }

A: Edit: July, 16th 2201
As a matter of fact, there is a simpler way of getting that data:

*

*How to map an array of objects from Cloud Firestore to a List of objects?

Seeing that your code is in Java, please see the solution below:
FirebaseFirestore.getInstance().collection("coll").document("9999").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Map<String, Object> friendsMap = document.getData();
                for (Map.Entry<String, Object> entry : friendsMap.entrySet()) {
                    if (entry.getKey().equals("Friends")) {
                        Map<String, Object> newFriend0Map = (Map<String, Object>) entry.getValue();
                        for (Map.Entry<String, Object> e : newFriend0Map.entrySet()) {
                            if (e.getKey().equals("newFriend0")) {
                                Map<String, Object> fNameMap = (Map<String, Object>) e.getValue();
                                for (Map.Entry<String, Object> dataEntry : fNameMap.entrySet()) {
                                    if (dataEntry.getKey().equals("fName")) {
                                        Log.d("TAG", dataEntry.getValue().toString());
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                Log.d("TAG", "No such document");
            }
        } else {
            Log.d("TAG", "get failed with ", task.getException());
        }
    }
});

The result in your logcat will be:
jem

Didn't see the name of your collection in the screenshot, so I named it simply coll but you should definitely change it to the correct one.

A: Basically you need to perform 2 steps, retrieve the document data with one of the provided libraries and then manipulate the resulting map object with the means of your programming language.
Here is a simple Nodejs example getting 'fName':
let docRef = db.collection('<collection_name>').doc('9999');
docRef.get()
  .then(doc => {
    if (!doc.exists) {
      console.log('No such document!');
    } else {
      console.log('Document data:', doc.data().Friends.newFriend0.fName);
    }
  })
  .catch(err => {
    console.log('Error getting document', err);
  });

A: Firestore document is in JSON format thus we can just convert the documentSnapshot.getData() to String first then to JSON so it will be more easier to access the Map objects data without needing too many loops/iteration. Another way is to do it like this documentSnapshot.getData().get("get_only_map_key_to_be_converted_as_JSON") convert it to string then to JSON as well. The possible remaining problem is if you store url in your document's map object which will have a problem as those link needs to be unescaped to become a valid JSON though I haven't tried that scenario yet in Android Java.


Q: Table in Markdown doesn't show I want to do a simple latex table in my markdown raport:
---
title: "Title"
output: html_document
---

## Table

\begin{table}[ht]
\centering
\begin{tabular}{rrrr}
\hline
 & chisq & df & p \\
\hline
mu & 0.889 & 1 & 0.346 \\
sigma & 0.810 & 1 & 0.368 \\
Q & 0.663 & 1 & 0.415 \\
P & 0.663 & 1 & 0.415 \\
\hline
\end{tabular}
\end{table}

but my table does not show up. There is no error so i don't know what i'm doing wrong. Do i need some brackets or sth like that?


Q: Understanding source of connection time-out exception I'm trying to connect to some URL through proxy:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("113.193.248.211", 3128));
HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection(proxy);

But I'm getting exception:

java.net.ConnectException: Connection timed out: connect

How I can know what exactly throw this exception - connection to proxy server or connection to url defined in constructor of URL class?


Q: How I can auto login with SwiftyDropbox? I have an app with SwiftyDropbox that function correctly, but I need to insert email and password for Dropbox every time that I use the app.
The app it's only for my use, it's not a security problem if the app auto-login in my account.
I don't find examples or documentation to make an auto-login with SwiftyDropbox. It's possible?

A: While the Dropbox API was designed with the intention that each user would link their own Dropbox account, in order to interact with their own files, it is technically possible to connect to just one account. We generally don't recommend doing so, for various technical and security reasons, but those won't apply if you're the only user anyway.
So, there are two ways to go about this:
1) Implement the normal app authorization flow as documented, and log in and authorize the app once per app installation. The SwiftyDropbox SDK will store the resulting access token for you, which you can programmatically re-use after that point each time using authorizedClient.
2) Manually retrieve an access token for your account and hard code it in to the app, using the DropboxClient constructor shown here under "Initialize with manually retrieved auth token".


Q: MySQL exact match acting like LIKE Got an interesting problem with a simple MySQL query. I'm trying to do an exact match on the id field.
SELECT id
FROM tablename
WHERE id = '23'

Returns
id: 23

All is well and good until I do:
SELECT id
FROM repairs
WHERE id = '23abcd'

Returns
id: 23

Why on earth would it do this?!
id field is int(10) and the database is MyISAM utf8_general_ci.
Any thoughts?

A: Your database has int field it will truncate the characters and only consider the numbers that's why you are getting 23 as return id.

A: You are quoting the number in your query, so MySQL must convert it from a string to a number.   When it does that, it is using only the numeric part of the string.
I don't think the behavior is completely appropriate ( "23abcd".ToInt() should be NULL, I think), but that's what it does.

A: As Fakhruddin said that int field truncates the value of characters. That's right. But you can prevent wrong values from being inserted in the first place by setting the STRICT_ALL_TABLES mode
mysql> SET sql_mode = 'STRICT_ALL_TABLES';

One more thing is that you need to store your id as character strings(VARCHAR) if they contain letters.


Q: How to filter an R data.table by index and condition Please have a look at the following sample code.
DT <-data.table(1:15,0,rbinom(15,2,0.5))

I can filter by condition DT[V3 == 1,] or select rows by index DT[1:5,].
How can I do both? In the following code, the sequence of the indexed rows seems to by ignored:
DT[V3 == 1 & 1:5]

I could do DT[1:5,][V3 == 1], but then, for example, I wouldn't be able to modify the filtered rows:
DT[1:5,][V3 == 1, V2 := 1]

This only works with the following workaround:
DT[V3 == 1 & DT[,.I <= 5], V2 := 1]

However, this looks too data.frame-ish to me. Is there a more elegant way and why does DT[V3 == 1 & 1:5] not work?

A: We can try
DT[V3==1 & 1:.N %in% 1:5,  V2 := 1]

Or another option is
DT[intersect(which(V3==1), 1:5), V2 := 1]

Benchmarks
set.seed(24)
DT <- data.table(1:1e6, 0, rbinom(1e6, 2, 0.5))
DT1 <- copy(DT)
DT2 <- copy(DT)

OP's version
system.time({
 DT[V3 == 1 & DT[,.I <= 5], V2:= 1]
})
#user  system elapsed
#0.08    0.00    0.08

Modified options
system.time({
 DT1[V3==1 & 1:.N %in% 1:5,  V2 := 1]
})
# user  system elapsed
#  0.14    0.00    0.14

system.time({
  DT2[intersect(which(V3==1), 1:5), V2 := 1]
})
 # user  system elapsed
 #  0.05    0.00    0.05

A: Here's a faster way for @akrun's example:
set.seed(24)
DT <- data.table(1:1e6, 0, rbinom(1e6, 2, 0.5))
DT1 <- copy(DT)
DT2 <- copy(DT)

library(microbenchmark)
microbenchmark(
    DT1[which(V3[1:5]==1L), V2:= 1],
    DT2[intersect(which(V3==1), 1:5), V2 := 1]
, times = 1, unit = "relative" )

# Unit: relative
#        expr      min       lq     mean   median       uq      max neval
#  sequential  1.00000  1.00000  1.00000  1.00000  1.00000  1.00000     1
#     set_ops 55.43582 55.43582 55.43582 55.43582 55.43582 55.43582     1

It's "sequential" in the sense that we subset by index before evaluating the condition.
The generalization is
cond = quote(V3 == 1)
indx = 1:5

DT[ DT[indx, indx[eval(cond)]], V2 := 1]
# or
set(DT, i = DT[indx, indx[eval(cond)]], j = "V2", v = 1)