text:
Q: Android: Imageview getting resized while the height of the object above is altered Here is my layout XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.homerevise.studyapp.activity.HomeScreenActivity"
    tools:showIn= "@layout/app_bar_main">

    <RelativeLayout
        android:id="@+id/rel_colour"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:background="@drawable/path_background">

        <ImageView
            android:id="@+id/image_more"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="25dp"
            android:background="@drawable/more"/>

        <TextView
            android:id="@id/txtName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="90dp"
            android:textColor="#000"
            android:textSize="24sp"
            android:visibility="invisible" />

        <ImageView
            android:id="@+id/image_page_title"
            android:layout_width="240dp"
            android:layout_height="120dp"
            android:layout_below="@id/txtName"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="20dp"
            android:background="@drawable/page_title" />

        <ImageView
            android:id="@+id/image_happy_student"
            android:layout_width="120dp"
            android:layout_height="165dp"
            android:layout_alignEnd="@id/image_page_title"
            android:layout_alignRight="@id/image_page_title"
            android:layout_alignParentRight="true"
            android:layout_marginTop="75dp"
            android:layout_marginRight="20dp"
            android:background="@drawable/happy_student" />
    </RelativeLayout>

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

        <ImageView
            android:id="@+id/image_subject_title"
            android:layout_width="80dp"
            android:layout_height="30dp"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/subject_title" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:layout_below="@id/image_subject_title"
            android:orientation="horizontal" />

        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone" />

        <TextView
            android:id="@+id/txtRecentlyLearned"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:layout_marginRight="20dp"
            android:layout_below="@id/recyclerView"
            android:text="Recently Learned"
            android:textColor="#2A3E61"
            android:textSize="24sp"
            android:textStyle="bold" />

        <ImageView
            android:id="@+id/image_Recently_Learned"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/txtRecentlyLearned"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginRight="10dp"
            android:src="@drawable/recently_learned"
            android:layout_marginBottom="90dp"/>

        </RelativeLayout>

    </LinearLayout>

If the layout height of the recycler view changes the imageview txtRecentlyLearned gets reseized. It becomes too small. Like even if the height of the recycler view is changed to 250dp the image size drops considerably. The Imageview should not get resized at all ever.
How do I fix this?
Thank you.

A: Move textView and imageView outside the RelativeLayout to the parent LinearLayout and add android:layout_weight="1" to the RelativeLayout
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_weight="1"
        android:layout_height="0dp">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </RelativeLayout>

    <TextView
        android:id="@+id/txtRecentlyLearned"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <ImageView
        android:id="@+id/image_Recently_Learned"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/recently_learned" />

</LinearLayout>

A: I Played around a little with the layout weight and relative views for now it seems to work.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.homerevise.studyapp.activity.HomeScreenActivity"
tools:showIn= "@layout/app_bar_main">

<RelativeLayout
android:id="@+id/rel_colour"
android:layout_width="match_parent"
android:layout_height="0dp"
    android:layout_weight="4"
android:background="@drawable/path_background">

    <ImageView
        android:id="@+id/image_more"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="25dp"
        android:background="@drawable/more"/>

    <TextView
        android:id="@id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="90dp"
        android:textColor="#000"
        android:textSize="24sp"
        android:visibility="invisible" />

    <ImageView
        android:id="@+id/image_page_title"
        android:layout_width="240dp"
        android:layout_height="120dp"
        android:layout_below="@id/txtName"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/page_title" />

    <ImageView
        android:id="@+id/image_happy_student"
        android:layout_width="120dp"
        android:layout_height="165dp"
        android:layout_alignEnd="@id/image_page_title"
        android:layout_alignRight="@id/image_page_title"
        android:layout_alignParentRight="true"
        android:layout_marginTop="75dp"
        android:layout_marginRight="20dp"
        android:background="@drawable/happy_student" />

    <ImageView
        android:id="@+id/image_subject_title"
        android:layout_width="80dp"
        android:layout_height="30dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="300dp"
        android:background="@drawable/subject_title" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:layout_below="@id/image_subject_title"
        android:orientation="horizontal" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="gone" />
 </RelativeLayout>

 <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1">

    <TextView
        android:id="@+id/txtRecentlyLearned"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:text="Recently Learned"
        android:textColor="#2A3E61"
        android:textSize="24sp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/image_Recently_Learned"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtRecentlyLearned"
        android:src="@drawable/recently_learned"
        />

</RelativeLayout>

</LinearLayout>


text:
Q: In firestore, how to reliably determine if snapshot listener contains some changed data from the server? Context:
There have been a few posts about this topic already. Most notably this one: How can I determine if a Firestore snapshot is from the server?.
Basically we have two variables that are passed from the snapshot listener, fromCache and hasPendingWrites. Here I am copying Frank's (in the above post) summary of them:

*

*hasPendingWrites indicates if there are local changes to this
document that haven't been sent to/handled by the server yet.

*fromCache indicates that this document may be stale. I think the
property name is a bit unfortunate here, as its value indicates data
freshness more than where the snapshot was loaded from.

There is also an option to subscribe to metadata changes (this way, the snapshot listener will fire once when hasPendingWrites is true or fromCache is false, and then again when the listener knows it's up-to-date with the server)
Problem:
So I have a feature involving highlighting. These highlights are pushed to the server but are also listened to - for example, if you add/remove/change a highlight on one device, another one will listen to it and update it live.
When you change a highlight, that new data is pushed to the server via setDoc. This triggers the listener. If the change is local, we don't want the listener to update the local highlight store every time, because it's an expensive operation, and of course, because it's already updated. But obviously, we do want to update the store when new data has been pushed from the server.
Originally I was using hasPendingWrites as described in the docs. This was working fine, until I discovered a use case that it doesn't quite cover.
Let's say one device goes offline (device A), and makes some modifications to the highlights. These changes are cached locally. When the device comes back online, these changes are pushed to firestore. As expected, the listener triggers with hasPendingWrites set to true, and so we can safely assume that the changes have been local and there's no need to update the local store because it's already updated.
The issue is when device B has modified the highlights while device A was offline, and device A modified highlights locally while offline as well. When device A comes back online, the listener is only fired once. It seems that the changes that were made in device B as well as the changes are being pushed from device A are merged together. The problem is that this all condenses into one listener trigger with hasPendingWrites set to true because device A does indeed have some pending writes. Now device A thinks that the new snapshot contains only local data and so it doesn't update with device B's new changes even though those changes are in the snapshot.
Here's a summary of the different scenarios from device A's perspective:

*

*device A goes offline -> device A makes changes -> device A comes back online = one snapshot, hasPendingWrites set to true = do not update local store = all good

*device A goes offline -> device *B* makes changes -> device A comes back online = one snapshot, hasPendingWrites set to false = update local store = all good

*device A goes offline -> device *B* and device *A* makes changes -> device A comes back online = one snapshot, hasPendingWrites set to true = do not update local store = undesirable
fromCache doesn't seem to have much use here either way, as it's subject to a similar problem.
There is also a solution regarding listening to metadata changes, however this doesn't work either because if set to true, every time there is a local write, there is always then another listener triggered with hasPendingWrites set to false. This would re-build the local store with every write.
I thought of a workaround to listen to when the device comes back online, and set a flag for the next listener trigger to be an exception, but this is very dirty.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wrong offset GMT Standard Time on Windows 10: +00:00 instead of +01:00 I receive a strange result when I try to find a time zone for "GMT Standard Time":

It returns UTC +00:00 when I expect to receive +01:00.
The next weird thing is when I convert UTC time to "GMT", then 1 hour is added to the time.
This is an example of the code:
var gmtTimeZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
var timeUtc = DateTime.UtcNow;
var gmtTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, gmtTimeZone);

Am I doing something wrong? How to get the correct display name? I need to allow the user to select a timezone and it's important to show the correct name.

A: The issue is that this is a TimeZoneInfo conversion.
From .NET 6.0 TimeZoneInfo.ConvertTimeFromUtc description

When performing the conversion, the ConvertTimeFromUtc method applies any adjustment rules in effect in the destinationTimeZone time zone.

Thus as, at the time of posting, GMT Standard Time as used by the United Kingdom is adjusted by the Daylight saving time of 1 hour.
Windows Default Time Zones shows that "GMT Standard Time" applies to the United Kingdom only.
This can be verified as follows:
var gmtTimeZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
var timeUtc = DateTime.UtcNow;
var gmtTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, gmtTimeZone);
var daylightSaving = gmtTime.IsDaylightSavingTime() ? "Yes" : "No";

Console.WriteLine($"UTC time : {timeUtc}");
Console.WriteLine($"GMT timezone time : {gmtTime}");
Console.WriteLine($"GMT timezone daylight saving? : { daylightSaving}");

gives:
UTC time : 18/08/2022 10:27:32
GMT timezone time : 18/08/2022 11:27:32
GMT timezone daylight saving? : Yes

If you wish to just use local time (as set on the user's system) then you can just use DateTime.ToLocalTime() e.g.
Console.WriteLine($"utc from gmtTime : {utc}");
Console.WriteLine($"utc to local : {utc.ToLocalTime()}");

gives:
utc from gmtTime : 18/08/2022 10:38:36
utc to local : 18/08/2022 11:38:36

To remove ambiguities when selecting a time zone I would recommend that you use the ISO3166 code e.g. "GB" instead of "GMT Standard Time".


text:
Q: Given a list of lists of length x, repeat it to get a list of lists of length n I have a list of lists like the following.
    f = [[1],[10,3], [10,15,16,20]]

I would like to repeat this list a certain number of times. Let's suppose I want the final list of lists to have length 12. I could do the following,
    from itertools import repeat, chain

    s = list(repeat(f, 4))

This gives me
    [[[1], [10, 3], [10, 15, 16, 20]],
    [[1], [10, 3], [10, 15, 16, 20]],
    [[1], [10, 3], [10, 15, 16, 20]],
    [[1], [10, 3], [10, 15, 16, 20]]]

I can now use chain to upack the list of list of lists into a list of lists
    d = list(chain(*s))

d gives,
    [[1],
    [10, 3],
    [10, 15, 16, 20],
    [1],
   [10, 3],
   [10, 15, 16, 20],
   [1],
   [10, 3],
   [10, 15, 16, 20],
   [1],
   [10, 3],
   [10, 15, 16, 20]]

length of d is 12. But this was possible only because 12 is a multiple of three. What if I wanted to repeat it 20 times or 17 , 20/3  = 6.666667 and the second parameter of the repeat function needs to be an integer.

A: If I'm understanding what you want to do, you want to be able to get a list of lists that is any length, not just a multiple of your input. The following should give you a dynamic way of getting the result you want.
It looks at the length of the input and rounds up to a value just above the desired amount. Finally, it returns a list containing only the amount of values you're looking for.
from itertools import chain, repeat, islice
import math

def my_func(list_of_lists, desired_amount):
     scalar = math.ceil(desired_amount/len(list_of_lists))
     s = repeat(list_of_lists, scalar)
     d = chain.from_iterable(s)
     return list(islice(d, desired_amount))

f = [[1],[10,3], [10,15,16,20]]
my_func(f, 20)
[[1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3]]

len(my_func(f, 20))
20

Alternative method using simpler language.
def my_func(list_of_lists, desired_amount):
     l = len(list_of_lists)
     multiplier = math.ceil(desired_amount/l)
     s = list(repeat(list_of_lists, multiplier))
     d = list(chain(*s))
     return d[:desired_amount]


text:
Q: How to deploy twincat 3 project to PLC programmatically I´m looking for a way to activate the configuration and update the boot project via C#.
My Twincat 3 project is compiled and all necessary file are in the  /_Boot folder.
Next step is a C# programm (actually unit tests) that loads and executes the project on my PLC.
So far I have read through Beckhoff Information System, but couldn´t find any hint.

A: You need the Twincat Automation Interface API in order to activate your configuration and start the PLC.
An example from the official documentation:
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using EnvDTE100;
        using System.IO;
        using TCatSysManagerLib;

        namespace ActivatePreviousConfiguration{

            class Program
            {

                static void Main(string[] args)
                {
                    Type t = System.Type.GetTypeFromProgID("VisualStudio.DTE.10.0");
                    EnvDTE.DTE dte = (EnvDTE.DTE)System.Activator.CreateInstance(t);
                    dte.SuppressUI = false;
                    dte.MainWindow.Visible = true;
                    EnvDTE.Solution sol = dte.Solution;
                    sol.Open(@"C:\Temp\SolutionFolder\MySolution1\MySolution1.sln");

                    EnvDTE.Project pro = sol.Projects.Item(1);
                    ITcSysManager sysMan = pro.Object;
                    sysMan.ActivateConfiguration();
                    sysMan.StartRestartTwinCAT();
                }
            }
        }

There are also many other things you can do with this api, for example generate code for your PLC..
You can find the documentation here:
Automation Interface pdf

A: If you only have the _Boot folder at your disposal, you just have to copy the content of _Boot\TwinCAT RT(x64)\Plc to your target boot folder C:\TwinCAT\3.1\Boot\Plc and start the PLC via ADS-Command.
The PLC will boot with the replaced compiled project.
Here an example from the official ADS-Documentation for starting the plc:
static void Main(string[] args)
{
    //Create a new instance of class TcAdsClient
    TcAdsClient tcClient = new TcAdsClient();

    try
    {
        // Connect to local PLC - Runtime 1 - TwinCAT2 Port=801, TwinCAT3 Port=851
        tcClient.Connect(851);

        Console.WriteLine(" PLC Run\t[R]");
        Console.WriteLine(" PLC Stop\t[S]");
        Console.WriteLine("\r\nPlease choose \"Run\" or \"Stop\" and confirm with enter..");
        string sInput = Console.ReadLine().ToLower();

        //Process user input and apply chosen state
        do{
            switch (sInput)
            {
                case "r": tcClient.WriteControl(new StateInfo(AdsState.Run, tcClient.ReadState().DeviceState)); break;
                case "s": tcClient.WriteControl(new StateInfo(AdsState.Stop, tcClient.ReadState().DeviceState)); break;
                default: Console.WriteLine("Please choose \"Run\" or \"Stop\" and confirm with enter.."); sInput = Console.ReadLine().ToLower(); break;
            }
        } while (sInput != "r" && sInput != "s");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        Console.ReadKey();
    }
    finally
    {
        tcClient.Dispose();
    }
}


text:
Q: How to increase size of canvas to 1080*1920 from 400*400 in code.org gamelab? I am Manav. I read articles, tried coding and researched a lot but I didn't know how to increase canvas size in code.org gamelab. Many suggested me to do code on editor.p5js, but there I am facing a lot of problems that I am not in code.org, My previous apps looked bad in the 400*400 canvas. I know that we can increase the size by dragging the canvas but it doesn't make muck of a change. After a lot of research I joined this community which was recommended by many people. I hope my issue get solved here.
Link to code.org :
https://code.org/
I tried using
createCanvas(1080,1920);
And
resizeCanvas(1090,1920);
But both don't work

A: You cannot increase canvas side in code.org default is 400x 400

A: You can't increase the canvas size for a project but you can increase it for your convenience by dragging the grey line near and right the canvas.

A: Well you can, but it has to be exported first:
Go to p5.play.js then find :
 this._defaultCanvasSize = {
    width: 400,
    height: 400
  };

I do this when making games for itch.io or whatever. It helps a lot well there is a downside to this:
It is impossible to do it without exporting. The width and height can be different changes and may mess up your game sometimes.


text:
Q: List streams of a particular DynamoDB table using CLI How can I list all the streams associated with one dynamo db table using CLI (terminal aws command)? Even listing all the streams didn't work for me:
aws dynamodb list-streams

A: To list the DynamoDb streams for a table, use this command
aws dynamodbstreams list-streams --table-name


text:
Q: Permanent access to app of dropbox account? I have an app which links to an dropbox account. I am able to login once and is saves that. But each time it asks whether I want to allow access to the app or not . Is there a way to save this preference as well and provide access to the app permanently ?

A: Read again https://www.dropbox.com/developers/start/authentication#android especially "Return to your app after user authorization".
After successful .getSession().finishAuthentication() there is AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair() which will give You data, which You should save somewhere for later use (You can use SharedPreferences for this).
In start time of application You have to check existance of this saved data, and if it's there, You don't have to call .startAuthentication() again, instead You should call .setAccessTokenPair(access) with saved data as access (look at top of https://www.dropbox.com/developers/start/files#android ).


text:
Q: Non-existent expectation and variance I have a problem the answer for which is intuitively obvious but is more difficult than anticipated to actually show.
Claim: If X is a random variable such that the expectation of X does not exist, then the variance of X does not exist either.
This seems true on an intuitive level, as the variance is a measure taken relative to the mean. My issue is in showing that, for a discrete random variable X with E[X] and E[X^2] both infinity, V[X] does not exist. In this case, using the definition V[X] = E[X^2]-E[X]^2, I have a sum which diverges to infinity take (the square of) another sum which diverges to infinity, which I don't really know how to treat.
Any tips would be appreciated.

A: Please see if the below is useful
\begin{align*}
\int\limits_{x=-\infty}^\infty x^2 f_X(x) dx &= \int\limits_{x=-\infty}^0 x^2 f_X(x) dx + \int\limits_{x=0}^1 x^2 f_X(x) dx+\int\limits_{x=1}^\infty x^2 f_X(x) dx\\
&\geq \int\limits_{x=-\infty}^0 x^2 f_X(x) dx + \int\limits_{x=0}^1 0 f_X(x) dx+\int\limits_{x=1}^\infty x^2 f_X(x) dx\\
&\geq \int\limits_{x=-\infty}^0 x f_X(x) dx + \int\limits_{x=0}^1 0 f_X(x) dx+\int\limits_{x=1}^\infty x f_X(x) dx\\
&= \int\limits_{x=-\infty}^\infty x f_X(x) dx +  \int\limits_{x=0}^1 (-x) f_X(x)  \\
&\geq \int\limits_{x=-\infty}^\infty x f_X(x) dx -  \int\limits_{x=0}^1 1 f_X(x)  \\
&\geq \int\limits_{x=-\infty}^\infty x f_X(x) dx -  \int\limits_{x=-\infty}^\infty f_X(x)  \\
&= \left[\int\limits_{x=-\infty}^\infty x f_X(x) dx\right]-1\\
&= \mathbb E [X]-1
\end{align*}
Therefore $\mathbb E [X^2] \geq \mathbb E [X]-1 = \infty$.
Let's call $\mathbb E[X] = \mu$. Then, $Var(X)=\mathbb E[(X-\mu)^2]$.
\begin{align*}
\lim\limits_{\mu\to\infty}Var [X] &=\lim\limits_{\mu\to\infty}\int\limits_{x=-\infty}^\infty (x-\mu)^2 f_X(x) dx\\
&=\lim\limits_{\mu\to\infty}\int\limits_{x=-\infty}^\infty [x^2 + \mu(\mu-2x)] f_X(x) dx\\
&=\int\limits_{x=-\infty}^\infty x^2f_X(x) dx +\lim\limits_{\mu\to\infty} \int\limits_{x=-\infty}^\infty\mu(\mu-2x) f_X(x) dx\\
&=\int\limits_{x=-\infty}^\infty x^2f_X(x) dx +\lim\limits_{\mu\to\infty} \mu\int\limits_{x=-\infty}^\infty(\mu-2x) f_X(x) dx\\
&\geq\int\limits_{x=-\infty}^\infty x^2f_X(x) dx +\lim\limits_{\mu\to\infty} \mu\int\limits_{x=-\infty}^\infty f_X(x) dx\\
&=\int\limits_{x=-\infty}^\infty x^2f_X(x) dx +\lim\limits_{\mu\to\infty} \mu\cdot 1\\
&=\mathbb E [X^2] +\lim\limits_{\mu\to\infty} \mu\cdot 1\\
&=\infty
\end{align*}


text:
Q: Can we pass closing bracket ")" at the end of a Url form View to Controller without using encoding Can I pass closing bracket ")" at end of Url in Asp MVC.
I can pass it anywhere except at the end.
I have used many methods for it but helpless.

A: Please try by encoding URL:
We can encode ) with %29.
Alternatively you can also try to escape the character with slash:
http://testurl\)


text:
Q: Calling a user defined function in sql server 2005 using JDBC I am trying to call a user defined function using jdbc, but the executeQuery() function just hangs and doesn't return.
I have tried using jTDS and Microsoft JDBC Driver for SQL Server with the same results.
Since it works when run through RazorSql, I've also tried copying the same database URL and use the same driver jar that RazorSql uses, but no luck.
Code below returns for the first query, but hangs on the second.  (Found this but did not work for me: http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/df7ee6b6-7efb-4971-baa5-fe78ae0e774b/
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

Properties props = new Properties();
props.put("user", "xxx");
props.put("password", "xxx");

Connection conn = DriverManager.getConnection("jdbc:sqlserver://xxx;selectMethod=cursor", props);

String query = "SELECT GETDATE()";
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();

while (rs.next()) {
  System.out.println(rs.getString(1));
}

query = "SELECT dbo.MY_FUNC()";
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();

while (rs.next()) {
  System.out.println(rs.getString(1));
}

stmt.close();


text:
Q: Find best result without findall and a filter I'm in a bit of pickle in Prolog.
I have a collection of objects. These objects have a certain dimension, hence weight.
I want to split up these objects in 2 sets (which form the entire set together) in such a way that their difference in total weight is minimal.
The first thing I tried was the following (pseudo-code):
-> findall with predicate createSets(List, set(A, B))
-> iterate over results while
---> calculate weight of both
---> calculate difference
---> loop with current difference and compare to current difference
       till end of list of sets

This is pretty straightforward. The issue here is that I have a list of +/- 30 objects. Creating all possible sets causes a stack overflow.
Helper predicates:
sublist([],[]).
sublist(X, [_ | RestY]) :-
  sublist(X,RestY).
sublist([Item|RestX], [Item|RestY]) :-
  sublist(RestX,RestY).

subtract([], _, []) :-
  !.
subtract([Head|Tail],ToSubstractList,Result) :-
  memberchk(Head,ToSubstractList),
  !,
  subtract(Tail, ToSubstractList, Result).
subtract([Head|Tail], ToSubstractList, [Head|ResultTail]) :-
  !,
  subtract(Tail,ToSubstractList,ResultTail).

generateAllPossibleSubsets(ListToSplit,sets(Sublist,SecondPart)) :-
  sublist(Sublist,ListToSplit),
  subtract(ListToSplit, Sublist, SecondPart).

These can then be used as follows:
:- findall(Set, generateAllPossibleSubsets(ObjectList,Set), ListOfSets ),
   findMinimalDifference(ListOfSets,Set).

So because I think this is a wrong way to do it, I figured I'd try it in an iterative way. This is what I have so far:
totalWeightOfSet([],0).
totalWeightOfSet([Head|RestOfSet],Weight) :-
  objectWeight(Head,HeadWeight),
  totalWeightOfSet(RestOfSet, RestWeight),
  Weight is HeadWeight + RestWeight.

findBestBalancedSet(ListOfObjects,Sets) :-
  generateAllPossibleSubsets(ListOfObjects,sets(A,B)),
  totalWeightOfSet(A,WeightA),
  totalWeightOfSet(B,WeightB),
  Temp is WeightA - WeightB,
  abs(Temp, Difference),
  betterSets(ListOfObjects, Difference, Sets).

betterSets(ListOfObjects,OriginalDifference,sets(A,B)) :-
  generateAllPossibleSubsets(ListOfObjects,sets(A,B)),
  totalWeightOfSet(A,WeightA),
  totalWeightOfSet(B,WeightB),
  Temp is WeightA - WeightB,
  abs(Temp, Difference),
  OriginalDifference > Difference,
  !,
  betterSets(ListOfObjects, Difference, sets(A, B)).
betterSets(_,Difference,sets(A,B)) :-
  write_ln(Difference).

The issue here is that it returns a better result, but it hasn't traversed the entire solution tree. I have a feeling this is a default Prolog scheme I'm missing here.
So basically I want it to tell me "these two sets have the minimal difference".
Edit:
What are the pros and cons of using manual list iteration vs recursion through fail
This is a possible solution (the recursion through fail) except that it can not fail, since that won't return the best set.

A: I would generate the 30 objects list, sort it descending on weight, then pop objects off the sorted list one by one and put each into one or the other of the two sets, so that I get the minimal difference between the two sets on each step. Each time we add an element to a set, just add together their weights, to keep track of the set's weight. Start with two empty sets, each with a total weight of 0.
It won't be the best partition probably, but might come close to it.
A very straightforward implementation:
pair(A,B,A-B).

near_balanced_partition(L,S1,S2):-
  maplist(weight,L,W),      %// user-supplied predicate weight(+E,?W).
  maplist(pair,W,L,WL),
  keysort(WL,SL),
  reverse(SL,SLR),
  partition(SLR,0,[],0,[],S1,S2).

partition([],_,A,_,B,A,B).
partition([N-E|R],N1,L1,N2,L2,S1,S2):-
   (    abs(N2-N1-N) < abs(N1-N2-N)
   ->   N3 is N1+N,
        partition(R,N3,[E|L1],N2,L2,S1,S2)
   ;    N3 is N2+N,
        partition(R,N1,L1,N3,[E|L2],S1,S2)
   ).

If you insist on finding the precise answer, you will have to generate all the partitions of your list into two sets. Then while generating, you'd keep the current best.
The most important thing left is to find the way to generate them iteratively.
A given object is either included in the first subset, or the second (you don't mention whether they're all different; let's assume they are). We thus have a 30-bit number that represents the partition. This allows us to enumerate them independently, so our state is minimal. For 30 objects there will be 2^30 ~= 10^9 generated partitions.
exact_partition(L,S1,S2):-
  maplist(weight,L,W),      %// user-supplied predicate weight(+E,?W).
  maplist(pair,W,L,WL),
  keysort(WL,SL),           %// not necessary here except for the aesthetics
  length(L,Len), length(Num,Len), maplist(=(0),Num),
  .....

You will have to implement the binary arithmetics to add 1 to Num on each step, and generate the two subsets from SL according to the new Num, possibly in one fused operation. For each freshly generated subset, it's easy to calculate its weight (this calculation too can be fused into the same generating operation):
  maplist(pair,Ws,_,Subset1),
  sumlist(Ws,Weight1),
  .....

This binary number, Num, is all that represents our current position in the search space, together with the unchanging list SL. Thus the search will be iterative, i.e. running in constant space.


text:
Q: Why do my controls stop working when I start a new game? I am emulating Kirby 64: The Crystal Shards using Project 64, but every ROM that I have found says "Issues (plugin)" under the status column. When starting the game, the controls work up until the point when I hit start new game, then start works, but everything else just stops working. Any thoughts on this issue?

A: Kirby 64: The Crystal Shards is listed in Project 64 as "Issues (Plugin)" because, according to the Game FAQ included with the emulator:

Missing life meter (eggs) on HUD - we have heard from users that after the first boss the meter is displayed normally. Or the problem may come and go at different points in the game. Exact cause is uncertain, very likely something in the core.

Project64 2.0.0.6 beta fixes this issue, but you'll have to be a donor to download the beta.  If you don't want to spend $20, then Mupen64 will fix the issue.
As for the controls, Kirby 64 is one of the oddballs that uses the D-Pad instead of the control stick.  If you're having trouble with all the other buttons, check out NRage's Input Plugin.


text:
Q: What are the requirements to install Windows Phone Developer Tool? I can't find it.
By requirements, I mean like:
Windows 7
Visual Studio 2010...

A: Microsoft Visual Studio 2010/2012 Express for Windows Phone
Windows Phone Emulator
Windows Phone SDK 7.1 Assemblies
Silverlight 4 SDK and DRT
Windows Phone SDK 7.1 Extensions for XNA Game Studio 4.0
Microsoft Expression Blend SDK for Windows Phone 7
Microsoft Expression Blend SDK for Windows Phone OS 7.1
WCF Data Services Client for Window Phone
Microsoft Advertising SDK for Windows Phone


text:
Q: multiple classes css selector not working with :hover I have the following css selector that is not working:
.button.button-green:hover

however if I do this, it works fine:
.button-green:hover

Is this a known issue with CSS and are there any ways around this (besided just using one class for the hover)?

A: See the following jsbin for a few different options:
http://jsbin.com/akowix/1/
What does your html look like?

*

*Do you have an element with both the "button" class and the "button-green" class?

*Or do you have an element with the "button" class that contains an element with the "button-green" class?

*Or do you have two different elements, one with the "button" class and one with the "button-green" class that you want the hover rule applied to both?


text:
Q: iOS Delegate returning nil (Swift 1.2) I'm trying to write a little RSS parser for my app, I have a XML parser class that i'm trying to implement a delegate into so my RSS class can be told when parsing is complete. But i'm having some issues.
So i have my delegate:
protocol MyXmlDelegate
{
    func onComplete ()
}

then in my XML parser class I have reference to it:
var someDelegate: MyXmlDelegate?

I call the delegate function when needed:
public func parserDidEndDocument(parser: NSXMLParser) {
    println("parsing finished")

    if someDelegate == nil {
        println ("Delegate nil bro")
    }
    else
    {
        someDelegate!.onComplete()
    }
}

then my RSS class implements the delegate:
class RSSFeed : NSObject, MyXmlDelegate

the class sets the parser' delegate to self:
init (feedURL url: String)
{
    super.init()

    parser = XMLParser(contentsOfURL: NSURL (string: url)!)!
    parser!.someDelegate = self
}

the rss class implements the delegate function:
func onComplete() {
    println ("on complete...")
}

Now when I run the app, the parser completes and prints:
"parsing finished",
"Delegate nil bro"
So why is my delegate nil?
Have I missed something obvious?


text:
Q: Why does the verb 'get' occur in these sentences? Let's look at the following sentences.
I got bored while watching serials.
His father got him the mobile.
She got married to John.
Why does the verb 'get' occur in these sentences?
The first sentence can be written as:
I was bored while watching serials.
The second one can be written as:
His father gave him the mobile.
The third one can be written as:
She was married to John.
Then what the verb get doing here?
Please make me know each of the sentences with explanation.

A:
I was bored while watching the series.

At that time, you had that state.  We have no idea when or why your boredom began, only that it overlapped your viewing of a television program.  This might imply that you didn't pay much attention to the show because you were already bored.

I got bored while watching a series.

At that time, you acquired that state.  Your boredom began during the show.  This might imply that your boredom is the result of the show.

His father gave him the cell.

This has nothing to do with when his father acquired the phone.  This action is the son's acquisition.

His father got him the cell.

This has little to do with when the son acquired the phone, or even whether he has.  This action is the father's acquisition.  It's possible that the father got the phone as a gift for his son, but the son doesn't have it yet.

She got married to John.

That implies a wedding.  Marriages generally start with one.

She was married to John.

That might suggest a divorce.  Without further context, it places the entire marriage in the past, not just its beginning.

A: In each of these sentences, "got" is simply an informal way of communicating. "I got bored while watching serials" could be said like this: "I became bored while watching serials." "I was bored while watching serials" is grammatically correct, but it does not mean the same thing as "I got bored while watching serials." "I was bored while watching serials" means that you were bored while you were watching serials. "Got" in this sentence refers to becoming bored, not simply being bored. "I became bored while watching serials" is the proper and more formal way of saying "I got bored while watching serials," because it tells us that you were not bored when you started watching serials, but you found them boring after a little while.
"His father got him the mobile" is describing someone's father either giving or buying him a mobile phone. A more formal way of saying it would be "His father gave him the mobile," or "His father bought him the mobile." Both of these sentences are a more formal way of saying "His father got him the mobile."
"She got married to John" is referring to a person becoming married to someone else. In informal English, we often say that two people "get married" instead of "become married." For example, "Are you going to get married?" "Did Anna get married to Dave?" The more formal way to say these sentences would be "Are you going to marry?" and "Did Anna marry Dave?" You could also say "Are you going to become married?" and "Did Anna become married to Dave" although this doesn't sound as natural as the first example. Thus, "She got married to John" could be more formally said as "She became married to John" or "She married John."
In each of these sentences, the verb "get" is being used informally. You will often hear native English speakers use the verb "get" as a general substitute for longer, more formal verbs.


text:
Q: Внести дополнительный параметр в скрипт День добрый! В наличии имеется башовый скрипт на роутере, переключающий провайдера с основного на резервный и наоборот. Скрипт рабочий, но попросили добавить туда дополнительный параметр avg rtt>50. Т.к. я совсем ещё зелень в баше, то прошу помощи. Куда можно запихнуть этот параметр, подскажите, пожалуйста? Код прикрепляю ниже.
#!/bin/bash
hos=$(hostname)
dat=$(date +"%Y-%m-%d")
t=$(date | cut -d " " -f5)
interf=$(/usr/sbin/ip route show | grep -n 1 | grep "1:" | cut -d " " -f5) #check default interface
tcf=$(timeout 3s ping -c 1 1.1.1.1 | grep time= | cut -d "=" -f4 | cut -d " " -f1 | cut -d "." -f1 ) #check CF dns resolver
tg=$(timeout 3s ping -c 1 8.8.8.8 | grep time= | cut -d "=" -f4 | cut -d " " -f1 | cut -d "." -f1 ) #check google dns resolver
tn=$tcf || $tg #check if one of dns providers in down, but internet is available
#echo $tn
if [[ -n $tn && $tn -lt 300 ]]; then #checking for ping >0 and ping time less 100 ms, if not - internet is down/weak
echo "[$t] $hos connection check success, on $interf with CF $tcf and Google $tg $dat $interf" » /var/log/failover/failover$dat.log
else
if [[ $interf == *"eno2"* ]]; then #if eno1 is default interface, we need to change it to eno2 with failover provider
/usr/sbin/ifup eno1 && sleep 5 #up reserve interface
echo "[$]$hos primary interface is now eno1 $dat $interf" » /var/log/failover/failover$dat.log
curl -X POST -H "Content-type: application/json" -d '{ "text": "'$hos' primary provider is now OBIT" }' 'https://hooks.slack.com/services/T1FRQ6K51/B01RCPMP940/8ybcgn..'
bash /opt/scripting/telegram 'primary provider is now OBIT'
else
/usr/sbin/ifup eno2 && sleep 5 #up interface
echo "[$]$hos primary interface is now eno2 $dat $interf" » /var/log/failover/failover$dat.log
curl -X POST -H "Content-type: application/json" -d '{ "text": "'$hos' primary provider is now GIS" }' 'https://hooks.slack.com/services/T1FRQ6K51/B01RCPMP940/8ybcgn..'
bash /opt/scripting/telegram 'primary provider is now GIS'
fi
fi


text:
Q: How to customize Bluemix push notification? I am using bluemix ibm-mfp-push and ibm-mfp-core for push notification for my hybrid mobile application.
I have added all the icons and splashscreen in the project but still whenever i am sending notification,it's showing a start icon.I want to change this star icon with my app icon.Also i need to redirect my user to some proper screen on click of push notification.
Any reference or examples will be appreciated...

A: You can customize your apps icons in the Cordova config.xml file using the <icon> tag.  Different devices will used different sized icons for push notifications, so you will need to ensure that you provide icons sized for each of the device types you'd like to support.
Here is an example of the icon configuration for Android and iOS:
<platform name="android">
    <!--
        ldpi    : 36x36 px
        mdpi    : 48x48 px
        hdpi    : 72x72 px
        xhdpi   : 96x96 px
        xxhdpi  : 144x144 px
        xxxhdpi : 192x192 px
    -->
    <icon src="res/android/ldpi.png" density="ldpi" />
    <icon src="res/android/mdpi.png" density="mdpi" />
    <icon src="res/android/hdpi.png" density="hdpi" />
    <icon src="res/android/xhdpi.png" density="xhdpi" />
    <icon src="res/android/xxhdpi.png" density="xxhdpi" />
    <icon src="res/android/xxxhdpi.png" density="xxxhdpi" />
</platform>

<platform name="ios">
    <!-- iOS 8.0+ -->
    <!-- iPhone 6 Plus  -->
    <icon src="res/ios/icon-60@3x.png" width="180" height="180" />
    <!-- iOS 7.0+ -->
    <!-- iPhone / iPod Touch  -->
    <icon src="res/ios/icon-60.png" width="60" height="60" />
    <icon src="res/ios/icon-60@2x.png" width="120" height="120" />
    <!-- iPad -->
    <icon src="res/ios/icon-76.png" width="76" height="76" />
    <icon src="res/ios/icon-76@2x.png" width="152" height="152" />
    <!-- iOS 6.1 -->
    <!-- Spotlight Icon -->
    <icon src="res/ios/icon-40.png" width="40" height="40" />
    <icon src="res/ios/icon-40@2x.png" width="80" height="80" />
    <!-- iPhone / iPod Touch -->
    <icon src="res/ios/icon.png" width="57" height="57" />
    <icon src="res/ios/icon@2x.png" width="114" height="114" />
    <!-- iPad -->
    <icon src="res/ios/icon-72.png" width="72" height="72" />
    <icon src="res/ios/icon-72@2x.png" width="144" height="144" />
    <!-- iPhone Spotlight and Settings Icon -->
    <icon src="res/ios/icon-small.png" width="29" height="29" />
    <icon src="res/ios/icon-small@2x.png" width="58" height="58" />
    <!-- iPad Spotlight and Settings Icon -->
    <icon src="res/ios/icon-50.png" width="50" height="50" />
    <icon src="res/ios/icon-50@2x.png" width="100" height="100" />
</platform>

You can find more information here:
https://cordova.apache.org/docs/en/latest/config_ref/images.html


text:
Q: Visual studio code, debug not working Hello i have problem with debug my app of node and visual studio code. When i tried run debug in visual i saw text " Debugger listening on port 30108
 " but when i open my browser on localhost:30108 there is only information somethig like this
Type: connect
V8-Version: 4.5.103.36
Protocol-Version: 1
Embedding-Host: node v4.4.7
Content-Length: 0

on localhost:3000 (default app port) there is only error
" This site is unreachable "
So how to do, to be able to debug app with running app in browser ?

A: If you do a node app.js or npm start (or whatever for your project) in a terminal/command window, does your project also start successfully?  Which OS are you using?  Any firewall issues going on?
If you can access the site in your browser outside of VS Code, check my "Third attempt" documented here.  Essentially, you need to edit both your launch.json and your package.json to indicate the port you are going to use. My examples follow the npm run {script name} format.  You should be able to tailor it to suit.
launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "cwd": "${workspaceRoot}",
            "runtimeExecutable": "npm.cmd",
            "runtimeArgs": [
                "run", "start"
            ],
            "port": 5858,
            "skipFiles": [
                "<node_internals>/**/*.js"
            ]
        }
    ]
}

package.json
"scripts": {
  "start": "node --inspect=5858 src/app.js",
}

Essentially, you need to ensure you are launching your app the same way you would from the command line.  Then, ensure you have the matching port info in both files (and their respective locations) mentioned above.
More info available here for alternate/additional configuration options for debugging.


text:
Q: Split String by "," I try to split a String by ",". Here is my code:
public class Test{

     public static void main(String []args){
         String s = "asdf, dfdf, ,ego, goggel,";
         s.split("\\s*,\\s*")
     }
}

I get this as output: ["asfd", "dfdf", ,"ego", "googel"]
But I want this: ["asdf", "dfdf", ,"ego", "googel",]
If there is just a comma at the end (ore more) it should be splitted too.
Can anyone help me?

A: To keep trailing empty element, you need to specify the limit parameter
s.split("\\s*,\\s*", -1);

Read more on String#split  docs


text:
Q: Removing gloss effect from an icon in iOS 4.3 I am currently trying to remove the gloss effect from an iOS icon using XCode 4.
I have set the 'Icon already includes gloss effect' (UIPrerenderedIcon) property to YES/true.
The gloss effect is successfully removed from the icon when i run my app through the iPhone 5.0 simulator.
However, the gloss effect is still visible when I run the app through the iPhone 4.3 simulator.
Can anyone tell me how to disable the gloss effect in both iOS versions?
My info.plist file reads as follows
<key>CFBundleIconFiles</key>
<array>
    <string>Icon.png</string>
    <string>Icon@2x.png</string>
    <string>Icon-72.png</string>
</array>
<key>CFBundleIcons</key>
<dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>Icon.png</string>
            <string>Icon@2x.png</string>
            <string>Icon-72.png</string>
        </array>
        <key>UIPrerenderedIcon</key>
        <true/>
    </dict>
</dict>

A: Clean your build, delete from simulator/Device..! It will work

A: I had the same problem. "CFBundleIcons" works for iOS 5.0 and "CFBundleIconFiles" works for 4.3.2 and 5.0. 4.3.2 doesn't recognise the newer "CFBundleIcons" icon property. I solved this by including a "UIPrerenderedIcon"=true at the top-level to match the "CFBundleIconFiles" array. The nested "UIPrerenderedIcon" key in your example code only applies to iOS 5.0. You should skip the "CFBundleIcons" if you want to field for both 4.3.2 and 5.0.
I think your plist should look like this (removing the "CFBundleIcons" array):
<key>CFBundleIconFiles</key>
<array>
    <string>Icon.png</string>
    <string>Icon@2x.png</string>
    <string>Icon-72.png</string>
</array>
<key>UIPrerenderedIcon</key>
<true/>

Search for "CFBundleIcons" on this page: http://developer.apple.com/library/IOs/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/App-RelatedResources/App-RelatedResources.html

A: The technical document states that you must ensure that this value is boolean and not a string litteral "YES". Check if you have correct value defined by viewing plist as a source list.


text:
Q: how to call a function on [browser tab close,browser close,backforward,refresh] i need to code for browser in js/jQuery to execute/call a function on browser close, on browser tab close, back, forward, refresh.

A: you can use this code
window.onbeforeunload = function(e) {
  var dialogText = 'are you sure?';
  e.returnValue = dialogText;
  return dialogText;
};

support
Feature         Chrome  Edge    Firefox (Gecko) IE  Opera   Safari
Basic support   1.0     (Yes)   1               4   12      3

A: You can use window.load, window.onunload and for back and forward use browser history.
you can find more on https://developer.mozilla.org/en-US/docs/Web/API/History_API


text:
Q: jwt auth - take action based on role and scope permissions I am using keycloak 20.0.3 and I want to protect my .net core 7 web api project with keycloak token.
I coded the exact content of the program.cs file as follows.
program.cs
    builder.Services.AddControllers(options =>
    {
        options.Filters.Add(new ValidateFilterAttribute());
    }).AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreReadOnlyFields = true;
        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault | JsonIgnoreCondition.WhenWritingNull;
    });

    builder.Services.Configure<ApiBehaviorOptions>(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });
    builder.Services.AddEndpointsApiExplorer();

    #region Swagger
    builder.Services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "IventoryManagement.API", Version = "v1" });
        c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
        {
            Name = "Authorization",
            Type = SecuritySchemeType.Http,
            Scheme = JwtBearerDefaults.AuthenticationScheme,
            BearerFormat = "JWT",
            In = ParameterLocation.Header,
            Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 1safsfsdfdfd\"",
        });
        c.AddSecurityRequirement(new OpenApiSecurityRequirement {
            {
                new OpenApiSecurityScheme {
                    Reference = new OpenApiReference {
                        Type = ReferenceType.SecurityScheme,
                        Id = JwtBearerDefaults.AuthenticationScheme,

                    }
                },
                new string[] {}
            }
        });
    });
    #endregion

    #region JWT
    builder.Services
        .AddAuthentication(options =>
        {
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.RequireHttpsMetadata = false;
            options.Authority = builder.Configuration["Keycloak:ServerRealm"];
            options.Audience = "inventory-client";
            options.IncludeErrorDetails = true;
            options.SaveToken = true;

            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = builder.Configuration["Keycloak:ServerRealm"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Keycloak:PublicKey"])),
            };
        });
    builder.Services.AddAuthorization(options =>
    {
        options.AddPolicy("create", policy => policy.RequireClaim("create:company"));
        options.AddPolicy("update", policy => policy.RequireClaim("update:company"));
        options.AddPolicy("delete", policy => policy.RequireClaim("delete:company"));
        options.AddPolicy("get", policy => policy.RequireClaim("get:company"));

    });
    #endregion

    app.UseAuthentication();
    app.UseAuthorization();

The json token content is as follows.
    {
    "exp": 1676981831,
    "iat": 1676981531,
    "jti": "2a2cc216-3df0-4086-9ca5-8e16d05a2945",
    "iss": "http://localhost:2011/realms/InventoryRealm",
    "aud": "inventory-client",
    "sub": "022a83d1-42e3-40b2-ac11-542d87c5672f",
    "typ": "Bearer",
    "azp": "inventory-client",
    "session_state": "59f68e71-3216-40e6-8bb6-2a997334074c",
    "acr": "1",
    "realm_access": {
        "roles": [
        "offline_access",
        "default-roles-inventoryrealm",
        "uma_authorization"
        ]
    },
    "resource_access": {
        "realm-management": {
        "roles": [
            "view-identity-providers",
            "view-realm",
            "manage-identity-providers",
            "impersonation",
            "realm-admin",
            "create-client",
            "manage-users",
            "query-realms",
            "view-authorization",
            "query-clients",
            "query-users",
            "manage-events",
            "manage-realm",
            "view-events",
            "view-users",
            "view-clients",
            "manage-authorization",
            "manage-clients",
            "query-groups"
        ]
        },
        "broker": {
        "roles": [
            "read-token"
        ]
        },
        "inventory-client": {
        "roles": [
            "Super Admin Role",
            "Computing Role",
            "uma_protection",
            "Admin Role",
            "User Role"
        ]
        },
        "account": {
        "roles": [
            "manage-account",
            "view-applications",
            "view-consent",
            "view-groups",
            "manage-account-links",
            "delete-account",
            "manage-consent",
            "view-profile"
        ]
        }
    },
    "authorization": {
        "permissions": [
        {
            "scopes": [
            "create:company",
            "update:company",
            "get:company",
            "delete:company"
            ],
            "rsid": "f2f036b2-4921-4e2b-9216-996d8cc5a349",
            "rsname": "Company Resource"
        },
        {
            "rsid": "c59c75c9-3bbe-4a1c-8671-71e3d4b975fc",
            "rsname": "Default Resource"
        }
        ]
    },
    "scope": "openid profile email",
    "sid": "59f68e71-3216-40e6-8bb6-2a997334074c",
    "email_verified": false,
    "name": "super user test",
    "preferred_username": "testuser001",
    "given_name": "test",
    "family_name": "user test",
    "email": "test@gmail.com"
    }

I made a definition on the controller as follows, that is, according to the scope permissions

[![This is the result I get with postman, but it shows no permissions. But the user has permission. I don't understand where I am doing wrong.
2]I normally get User Roles and scope permissions, but when I specify it with "policy" it shows as no permissions.]2


text:
Q: one accept call for multi client requests To begin with, I know there are ways to handle multiple client requests by forking or threading. But I cannot understand why there cannot be multiple acceptance by the server without forking or threading. accept() call can simply accept all process wish to connect to it. Why cannot the the call(accept()) go on unless a client cut its connection??
server does socket(), listen() and bind() with blocking(default) way
client does likewise by default socket() and connect()
What I think is accept's returned value will be for the recent child. But in reality it blocks until the prior client(s) cut its connection.

A:
I wonder whether there is file-descriptor which is returned by accept() overwriting? If not, how?

There is no overwriting; accept() creates a new connected socket, and returns a new file descriptor referring to that socket - a new, distinct one each time. Of course, a server which manages all client connections without creating other threads must store all those file descriptors, e. g. in an array.


text:
Q: Importing different Django projects settings I am trying to import different Django projects settings file from the same python module.
project_path = ["/home/Desktop/test1", "/home/Desktop/test2", "/home/Desktop/test3"]
for j, i in enumerate(project_path):
    if os.path.exists(i):
        sys.path.append(i)
        os.system("fm -rf " + project_path[j - 1] + "/settings.pyc")
        import settings
        print "settings file path>>>", settings.__file__
        project_directory = os.path.dirname(settings.__file__)
        print "Application direcotry>>>", project_directory
        project_name = os.path.basename(project_directory)
        print "Application name>>>", project_name
        sys.path.append(os.path.join(project_directory, '..'))
        project_module = __import__(project_name, '', '', [''])
        # Set DJANGO_SETTINGS_MODULE appropriately.
        sys.path.remove(i)

and I am getting the following results:
settings file path>>> home/Desktop/test1/settings.pyc
Application direcotry>>> home/Desktop/test1
Application name>>> test1
settings file path>>> home/Desktop/test1/settings.pyc
Application direcotry>>> home/Desktop/test1
Application name>>> test1
settings file path>>> home/Desktop/test1/settings.pyc
Application direcotry>>> home/Desktop/test1
Application name>>> test1

My question is even I am removing the projects path and appending new one then also it is importing the same application path. So I am not able to import the next application path.
I even tried to reload the settings file.
import settings
settings = reload(settings)

A: Try to import with package name and comment unrelevant lines.
Make sure folder test1/test2/test3 is package first. If not, add __init__.py inside the folder.
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys

project_path = ["/home/Desktop/test1", "/home/Desktop/test2", "/home/Desktop/test3"]

for path in project_path:

    sys.path.append(path)
    package_name = path.split('/')[2]

    cmd = 'import ' + package_name + '.settings'
    sys.path.remove(path)


text:
Q: Is it possible to programatically alter tables with Core Data I'm working on a project in which I might need to change my local database, according to information fetched from a server.I've read about Core Data, but from all I saw it uses a pre-defined database structures, and I haven't found a way to alter a table by code with it.I was wondering - should I use Core Data for this use? or should I stick with low-level objective-c wrap for SQLite?Tnx in advance!

A: I am going to go ahead and say "no, that is not a good idea" mainly because core data requires a lot of generated code to work properly...code which is generated in the XCode environment, not in the application environment.
For example, if you come up with schema for your data, XCode creates data entity objects and links them in specific ways which you shouldn't tamper with. If you were to attempt to alter the schema in real time, you would have to effectively regenerate all those entities and their linkages...which seems impossible. In my experience, any core data schema change requires a clean, delete and reinstall of the application before it will run again as well as resetting the host device's data entirely in some cases to get rid of the old data.
So no...seems unlikely to work.


text:
Q: Why extra subquery needed for filtering out where clause? First of all. Sorry for the vague title. I couldn't figure out how to frame it. With the sample code, I hope you can understand my doubt.
The task was to find out the top three facilities in a club in terms of revenue generated.
I thought this is the final code.
 SELECT x,y as rank
    FROM tableA
 where rank <=3;

But this says the rank column doesn't exist. So I have to include this in another subquery to filter the top 3 ranks.
 SELECT x,rank
    FROM
 (SELECT x,y as rank
    FROM tableA
 ) as sub
 where rank<=3;

Why? I need one extra subquery? Why can't it filter using where clause in the original query?
Code for  Facility names, and their rank by revenue:
select res.name,rank() over(order by total desc) as rank
    from
(select fac.facid,fac.name,sum(slots*
                case
                    when memid=0 then guestcost
                    else membercost
                    end) as total
    from cd.bookings bks
    inner join cd.facilities fac
        on bks.facid=fac.facid
    group by fac.facid
order by total desc) as res

What I thought would work:
select res.name,rank() over(order by total desc) as rank
    from
(select fac.facid,fac.name,sum(slots*
                case
                    when memid=0 then guestcost
                    else membercost
                    end) as total
    from cd.bookings bks
    inner join cd.facilities fac
        on bks.facid=fac.facid
    group by fac.facid
order by total desc) as res
where rank<=3;

     (why this don't work??)

What works :
select name, rank
    from
(select res.name,rank() over(order by total desc) as rank
    from
(select fac.facid,fac.name,sum(slots*
                case
                    when memid=0 then guestcost
                    else membercost
                    end) as total
    from cd.bookings bks
    inner join cd.facilities fac
        on bks.facid=fac.facid
    group by fac.facid
order by total desc) as res) as sub
where rank <=3;

A: Consider your first version of the query:
SELECT x, RANK() OVER (ORDER BY y) rnk
FROM tableA
WHERE rnk <= 3;

This is not legitimate, because you can't use aliases in the WHERE clause which were defined in a SELECT at the same level.  The issue here is that window functions execute generally execute last, before the filtering in the WHERE clause happens.  Instead, you need to compute the rank in a subquery and then filter on it:
SELECT *
FROM
(
    SELECT x, RANK() OVER (ORDER BY y) rnk
    FROM tableA
) t
WHERE rnk <= 3;

Note that some versions of SQL do allow window functions to be used in a QUALIFY clause:
SELECT x, RANK() OVER (ORDER BY y) rnk
FROM tableA
QUALIFY RANK() OVER (ORDER BY y) <= 3;

But Postgres does not support QUALIFY, so the subquery option is what you will likely have to use.


text:
Q: Windows Store app test certificate expired Suddenly, when running a build of my Windows Store app I got the error.

error APPX0108: The certificate specified has expired. For more information about
  renewing certificates, see
  http://go.microsoft.com/fwlink/?LinkID=241478

There is a link to the Renewing a certificate page but it's just a circular reference.

A: The information was there - just buried at the bottom of the page:

*

*Open the .appxmanifest file in Visual Studio (app manifest designer view)

*On the Packaging tab in the

*

*Click Choose Certificate

*In the dropdown, select Create test certificate...

*

*This blog post recommends you do not set a password

*Agree to replace the certificate

A: You have to create a new certificate:

*

*Open the Package.appxmanifest

*Select the Packaging tab

*Click Choose Certificate

*Click Create

*

*Enter your existing publisher name

*A password

*Agree to replace the certificate

Then you can update your microsoft store app


text:
Q: When the child class inherits the parent class, how can the original type be passed in public class Parent<T> where T : class, new()
{
    public class T data { get; set;}
}

public class Child : Parent<decimal>
{
}

Error: The type "decimal" must be a reference type to be used as the parameter "T in a generic type or method "Parent"
When the child class inherits the parent class, how can the original type be passed in?

A: Your code has some errors, change public class T data { get; set;} to public T data { get; set;}
and if you want to use value types in this case change your code to this:
public class Parent<T> where T: struct
{
   public T data { get; set;}
}

public class Child: Parent<decimal>
{
}


text:
Q: Accessing an element from an array fails on real server, works on localhost This issue is driving me crazy, could someone please tell whats going wrong with this!? (NOTE: Chances are that it is something really stupid but I can't seem to figure out.)
On a CodeIgniter framework I have a language key like this:
$lang['android'] = array
(
    'title' => 'Android apps',
    'image_id' => 5,
    'description' => 'Learn how to create your own Android app',
    'level' => 'Beginner'
);

Then on a view file I load this key like this:
<?php
    echo lang($course)['title'];
?>

This works perfectly on localhost, and if $course is 'android' it will print "Android apps". However this very same code does not work on the real server! It simply fails and shows me the error "PHP Parse error:  syntax error, unexpected '[', expecting ',' or ';' in [filename]"
Why does this happens? Is it probably a lower PHP version? If so how I could access this array key??
Additional info: Doing a
var_dump('android');

Throws:
array(4) { ["title"]=> string(12) "Android apps" ["image_id"]=> int(5) ["description"]=> string(40) "Learn how to create your own Android app" ["level"]=> string(8) "Beginner" }

Which is the expected value... So why does this happens?

A: Unbeliavable, yes I'm running a PHP server lower than 5.4... So dereferencing does not work.
I already solved it, you can paste the following function on your CodeIgniter:
function lang_arr($line, $key = '')
    {
        $CI =& get_instance();
        $line = $CI->lang->line($line);
        if ($key != '')
        {
            $line = $line[$key];
        }

        return $line;
    }

Paste it on the file "system/helpers/language_helpers" just next to the function "lang" which does not supports arrays.
And now you should be able to access language array keys like this:
$lang['word'] = array
(
    'key1' => 'value1',
    'key2' => 'value2'
);

On the code simply call:
echo lang_arr($word, 'key');

For example
echo lang_arr('word', 'key1'); //Will echo 'value1'

Thanks to all commenters it helped me to get on the right track.

A: <?php
$lang['android'] = array
(
    'title' => 'Android apps',
    'image_id' => 5,
    'description' => 'Learn how to create your own Android app',
    'level' => 'Beginner'
);
$course ='android'; //here you have to assign
echo($lang[$course]['title']);
?>


text:
Q: javascript variable turned out empty The following code (as a bookmarklet in chrome) does not work like I thought-----I could see alert popup but the content is empty.

javascript:window.location.href='http://new.cloudfile.co/transfer';var tmp=document.referrer;alert(tmp);

In fact "alert()" is for debug, I want to directly assign this referrer url to an inputbox, instead of using "document.execCommand('paste')", which turned out to be failure.
Anyway, why alert() got empty value here?
Please help, Thanks.


text:
Q: .NET 6 : HttpClient work with dynamic json response I'm using .NET 6. How work with json response from HttpClient without declaring a type?
I try do request with dynamic:
var http = new HttpClient();
var res = await http.GetAsync("https://api");
var body = await res.Content.ReadFromJsonAsync<dynamic>();

In debug mode I see that I get the correct value:

but then I try get access to field, I get an error
body['pagesCount']

A: Try following code
var resultType = new { refresh_task = "" }.GetType();
dynamic? result = await response.Content.ReadFromJsonAsync(resultType);


text:
Q: Does jQuery Validate conflict submit functions other than form button (image/hyperlink)? I will give a few examples of the form issue I am running into. I have already been chastised for using 'obstrusive js' and trying to do a better job as a programmer but it makes it utterly frustrating when the 'obtrusive js' works and the unobtrusive does not. The overall goal is give submit() like behavior to something other than an actual form type=submit button, in this case an image link.
EXAMPLE 1
Example Link 1
Theory here would be that on the click of ID "pw_submit", the form input is disabled (works), the submit function is called which triggers validate. The latter does not happen. Moving on.
EXAMPLE 2 -
See this JS fiddle: http://jsfiddle.net/YkuAk/
Works but with regular html button, not what I want/need
As I mention above, example 2 "works" in the sense validate is called but it does NOT achieve our goal of using a hyperlink, image, etc to initialize the submit() function.
EXAMPLE 3 - "obtrusive JS"
Third example with Obtrusive Javascript
This example works without any issue but as I mention above, have been criticized for using inline js. While in my mind it is NO different than the code in example one, clearly it is.
Any ideas?

A: the validation plugin binds its own listener to form submit event. In the first fiddle, take the $("#someform").validate(); outside of the click event callback. The way it is now, the plugin is adding another submit listener to the form.
EDIT:
misread the fiddle. The validation plugin doesn't validate disabled inputs.

If you really want to validate all disabled form fields also, the
  relevant line in the plugin is
      .not(":submit, :reset, [disabled]") to which you can add or remove
  functionality.

src: http://forum.jquery.com/topic/jquery-jquery-validate-validating-disabled-inputs

A: I am not sure - may have found the answer but in Example 1, when I remove the event to disable input fields - it appears the function runs properly. Testing further but not sure why this is the case regardless.


text:
Q: Passing Arguments into a thread in Scala I am learning Scala and as an exercise I am transforming some python (PySpark) code to Scala (spark/Scala) code. Everything was going ok until I started dealing with scala threads. So,  Do you now how can I re write the following code to scala?
Thank You in Advance!
def load_tables(table_name, spark):
    source_path = f"s3://data/tables/{table_name}"
    table = spark.read.format("csv").load(source_path)
    table.createOrReplaceTempView(table_name)

def read_initial_tables(spark):
    threads  = []
    tables = ["table1", "table2", "table3"]
    for table in tables:
        t = threading.Thread(target=load_tables, args=(table, spark))
        threads.append(t)
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

A:
...passing arguments into threads...

Scala uses the Java standard libraries, and starting a thread in Java is a little bit different from starting a thread in Python. The main difference is, in Python you can choose any target (i.e., any function or callable object) for the thread's top-level, and you can pass in any args that you like. But when you start a Java thread, the top-level function must be a no-argument method named run() that belongs to an object that implements java.lang.Runnable.
Your Python thread's top-level function is load_tables(table, spark). So, what you need in your Scala program is a thread whose top-level function is a run() function that calls load_tables(table, spark).
I don't actually know Scala, but maybe the example on this web page will steer you in the right direction: https://alvinalexander.com/scala/how-to-create-java-thread-runnable-in-scala/
Basically, I think all you have to do is follow his example, and put your load_tables(table, spark) call in the place where his example says, "your custom behavior here."

A: Solomon is right. I could not describe it better. Taking advantage of the syntactic sugar Scala provides over Java, your Python code is not longer in Scala:
  def load_tables(table_name: String, spark: SparkSession): Runnable = () => {
    val source_path = s"s3://data/tables/$table_name"
    val table = spark.read.format("csv").load(source_path)
    table.createOrReplaceTempView(table_name)
  }

  def read_initial_tables(spark: SparkSession): Unit = {
    val tables = List("table1", "table2", "table3")
    val threads = for {
      table <- tables
    } yield new Thread(load_tables(table, spark))
    for (thread <- threads)
      thread.start()
    for (thread <- threads)
      thread.join()
  }

You might ask where is the run() method, Solomon was talking about. Actually, the empty parentheses () after the = sign the load_tables starts with, represent the no-argument parameter list that is passed to the run method, while the body of the run method is the block of code between curly braces after the => sign.
So a call to load_tables actually returns a new Runnable instance.
This is called a Single Abstract Method which is just a syntactic sugar that gives the impression that load_tables looks callable as in Python, but it's not actually. Only it's return type is, because it returns a Runnable object. This short version is only achievable because Runnable is a Functional Interface.
I'm not a specialist in Spark, so I'm not sure if this is the idiomatic way to code in Scala with Spark, but it's a good starting point to go from here.

A: Maybe not really what you are looking for but it could be interesting. Scala has some very convenient stuff for parallelization of collections with the method .par:
val parallelizedList = List(1, 2, 3, 4).par
parallelizedList.foreach(i => println(i)) // this is executed in parallel, not sequentially
// output:
// 2
// 4
// 1
// 3

So you can use this syntax with spark to read multiple tables in parallel:
def loadTable(tableName: String, spark: SparkSession): Unit = {
    val sourcePath = f"s3://data/tables/$tableName"
    val table = spark.read.format("csv").load(sourcePath)
    table.createOrReplaceTempView(tableName)
}

val tableNames = List("table1", "table2", "table3")
tableNames.par.foreach(name => loadTable(name, spark))

EDIT

*

*If you use Scala 2.12, parallel collections will be available. They have been moved to their own module in 2.13: scala/scala-parallel-collection

*

*libraryDependencies += "org.scala-lang.modules" %% "scala-parallel-collections" % "1.0.0"

*import scala.collection.parallel.CollectionConverters._

*Be careful if the actions you execute on a parallel collection modify the same data. This can lead to non-deterministic behaviour (see @Alin Gabriel Arhip's comment below).

*Apparently, it is not really encouraged to use parallel collections with Spark (also see @Alin Gabriel Arhip's comment below), but I've never had any problem with them so far (although I usually only use them for very simple processing that I know won't use all available resources)


text:
Q: Time series analysis, moving-average model, ARMA model I'm reading documents about time series analysis, including Autoregressive–moving-average model, Moving average model, Wold's theorem, etc.

The notation MA(q) refers to the moving average model of order q:
$$X_t = \mu + \varepsilon_t + \theta_1 \varepsilon_{t-1} + \cdots + \theta_q \varepsilon_{t-q} \qquad (*)$$
where μ is the mean of the series, the $θ_1$, ..., $θ_q$ are the parameters of the model and the $ε_t$, $ε_{t−1}$,..., $ε_{t−q}$ are white noise error terms.

1) I would understand if we would want to express $X_t$ as a linear combination of past values $X_{t-1}$, $X_{t-2}$, $X_{t-3}$, etc. i.e. :
$$X_t = a_1 X_{t-1} + a_2 X_{t-2} + ... + a_q X_{t-q} + \epsilon_t$$
and if we would want to find optimal values for $(a_i)_{i \leq q}$.
This would make sense to me (by the way, does this approach exist, what's its name?).

2) But here I don't understand why we try to express $X_t$ in terms of past values of something which is totally uncontrolled and has nothing to do with $(X_t)$ : $\epsilon_t$, i.e. some random white noise!
Why do we do this in the moving average model?
(By the way, how are exactly defined the $\epsilon_t$ ?)


text:
Q: How to Hide Content on Status Bar When Scrolling on iPhone X I have a UICollectionView that scrolls vertically. The collection view is a form. It has multiple sections, each section has a few items in it. The top section has a header which is pinned to the top of the view so it remains in place as the content scrolls.
The problem is, as I scroll the content up, the items show against the status bar. How do I get the items to be hidden as I scroll? Can I set a color to the status bar, or set an inset on the view?
Notice in the behavior in the screenshot below:

A: The usual thing is to pin the top of the collection view to the top Safe Area layout guide.
(But the whole thing looks a lot better, in my opinion, if you are also inside a navigation controller.)
EDIT It appears from your subsequent query (in a comment) that you are using a UICollectionViewController (you did not mention that in your question). So the answer boils down to: never use a "bare naked" UICollectionViewController. Always use it as a child view controller, in one of these ways:

*

*As the child of a UINavigationController, because the collection view's top will then be concealed by the navigation bar

*Or, through a Container View and an embed segue, because then you can pin the container view's top to the safe area top.


text:
Q: "Saving on the parrot's chocolate is futile" In Catalan there is an expression "ser la xocolata del lloro" that can be translated as "saving by not giving chocolate to the parrot is futile", conveying the meaning that when a household wants to save money, there are ways by which not much saving is going to be made. As an example, if you stop giving little bits of chocolate to the parrot to enjoy, although it looks like a saving measure, it's more posturing than real savings, so that doesn't make much difference: you actually won't end up saving much, because the amount of chocolate is very small.
Is there any equivalent expression in the English language for the same kind of saving efforts that won't make a difference?

A: Not in exactly the same vein but "rearranging deck chairs on the Titanic" also speaks to worrying about detail that won't make a difference to the looming disaster.

A: The term penny-wise refers to being "careful in dealing with small sums of money or small matters".  It's commonly found in the phrase penny wise, pound foolish, meaning "Someone who is penny wise, pound foolish can be very careful or mean with small amounts of money, yet wasteful and extravagant with large sums."
You may also find the term bikeshedding of interest:

The word ... implies technical disputes over minor, marginal issues conducted while more serious ones are being overlooked. The implied image is of people arguing over what color to paint the bicycle shed while the house is not finished.

The term cheeseparing economy refers to "a useless economy."  According to ngrams for cheeseparing economy it is occasionally but not frequently used.  The phrase "strain at a gnat and swallow a camel", from Matthew 23:23, means "to fuss about trifles while ignoring more serious matters" (per reference.com) or "to criticize other people for minor offenses while ignoring major offenses" (per thefreedictionary.com).
For related phrases, also see questions #41508 and #39726.

A: Slightly vulgar, but pissing in the ocean is a metaphor for an action that won't make much of a difference. This may specifically be an Australianism.

A: One idiomatic way to refer to a measure that doesn't make much difference would be a drop in the bucket or a drop in the ocean.

drop in the bucket
(idiomatic) An effort or action having very little overall influence, especially as compared to a huge problem.
A $100 donation from an individual is generous, but it is a drop in the bucket compared to the $100,000 fundraising goal.

A: I don't know how widespread it is, but in my experience the phrase "counting paper clips" is something like this.
It refers to trying to bring a company's finances under control by accounting for every bit of stationery: this is usually both time-consuming and ineffective.

A: I've heard it as being penny-wise and pound-foolish. It means being thrifty with small sums and foolish with large sums. We use it in the U.S., even though we use dollars.

A: As RegDwight says, drop in the bucket (American), and drop in the ocean (British) are commonly used, but they both often carry the implication that some minor "positive" contribution will have no detectable effect on the overall situation.
It's declined a bit from its heyday around WW2, but don't spoil the ship for a hap'orth of tar is a well-established adage more specifically focussed on the downside of excessive scrimping.
A hap'orth there is a half-penny's worth, and the tar is used in the final caulking process to make the hull completely waterproof before the newly-built vessel is lowered from dry dock into water. Making a small saving there would indeed be a mistake if your boat sank on its maiden voyage!

A: There is an expression

won't amount to a hill of beans

(sometimes also phrased as won't add up to a hill of beans)
Since beans are so inexpensive, even a hill of them won't be worth much.
As an example:

All our efforts won't amount to a hill of beans if we can't get that valve closed.

A: Apart from the obvious false economy have you considered robbing Peter to pay Paul?


text:
Q: How to merge two different object type in one object? callingmethod(){
File f=new File();
//...
String s= new String();
//...

method( f + s);    // here is problem (most put f+s in object to send it to method)
}

cant change method args
method(Object o){
//...
//how to split it to file and String here
}

for any thing not clear ask plz

A: The cleanest and most idiomatic way is to create a simple class to represent your pair:
static class FileString {
  public final File f;
  public final String s;
  FileString(File f, String s) {
    this.f = f; this.s = s;
  }
}

then write
method(new FileString(file, string));

inside method:
FileString fs = (FileString)o;
// use fs.f and fs.s

Depending on further details, use a nested class like in my example, or put it into its own file. If you keep it close to the place where you instantiate it, then you can make the constructor private or package-private, like I did. But these are just the finer details.

A: You can e.g. put it in an array:
method (new Object[] {f, s});

void method (Object o) {
    final Object[] arr = (Object[]) o;
    File f = (File) arr[0];
    String s = (String) arr[1];
}


text:
Q: Unable to read write on serial port in C++ I am writing a serial communication code in c++ on Visual Studio 2010. For this I try this example, which is working fine. Now, I try to send a string and read it back by shorting Rx and Tx pins of my hardware. Here is my code for sending string:-
char *buffer ="hello";
   DWORD bytesSend;
   DWORD errors;
   COMSTAT status;
   DWORD numWritten;
   WriteFile(hCom, buffer, strlen(buffer), &numWritten, NULL);
   printf("send succesfully\n");

and here is my receiving code:-
DWORD numRead;

  BOOL ret = ReadFile(hCom, buffer, 5, &numRead, NULL);

    if(!ret)
    {
        printf("Read Fail\n");
    }
    else
    {
        printf("%s\n",buffer);
    }

On running my code, receive is getting failed. So, please tell me where is the problem. here is my complete code.
#include "stdafx.h"

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

void PrintCommState(DCB dcb)
{
    //  Print some of the DCB structure values
    _tprintf( TEXT("\nBaudRate = %d, ByteSize = %d, Parity = %d, StopBits = %d\n"),
              dcb.BaudRate,
              dcb.ByteSize,
              dcb.Parity,
              dcb.StopBits );
}

int _tmain( )
{
   DCB dcb;
   HANDLE hCom;
   BOOL fSuccess;
   TCHAR *pcCommPort = TEXT("COM1"); //  Most systems have a COM1 port

   //  Open a handle to the specified com port.
   hCom = CreateFile( pcCommPort,
                      GENERIC_READ | GENERIC_WRITE,
                      0,      //  must be opened with exclusive-access
                      NULL,   //  default security attributes
                      OPEN_EXISTING, //  must use OPEN_EXISTING
                      0,      //  not overlapped I/O
                      NULL ); //  hTemplate must be NULL for comm devices

   if (hCom == INVALID_HANDLE_VALUE)
   {
       //  Handle the error.
       printf ("CreateFile failed with error %d.\n", GetLastError());
       return (1);
   }

   //  Initialize the DCB structure.
   SecureZeroMemory(&dcb, sizeof(DCB));
   dcb.DCBlength = sizeof(DCB);

   //  Build on the current configuration by first retrieving all current
   //  settings.
   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess)
   {
      //  Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
   }

   PrintCommState(dcb);       //  Output to console

   //  Fill in some DCB values and set the com state:
   //  57,600 bps, 8 data bits, no parity, and 1 stop bit.
   dcb.BaudRate = CBR_57600;     //  baud rate
   dcb.ByteSize = 8;             //  data size, xmit and rcv
   dcb.Parity   = NOPARITY;      //  parity bit
   dcb.StopBits = ONESTOPBIT;    //  stop bit

   fSuccess = SetCommState(hCom, &dcb);

   if (!fSuccess)
   {
      //  Handle the error.
      printf ("SetCommState failed with error %d.\n", GetLastError());
      return (3);
   }

   //  Get the comm config again.
   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess)
   {
      //  Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
   }

   PrintCommState(dcb);       //  Output to console

   _tprintf (TEXT("Serial port %s successfully reconfigured.\n"), pcCommPort);

   char *buffer ="hello";
   DWORD bytesSend;
   DWORD errors;
   COMSTAT status;
   DWORD numWritten;
    WriteFile(hCom, buffer, strlen(buffer), &numWritten, NULL);
    printf("send succesfully\n");

  DWORD numRead;
  BOOL ret = ReadFile(hCom, buffer, 5, &numRead, NULL);

    if(!ret)
    {
        printf("Read Fail\n");
    }
    else
    {
        printf("%s",buffer);
    }

   return (0);
}

Here is my output:-

A: Try flushing the file buffer after write.
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364439%28v=vs.85%29.aspx


text:
Q: My banner section is not showing in my static html website, rest is working fine I'm trying to host my static website on firebase everything is working fine except this banner code. All images of my website are working perfectly fine except these banner images and are placed in same folder. I would really appreciate it if anyone could help, many thanks in advance.

.pogoSlider{
    width:100%;
    height:874px!important;
    position:relative;
    overflow:hidden;
}
#column-left .pogoSlider,#column-right .pogoSlider,#content .pogoSlider{
    margin-bottom:20px;
}
.pogoSlider--banner .pogoSlider-slide{
    ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter:alpha(opacity=100);
    opacity:1;
}

.pogoSlider-slide{
    width:100%;
    height:100%;
    position:absolute;
    background-size:100% 100%;
    -webkit-background-size:100% 100%;
    -moz-background-size:100% 100%;
    -o-background-size:100% 100%;
    -ms-background-size:100% 100%;
    min-height:650px!important;
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    filter:alpha(opacity=0);
    opacity:0;
    -webkit-perspective:1300px;
    perspective:1300px;
    overflow:hidden;
}
.pogoSlider-loading{
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:#eaeaea;
    z-index:11;
}

MOBLIE  Finance

MOBLIE  REPAIRING

WE SELL MOBILE ACCESSORIES

BEST PRICE. IN AREA

A: Not sure the actual error but I suspect its your first .pogoSlider-slide element, which has a url of background-image:url(/public/images/home1.jpg) when I think you don't need that first / so background-image:url(public/images/home1.jpg)

A: You have set opacity: 0 in .pogoSlider-slide. Just remove these 3 lines (mentioned below), banner will show up.
.pogoSlider-slide{
    width:100%;
    height:100%;
    position:absolute;
    background-size:100% 100%;
    -webkit-background-size:100% 100%;
    -moz-background-size:100% 100%;
    -o-background-size:100% 100%;
    -ms-background-size:100% 100%;
    min-height:650px!important;
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; //***Remove this
    filter:alpha(opacity=0); //***Remove this
    opacity:0; //***Remove this
    -webkit-perspective:1300px;
    perspective:1300px;
    overflow:hidden;
}


text:
Q: Facebook Login PHP SDK works locally but not on the server hi my facebook login works fine on my local server, i make the app live, update 'app domains' on the settings page and also the 'Valid OAuth redirect URIs' on the product settings page, i am still getting the error:
"Graph returned an error:Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings."
I have tried multiple varieties of the domain, ive tried adding the /index.php page as well as the standard URL to the redirect URI's and still no luck.
Ive made sure the redirect URI in my code matches the one on facebook.
Im sure its something simple im missing but i cant see it
[index.php **request to API made][3]
[protected_page.php **redirect URI page][4]

A: It appears there are reported different variations of this bug recently: https://developers.facebook.com/bugs/518422995172099/
I'm going nuts with this issue since yesterday as well and can't seem to validate these domains at all.

A: They enabled oAuth whitelisting by default. How to fix: https://wp-native-articles.com/blog/news/how-to-fix-facebook-apps-error-cant-load-url-domain-url-isnt-included-apps-domains/


text:
Q: Python Email Parser not reading from text file I am trying to run the following code for reading the contents of the mail from a text file by using the parse() function of email.parser.Parser but continuously getting error as "TypeError: parse() missing 1 required positional argument: 'fp'"
from email.parser import Parser

with open('an_email.txt') as fp:
    mail_msg = Parser.parse(fp)

print(mail_msg)

I am unable to find a solution to this. Can please someone help on this one ?

A: parser is an instance method in the Parser class. That means that you must first create a Parser instance:
...
parser = Parser()
with open('an_email.txt') as fp:
    mail_msg = parser.parse(fp)