text:
Q: Binding of TextBlock inside Custom Control to dependency property of the same Custom Control I have a custom control with a TextBlock inside it:
<Style TargetType="{x:Type local:CustControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustControl}">
                <Border Background="Blue"
                        Height="26"
                        Width="26" Margin="1">

                        <TextBlock x:Name="PART_CustNo"
                                   FontSize="10"
                                   Text="{Binding Source=CustControl,Path=CustNo}"
                                   Background="PaleGreen"
                                   Height="24"
                                   Width="24"
                                   Foreground="Black">
                        </TextBlock>

                </Border>
             </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And this Custom control has a dependency property:
    public class CustControl : Control
{
    static CustControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustControl), new   FrameworkPropertyMetadata(typeof(CustControl)));
    }

    public readonly static DependencyProperty CustNoProperty = DependencyProperty.Register("CustNo", typeof(string), typeof(CustControl), new PropertyMetadata(""));

    public string CustNo
    {
        get { return (string)GetValue(CustNoProperty); }
        set { SetValue(CustNoProperty, value); }
    }

}

I want the value of "CustNo" property be transfered in "Text" property of TextBlock in each instance of the Custom Control.
But my:
Text="{Binding Source=CustControl,Path=CustNo}"

isn't working.
Isn't working also with Path=CustNoProperty:
Text="{Binding Source=CustControl,Path=CustNoProperty}"

A: Try the answers to this SO question. I think you'll want the third example. ie:
{Binding Path=CustNo, RelativeSource={RelativeSource TemplatedParent}}

A: You need a TemplateBinding, like
<TextBlock
   Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=CustNo}" />


text:
Q: Geometrical paraxial optics Why is geometrical optics treated in 2d? I actually never thought about it and calculated all the problems straightforward with the ABCD matrices. And then this question came to my mind for which I have no answer so far.

A: Usually optical systems are axially symmetric, so that you only need 2 d to understand the paths of all the rays traversing the system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shorter word for "Uncanny person"? (New Zealand english) As the title stated it's a simple question but to elaborate a bit more by giving a example...
I was watching a harmless video from YouTube via. The Short feature where two girls stated they "looked Like sisters" when they obviously did not briefly before doing a comparison video sort of thing then it cuts to one of the girls laughing where it's showing alot of the girls gum.
It wasn't really the gum laugh thing that took me off guard the whole video just felt strange and foreign to be honest as the two girl were no doubt real people but at the same time not.
TLDR: Is there a shorter word for an "uncanny person"?

A: Based on the feeling you described, I will propose:
creepy
From Oxford Languages:

causing an unpleasant feeling of fear or unease. "the creepy feelings
one often gets in a strange house"

A: It is unclear whether you mean the video or the girls are "uncanny". It is also unclear whether you are looking for a word that is (i) unique to, or (ii) would be understood in, New Zealand.
That said,
OED:
surreal, adj.
Having the qualities of surrealist art; bizarre, dreamlike.
1937   Burlington Mag. Jan. p. xiv/1   Some 'surreal' influence haunts the regions of the Black Forest.
MW
surreal adjective
1: marked by the intense irrational reality of a dream
Players traverse surreal worlds and duke it out with sentient poker chips, demonic clowns and boxing frogs across elaborate, multistage boss battles. — Alyse Stanley, Washington Post, 17 May 2022


text:
Q: I Want to render component when user scrolled on top in react native giftedchat I Have an onScroll Event that returns the current value of the current scroll value and I want to render the offer details card when the user scrolled on top of the message. anyone do you have any idea about this in react native ??
  const [scrolledRecord, setScrolledRecord] = useState(false);

  const prevScroll = 0;
  let currentScroll = 0;

              listViewProps={{
                scrollEventThrottle: 400,
                onScroll: ({nativeEvent}) => {
                  if (nativeEvent.contentOffset.y) {
                    currentScroll = nativeEvent.contentOffset.y;

                    if (currentScroll < prevScroll) {
                      setScrolledRecord(false);
                      console.log(currentScroll, prevScroll);
                    } else {
                      setScrolledRecord(true);
                    }
                  }
                },
              }}

     {scrolledRecord ? <ChatHeader item={userData} /> : null}

Here is current on scrolled values
56
597.8181762695312
717.8181762695312
981.4545288085938
1250.9090576171875
1509.8182373046875
1736.727294921875
1624.727294921875
1488.727294921875
1361.0909423828125
1210.54541015625
1106.54541015625
842.9091186523438
573.0908813476562
447.2727355957031
182.18182373046875
-6.181818008422852
-6.181818008422852 0
0

When the User Scrolled to the top then it returns the large number 123,123000 same as when the user scrolled to the button then it will render 0 sometimes -6
My Logic is not working as per my expectations


text:
Q: Java change main boolean from Thread how can I change a boolean which I defined in the Main class from inside a Thread? It doesn't seem to work using booleanName = true;.
Is there a way to change the variable's value?

A: As suggested by others, you should post your sample code. If you are asking if you can change the state of a variable from inside the run() method of a thread, yes, of course it's possible.
public class MyThread implements Runnable {

    private boolean b = true;

    public void run() {
        b = false;
        System.out.println(b);
    }

    public boolean getBoolean() {
        return b;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new MyThread());
        t.start();
    }
}

A: Changing the value works just like that. booleanName = false if booleanName is reachable from your thread code, or something like Main.setBooleanName(false) if it is not.
If you want to read that boolean from another thread, you also have to make sure that the new value is visible to your other thread. This can be done by making booleanName volatile, using a thread-safe boolean type like AtomicBoolean or entering/leaving a synchronized method or block before reading from booleanName.


text:
Q: Image stays stuck in the upper left-hand corner in CSS I have the following in-line style code:
<style>
.quote {
    background-color: #00FFFF;
    position: absolute;
    height: 50px;
    width: 300px;
    top: 250px;
    left: 500px;
    text-align: center;
};

#apple{
    position: absolute;
    top: 3000px;
    left: 600px;
}

#random{
    position: absolute;
    top: 500px;
    left: 500px;
}

and I'm trying to get the image with the apple id to move to a location different from where it's currently situated, which is in the upper left hand corner. Changing the coordinates of the other images and divs works fine, and I've experimented with changing the position of the apple image from fixed to absolute to relative and haven't found anything which allows me to move it to the center of the page.

A: It got me stunned for a second too but your problem comes from the semi-colon after .quote class! Remove it and your code will work just fine.
This is how it should look :
    .quote {
        background-color: #00FFFF;
        position: absolute;
        height: 50px;
        width: 300px;
        top: 250px;
        left: 500px;
        text-align: center;
    }

    #apple{
        position: absolute;
        top: 100px;
        left: 100px;
    }

    #random{
        position: absolute;
        top: 500px;
        left: 500px;
    }

A: there is a syntax error in your css
        .quote {
        background-color: #00FFFF;
        position: absolute;
        height: 50px;
        width: 300px;
        top: 250px;
        left: 500px;
        text-align: center;
        };
remove this ; and run your code


text:
Q: Android app crashes - Unable to instantiate activity ComponentInfo need your help!
I am new in Android and for some reason my app stopped working and crashes right on startup.
I am not sure if it is related but I've added maven to the project.
Here's the error log:
06-23 14:32:18.380: E/AndroidRuntime(1775): FATAL EXCEPTION: main
06-23 14:32:18.380: E/AndroidRuntime(1775): Process: com.app.test, PID: 1775
06-23 14:32:18.380: E/AndroidRuntime(1775): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.app.test/com.test.activities.SplashActivity}: java.lang.ClassNotFoundException: Didn't find class "com.test.activities.SplashActivity" on path: DexPathList[[zip file "/data/app/com.app.test-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
06-23 14:32:18.380: E/AndroidRuntime(1775):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at android.app.ActivityThread.access$800(ActivityThread.java:151)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at android.os.Handler.dispatchMessage(Handler.java:102)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at android.os.Looper.loop(Looper.java:135)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at android.app.ActivityThread.main(ActivityThread.java:5257)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at java.lang.reflect.Method.invoke(Native Method)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at java.lang.reflect.Method.invoke(Method.java:372)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
06-23 14:32:18.380: E/AndroidRuntime(1775): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.test.activities.SplashActivity" on path: DexPathList[[zip file "/data/app/com.app.test-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
06-23 14:32:18.380: E/AndroidRuntime(1775):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
06-23 14:32:18.380: E/AndroidRuntime(1775):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
06-23 14:32:18.380: E/AndroidRuntime(1775):     ... 10 more
06-23 14:32:18.380: E/AndroidRuntime(1775):     Suppressed: java.lang.ClassNotFoundException: com.test.activities.SplashActivity
06-23 14:32:18.380: E/AndroidRuntime(1775):         at java.lang.Class.classForName(Native Method)
06-23 14:32:18.380: E/AndroidRuntime(1775):         at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
06-23 14:32:18.380: E/AndroidRuntime(1775):         at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
06-23 14:32:18.380: E/AndroidRuntime(1775):         at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
06-23 14:32:18.380: E/AndroidRuntime(1775):         ... 13 more
06-23 14:32:18.380: E/AndroidRuntime(1775):     Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

here's the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test"
    android:versionCode="1"
    android:versionName="1.0" >

<uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="22" />
    <uses-permission
        android:name = "android.permission.INTERNET"/>
    <uses-permission
        android:name = "android.permission.BLUETOOTH_ADMIN"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.test.activities.SplashActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.test.activities.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                  <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.test.activities.MainMenuActivity"
            android:label="@string/title_activity_main_menu" >
        </activity>
    </application>

and here's the activity:
public class SplashActivity extends Activity{

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

        Thread StartTimer = new Thread(){
            public void run(){
                try {
                    sleep(2000);
                    Intent main = new Intent(SplashActivity.this, MainActivity.class);
                    startActivity(main);
                    finish(); //kills the current activity
                }
                catch (InterruptedException ex){}
            }
        };
        StartTimer.start();
    }
}

Here is the pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
        <groupId>com.squareup.okhttp</groupId>
        <artifactId>mockwebserver</artifactId>
        <version>2.4.0</version>
    </dependency>
    <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.3.1</version>
</dependency>

  </dependencies>
</project>

also here are the build path settings:

Dir structure:

A: As I know Maven build systems waiting some pathes, check you project, your sources should be located somewhere like:
/src/main/java/com/test  in your case.
Is your project have such structure?
And also I recommend to name groupid as "com.test"
https://spring.io/guides/gs/maven-android/


text:
Q: How to sum between dates using SQL? Look at the following UPDATED scenario (sorry that I fooled you with the un updated version - hope it will be clearer now) - it may seem simple to some people, and hopefully it is!
Explanation: Every row is a Request. Allocated is the number of people requested to an activity, total is the total amount of people for this country available for activities, and diff is... the diff between the total amount of people and Max people used.
And "Max people used..." is what everything else hangs on.
SHOULD BE:

COLLECTION OF REQUESTS WITH DIFFERENT START- AND END DATES

COUNTRY START DATE  END DATE    ALLOCATED   TOTAL    Max people used for this period    DIFF
China     NOV 1       NOV 2       2           5         4                                 1
China     NOV 3       NOV 4       2           5         4                                 1
China     NOV 1       NOV 4       2           5         4                                 1

MY RESULT:

COLLECTION OF REQUESTS WITH DIFFERENT START- AND END DATES

COUNTRY START DATE  END DATE    ALLOCATED   TOTAL    Max people used for this period    DIFF
China     NOV 1       NOV 2       2           5         4                                 1
China     NOV 3       NOV 4       2           5         4                                 1
China     NOV 1       NOV 4       2           5         6                                -1

(For NOV 1 to NOV 4 "Max people used..." sums ALLOCATED as 2+2+2 instead of 2+2...)

And here you can see how I got "MY RESULT"
SELECT DISTINCT Country.Country,
-- here comes the sum that doesn´t work...
SUM(Requests.[Amount of people per day needed]) AS [Max people used for this period]
FROM         Country INNER JOIN
                      Requests ON Country.CountryID = Requests.CountryID
WHERE     (Country.Country = 'China')
AND (Requests.[End date] >= @busyStartDate)
AND (Requests.[Start date] <= @busyEndDate)
GROUP BY Country.Country

"Max people used..." is the thing not working here - can I get that right, the rest will follow by business logic that you don´t see here :-)
UPDATE
Actually, I have given this up - didn´t get it to work in spite of good answers. Instead I did this (with the help of others, of course) to finally reach my goal ;-)

A: All-in-one multiple CTE solution (thanks Martin!)
with AllDates as (
  select  StartDate as [day] from Request
  union
  select  Enddate as [day] from Request),
TotalUsage as (
  select  [day], sum(allocated) as TotalAllocated
    from  AllDates
    join  Request
      on  [day] between StartDate and EndDate
    group by [day]),
MaxPerRequest as (
  select  CountryId, StartDate, EndDate, Allocated, MAX(TotalAllocated) as MaxAllocated
    from  Request
    join  TotalUsage
      on  [day] between StartDate and EndDate
    group by CountryId, StartDate, EndDate, Allocated
    )
select StartDate, EndDate, Allocated, MaxAllocated, Country.People - MaxAllocated as Diff
  from MaxPerRequest
  join Country on MaxPerRequest.CountryId = Country.CountryId

Old temp-table solution
Alas I don't think you can nest CTEs, so you'd need something like
with alldates as (
  select StartDate as [day] from request
  union
  select EndDate as [day] from request)
select [Day], sum(allocated) as TotalAllocated
into #TotalUsage
from alldates
join request on [Day] between StartDate and EndDate
group by [Day];

to build the total allocated per day for all interesting dates into a temporary table. (I can never remember which is the best temp table mechanism for SQL Server sorry - it may be better to go with a table variable, and may need to add indexes + keys either way.) You can then select max(TotalAllocated) from that for a given date range.
with MaxPerRequest as (
  select CountryID, StartDate, EndDate, Allocated, MAX(TotalAllocated) as MaxAllocated
    from request
    join #TotalUsage
      on [DAY] between StartDate and EndDate
    group by CountryID, StartDate, EndDate, Allocated
    )
select StartDate, EndDate, Allocated, MaxAllocated, Country.People - MaxAllocated as Diff
  from MaxPerRequest
  join Country on MaxPerRequest.CountryID = Country.CountryID

drop table #TotalUsage

Sorry I can't think of a simpler solution.

A: I think the search condition you require will look something like this:
SELECT *
  FROM MyTable AS T1
 WHERE CASE
          WHEN @start_date > T1.start_date THEN @start_date
          ELSE T1.start_date
       END
       <
       CASE
          WHEN @end_date > T1.end_date THEN T1.end_date
          ELSE @end_date
       END;

...but I would be making many assumptions about your data to come up with much more e.g. are you using the closed-open representation, are you using DATETIME values, etc?
Temporal database design is very difficult to get right and if your SQL DDL isn't correct then your SQL DML will be very tricky indeed. A good book on the subject is Developing Time-Oriented Database Applications in SQL by Rick Snodgrass, available as a free pdf download.


text:
Q: Is there any way to create WP archive page for a custom taxonomy? I have created custom taxonomy name "towers".
I'm trying to get to the "**www.example.com/towers/**" page (not the "www.example.com/towers/abc" page),
but I'm reaching 404, page not found error.
I've done some reading and realize that this is not ordinary on WP. meaning that WP don't understand what Tower am I trying to access, and that is why they need me to use the full URL above.
And yet, are any of you familiar with some solution?


text:
Q: How to compare dataframe columns using a given value? I have a dataframe that looks like this:
>>> df = pd.DataFrame( {'InLevel_03': [12, 12, 13, 12, 11,], 'InLevel_02': [11.5, 11.5, 12.5, 11.5, 10.5], 'InLevel_01': [11, 10.5, 12, 10.5, 9], 'OutLevel_01': [10.5, 10, 11.5, 10, 8.5], 'OutLevel_02': [10, 9.5, 11, 9.5, 8], 'OutLevel_03': [9.5, 9, 10, 9, 7.5]} )

>>> df
   InLevel_03  InLevel_02  InLevel_01  OutLevel_01  OutLevel_02  OutLevel_03
0          12        11.5        11.0         10.5         10.0          9.5
1          12        11.5        10.5         10.0          9.5          9.0
2          13        12.5        12.0         11.5         11.0         10.0
3          12        11.5        10.5         10.0          9.5          9.0
4          11        10.5         9.0          8.5          8.0          7.5

If the given value is 0.5, I want to check if there's a gap bigger than the given value in a row. For example, in the 2nd row, there's a gap between InLevel_02(11.5) and InLevel_01(10.5), which is 11. In the 5th row, the gaps are 10 and 9.5, between InLevel_02(10.5) and InLevel_01(9.0).
The result of this job would look like this:
 gapLevel    count    # row number, column name of each gap
       11        2    # (1, InLevel_02 - 1, InLevel_01), (3, InLevel_02 - 3, InLevel_01)
     10.5        1    # (2, OutLevel_02 - 2, OutLevel_03)
       10        1    # (4, InLevel_02 - 4, InLevel_01)
      9.5        1    # (4, InLevel_02 - 4, InLevel_01)

I tried converting the dataframe into an array(using .to_records) and comparing each value with its next value using loops, but the code gets too complicated when there are more than 1 level between two values and I'd like to know if there are more efficient ways to do this.

A: Here's one approach:
You can begin by obtaining a list of indices of rows and columns from which to extract the counts checking where the df minus a shifted version of itself (see pd.shift) is greater than 0.5:
t = 0.5
# df = df.astype(float) # if it isn't already
rows, cols = np.where(df - df.shift(-1, axis = 1) > t)
# (array([1, 2, 3, 4]), array([1, 4, 1, 1]))

Get the arange from the values in these rows and columns using a list comprehension as (note that this approach assumes that the values keep decreasing throughout the columns):
v = [np.arange(*df.iloc[r,[c+1, c]].values, step=t)[1:] for r, c in zip(rows, cols)]
# [array([11.]), array([10.5]), array([11.]), array([ 9.5, 10. ])]

Create a new Series from the counts using Counter:
from itertools import chain
from collections import Counter

x = list(chain.from_iterable(v.values))
#[11.0, 10.5, 11.0, 9.5, 10.0]
pd.Series(Counter(x), name = 'count')

11.0    2
10.5    1
9.5     1
10.0    1
Name: count, dtype: int64


text:
Q: Can I catch an inline error in an SQL subquery Is there any way I can check for an error in a sub-query just like we check for Null using IsNull?
For example, I need something like:
Select IsError((Select A From ABC Whete X=123), 0) ColA, ColB From MyTable
As shown, there could be a syntax error in the sub-query, a conversion error at run-time or even a missing parameter. The sub-query is injected at run-time and it's not possible to determine validity beforehand.
If the sub-query fails for any reason, I should get 0 returned in ColA.
Yes, I know that's dangerous, injecting a subquery. The sub-query is expected be correct in 99.9% of the cases. But I want to catch any error if all it happens.


text:
Q: Using useRef hook for scroll detection causing re-rendering I am using useRef hook in a layout component to detect the scroll value of it's children (pageContent). I am then conditionally displaying a button to scroll back to top.
Functionalities are working as excepted, but when I console.log something inside the pageComponent children (<route.component/>), it's shows me that the component is re-rendering each time the button shows / hide (scrollTop Value crosses 500)
Here is my Layout component :
function Layout() {
    const [showBackToTopButton, setShowBackToTopButton] = useState(false);
    const pageContentRef = useRef<HTMLDivElement>(null);

    function handleScroll() {
        const mainContent = pageContentRef.current;
        if (mainContent) {
            if (mainContent.scrollTop > 500) {
                setShowBackToTopButton(true);
            } else {
                setShowBackToTopButton(false);
            }
        }
    }

    function handleClickBackTop() {
        const mainContent = pageContentRef.current;
        if (mainContent) mainContent.scrollTo({ top: 0, behavior: 'smooth' });
    }

    useEffect(() => {
        const mainContent = pageContentRef.current;
        if (mainContent)
            mainContent.onscroll = function () {
                handleScroll();
            };
    }, []);

    return (
        <>

                <input
                    id='left-sidebar-drawer'
                    type='checkbox'
                    className='drawer-toggle'
                />
                <PageContent pageContentRef={pageContentRef} />
                <LeftSidebar />

            {showBackToTopButton && (
                <Button
                    className='back-to-top-button absolute right-0 bottom-10'
                    id='back-to-top'
                    onClick={handleClickBackTop}
                >

                </Button>
            )}
        </>
    );
}

export default Layout;

and here is the PageContent component :
interface PageContentProps {
    pageContentRef: React.RefObject<HTMLDivElement>;
}

function PageContent({ pageContentRef }: PageContentProps) {
    return (

                <Suspense fallback={<SuspenseContent />}>
                    <Routes>
                        {routes.map((route, key) => {
                            return (
                                <Route
                                    key={key}
                                    path={`${route.path}`}
                                    element={<route.component name={route.name} />}
                                />
                            );
                        })}

                        {/* Redirecting unknown url to 404 page */}
                        <Route path='*' element={<NotFound />} />
                    </Routes>
                </Suspense>

    );
}

export default PageContent;

Is it a normal behaviour considering the useState value ?
I tried using useMemo but I did not manage to solve my issue.
It's not a very big deal since the component are not rendering tenths of times, but it would be cleaner if they could render only once...

A: The reason is that when PageContent  component value change and Layout component rerender.
pageContent component wrap in memo() hook.
export default React.memo(PageContent);

and second,  wrap handleScroll function in useMemo hook that returns memorize function.
    useMemo(function handleScroll() {
        const mainContent = pageContentRef.current;
        if (mainContent) {
            if (mainContent.scrollTop > 500) {
                setShowBackToTopButton(true);
            } else {
                setShowBackToTopButton(false);
            }
        }
    }, [dependency]);

A: I found the solution wrapping my PageContent component inside a memo
const PageContent = React.memo(({ pageContentRef }: PageContentProps) => {
    return (
        // ...
    );
});

Children are now rendered only once.
Hope it can help ohter people


text:
Q: How to consider crf, -maxrate and -bufsize of a lossless video for whatsapp status I am using ffmpeg to encode my videos to upload them on Whatsapp status. This videos are <30 sec duration, and the output size should be in 10-14mb range.
Suppose I have a video of size 50 MB with a duration of 30 sec and I want it in size 10-14mb without losing quality.
How would I consider the value for these flags : -crf, -maxrate and -bufsize for this process?
Currently using this command line, it does the job of sizing but lose some quality.
ffmpeg -y -i "C:\Users\Input.mp4" -c:v libx264 -crf 17 -maxrate 3500k -bufsize 2000k -c:a copy "C:\Users\output.mp4"


text:
Q: PCB with AC voltages - May earth cross paths with hot/neutral on a different plane? I'm trying to build an AC "transfer" board that will feature:

*

*1x DPST switch (hot and neutral will be switched)

*1x power line filter

Although this is my first time designing a "high voltage" (120/220V) board, I think I could have done worse. The traces are 3mm thick, I set the clearances to 4.5mm, which is way too much according to my calculations, given that the PCB will be enclosed in a case and will live in a "normal" environment. The maximum power draw will be 400W (120V 3,3A, 220V 1,8A). The PCB that I am planning on using is your simple run of the mill 2 layer board, 1oz.
Here's how it looks:

I'm not too big a fan of that earth connection. The C14 receptacle is connected to the chassis, the chassis is connected to the board with one M4 screw.
Would you rather leave it as is or have the two planes cross each other?
Like so:


text:
Q: CDC debezium (postgres) is not publishing events for certain table I've set up a CDC pipeline in docker network using following scripts

*

*zookeper
--restart always \
-p 2181:2181 \
-p 2888:2888 \
-p 3888:3888 \
--network=test-net \
-v /var/ibank/msdata/test/zookeper/config/zoo.cfg:/zookeper/conf/zoo.cfg \
-v /var/ibank/msdata/test/zookeper/data/main-data:/zookeper/data \
-v /var/ibank/msdata/test/zookeper/data/txns:/zookeper/txns \
-v /var/ibank/msdata/test/zookeper/data/logs:/zookeper/logs \
debezium/zookeeper:1.6

*kafka
--name kafka \
--restart=always \
--network=test-net \
-p 9092:9092 \
-p 29092:29092 \
-e ADVERTISED_HOST_NAME=kafka \
-e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT \
-e ZOOKEEPER_CONNECT=zookeeper:2181 \
-e KAFKA_LISTENERS=PLAINTEXT_HOST://0.0.0.0:29092,PLAINTEXT://kafka:9092 \
-e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092 \
-v /var/ibank/msdata/test/kafka/data/kafka-data:/var/lib/kafka/data \
debezium/kafka:1.6

*connect

--restart=always \
--net=test-net \
-p 8083:8083 \
-e BOOTSTRAP_SERVERS=kafka:9092 \
-e GROUP_ID=afr-group-test \
-e CONFIG_STORAGE_TOPIC=afr_storage_topic \
-e OFFSET_STORAGE_TOPIC=afr_offset_topic \
debezium/connect:1.6

*added connector using the following config

{
    "name": "afr-connector",
    "config": {
      "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
      "database.hostname": "postgres",
      "database.port": "5432",
      "database.user": "test_user",
      "database.password": "test_user",
      "database.dbname": "ibank",
      "database.server.name": "ibankserver1",
      "table.include.list": "private.sessions, private.transactions, private.failed_auth_attempts",
      "plugin.name": "pgoutput",
      "publication.autocreate.mode": "filtered",
      "snapshot.mode": "never",
      "heartbeat.interval.ms": 1000,
      "heartbeat.action.query": "update debezium_heartbeat set last_heartbeat_ts = now();"
    }
  }

Postgres is in the same network, debezium connector successfully connects to the databse. PG user has all needed privileges (update, select, replication, login).
The problem is that I receive inerts (that's all I need) for transactions and failed_auth_attempts table but sessions table is not working.
What might be the problem?
here's a schema for the table
create table private.sessions
(
    id                        serial not null
        constraint sessions_pkey
            primary key,
    session_id                varchar(30),
    session_key               varchar(30),
    user_id                   integer
        constraint sessions_user_id_fkey
            references private.users,
    session_key_type          varchar(80),
    last_update_time          timestamp with time zone,
    ip_address                varchar,
    extradata                 jsonb,
    ip_address_location       varchar(30),
    auth_type                 varchar(30),
    user_agent_session_init   jsonb,
    last_used_ip_address      varchar(30),
    is_valid                  boolean,
    created_at                timestamp with time zone default now(),
    user_agent_session_actual jsonb,
    login_otp_sent_counter    integer                  default 0,
    otp_value                 varchar(8),
    restore_otp_sent_counter  integer                  default 0,
    firebase_token            varchar
);

alter table private.sessions
    owner to test_user;

grant select on private.sessions to test_user;

grant delete, insert, references, select, trigger, truncate, update on private.sessions to test_user;

A: turns out, debezium did not create publication only for "sessions" table for some unknown reason. Deleting the connector and recreating it did not help, then I manually deleted all publications that were created by debezium and recreated them for sessions table.


text:
Q: Неккоректная ширина на телефоне в веб браузере (JS) При загрузки окна js вычисляет ширину окна, после чего устанавливает ширину canvas в два раза больше.
На десктопе всё работает ровно так, как я и ожидал:
Однако на телефоне я получил неожиданный результат:

Возможно, это связано с какими-то ограничениям на ширину в мобильных веб браузерах, однако мне так и не удалось решить эту проблему. Попытки установить свойства max-width в body/canvas ни к чему не привели.

window.onload = () => {
  canvas = document.getElementById("myCanvas");
  ctx = canvas.getContext('2d');

  canvas.width = window.innerWidth * 2;
  canvas.height = window.innerHeight;

  console.log("Canvas width: " + canvas.width);
  console.log("Window width: " + window.innerWidth);
}
body {
  margin: 0;
}

canvas {
  overflow-x: visiable;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="style.css">
  <title>Игра</title>
</head>

<body id>
  <canvas id="myCanvas"></canvas>
</body>
<script src="script.js"></script>

</html>

A: Проблема решена.  Как я понял, в мобильной версии веб браузера js получает ширину окна ещё до того, как само окно было полностью загружено. Хотя это странно, ведь скрипт начинает работать только лишь после загрузки окна.   Так или иначе. Моё решение заключается в постоянном получении значений ширины (и высоты) окна в цикле рисования:

function draw() {
  canvas.width = window.innerWidth * 2;
  canvas.height = window.innerHeight;
  ...
}

...

setInterval(draw, 200);

Ну или через использование requestAnimationFrame, но это уже другая история.


text:
Q: Getting errors when adding a foreign and reference key in mysql I have two tables Plane and PlaneType.
 CREATE TABLE Plane
(
    ID INT,
    Maker VARCHAR(30),
    Model VARCHAR(30),
    LastMaint VARCHAR(30),
    LastMaintA VARCHAR(3),

    PRIMARY KEY (ID)
) ENGINE = INNODB;

CREATE TABLE PlaneType (
    Maker VARCHAR(30),
    Model VARCHAR(30),

    PRIMARY KEY (Maker, Model)
    ) ENGINE = INNODB;

After I insert these two tables I add the following foreign and primary keys:
ALTER TABLE Plane ADD FOREIGN KEY (Maker) REFERENCES PlaneType(Maker);
ALTER TABLE Plane ADD FOREIGN KEY (Model) REFERENCES PlaneType(Model);

The first ALTER works perfectly but the second gives me the error:
 ERROR 1005 (HY000): Can't create table '----.frm' (errno: 150)

I cannot figure out why the first ALTER works perfectly and the second doesn't. Both are references to primary keys, and that's the only issue I could think off. I'm a mysql noob so it might be something very obvious.
Any help is appreciated, thanks in advance.

A: Try this SHOW ENGINE INNODB STATUS and look for the LATEST FOREIGN KEY ERROR to get the specific error.
But I do believe it's a problem of indexes. Your primary key consists of Maker AND Model. Create an index on Model and the FK will be created.


text:
Q: How is NullReferenceException thrown in DetectChangesInProperty, deep within DbContext..Find? We occasionally see this exception in our logs, but can't figure out how to reproduce it under test:

System.NullReferenceException: Object reference not set to an instance of an object.
       at System.Data.Objects.EntityEntry.DetectChangesInProperty(Int32 ordinal, Boolean detectOnlyComplexProperties, Boolean detectOnly)
       at System.Data.Objects.EntityEntry.DetectChangesInProperties(Boolean detectOnlyComplexProperties)
       at System.Data.Objects.ObjectStateManager.DetectChangesInScalarAndComplexProperties(IList1 entries)
       at System.Data.Objects.ObjectStateManager.DetectChanges()
       at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force)
       at System.Data.Entity.Internal.Linq.InternalSet1.Find(Object[] keyValues)
       at

The failing method System.Data.Objects.EntityEntry.DetectChangesInProperty(Int32 ordinal, Boolean detectOnlyComplexProperties, Boolean detectOnly) decompiles with dotPeek (plus my comments) to:
private bool DetectChangesInProperty(
  int ordinal,
  bool detectOnlyComplexProperties,
  bool detectOnly)
{
  bool changeDetected = false;
  // possible System.NullReferenceException on _cacheTypeMetadata
  StateManagerMemberMetadata managerMemberMetadata = this._cacheTypeMetadata.Member(ordinal);
  // possible System.NullReferenceException on managerMemberMetadata (if a null entry exists in _members[])
  object obj1 = managerMemberMetadata.GetValue(this._wrappedEntity.Entity);
  if (managerMemberMetadata.IsComplex)
  {
    if (this.State != EntityState.Deleted)
    {
      object complexObjectSnapshot = this.GetComplexObjectSnapshot(this.Entity, ordinal);
      if (this.DetectChangesInComplexType(managerMemberMetadata, managerMemberMetadata, obj1, complexObjectSnapshot, ref changeDetected, detectOnly))
      {
        this.CheckForDuplicateComplexObjects(obj1);
        if (!detectOnly)
        {
          ((IEntityChangeTracker) this).EntityMemberChanging(managerMemberMetadata.CLayerName);
          // possible System.NullReferenceException on _cache
          this._cache.ChangingOldValue = complexObjectSnapshot;
          ((IEntityChangeTracker) this).EntityMemberChanged(managerMemberMetadata.CLayerName);
        }
        this.UpdateComplexObjectSnapshot(managerMemberMetadata, this.Entity, ordinal, obj1);
        if (!changeDetected)
          this.DetectChangesInComplexType(managerMemberMetadata, managerMemberMetadata, obj1, complexObjectSnapshot, ref changeDetected, detectOnly);
      }
    }
  }
  else if (!detectOnlyComplexProperties)
  {
    object obj2;
    // possible System.NullReferenceException on _wrappedEntity
    this.FindOriginalValue(managerMemberMetadata, this._wrappedEntity.Entity, out obj2);
    object originalValue = ((StateManagerValue) obj2).originalValue;
    // possible System.NullReferenceException on object
    if (!object.Equals(obj1, originalValue))
    {
      changeDetected = true;
      if (managerMemberMetadata.IsPartOfKey)
      {
        // static so no possible System.NullReferenceException
        if (!ByValueEqualityComparer.Default.Equals(obj1, originalValue))
          throw EntityUtil.CannotModifyKeyProperty(managerMemberMetadata.CLayerName);
      }
      else if (this.State != EntityState.Deleted && !detectOnly)
      {
        ((IEntityChangeTracker) this).EntityMemberChanging(managerMemberMetadata.CLayerName);
        ((IEntityChangeTracker) this).EntityMemberChanged(managerMemberMetadata.CLayerName);
      }
    }
  }
  return changeDetected;
}

There are several places where a NullReferenceException could be thrown, and I can't begin to guess.  If we knew how to reliably reproduce the problem I could step through, but I don't.  So far, this is all I have.
We have a large ASP.NET website solution with dozens of repositories which all use the same type of DbContext.  We haven't implemented instance-per-request yet, but we know we have to.  It'll take us several weeks to do it.  We think this is the cause of the exception.  In the meantime we have various approaches to newing up DbContext: per method call (expensive), now being replaced by (less expensive but also-smelly) service locators, with a bit of Autofac (still not instance per request because of that being incompatible with our version of MVC plus async).
We want to figure out how to reproduce this error reliably, so that we can know that instance-per-request has actually fixed the problem.  So the underlying question is not "how do we fix this", but "how do we reproduce it"?  And to answer that, I'm curious as to how this exception is actually happening.


text:
Q: solve expected ';' before '{' token my code is
#include<stdio.h>

struct car
{
    int id;
     char carname[50];
    float price;
};

struct car add();
void accept();
void display(struct car c[],int n);

void main()
{
    struct car c[20];
    int opt,n;
    do
    {
        printf("\nWelcome\nEnter your choice\n1.Accept\n2.Display\3.Search\n4.Delete\n5.Exit");
        scanf("%d",&opt);
        swtich(opt)
        {
            case 1://Accept
                   n=0;
                   c[n]=struct car add();
                   n++;
                   break;
            case 2://Display
                   display(struct car c[],n);
                   break;
        }
    }while(opt!=5);
}

struct car add()
{
    struct car c1;
    printf("\nEnter the id");
    scanf("%d",&c1.id);
    printf("\nEnter the carname");
    scanf("%s",&c1.carname);
    printf("\nEnter the price");
    scanf("%f",&c1.price);
    retrun(c1);
}

void display(struct car c[],int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        printf("\nCar id\tCar Name\tprice");
        printf("\n%d\t\t%s\t%d",c[n].id,c[n].carname,c[n].price);
    }
}

i cant get the code fixed by myself
i tried many thing neither of them worked for me...
please tell me what si wrong
my exams are tomorrow and i cant get a simple program fixed
i am screwed
help me
i use dev c++ on windows 8.1 operating sys 32 bit
i tried the same code on ubuntu same error
error is shown on the line 23
this { is present on it
and the error is expected ';' before'{' token
P.S tell me where i was going wrong...!!!

A: You have made a typo. swtich should be switch on line 22. I see a number of other compile error you'll find after that is solved. There is a similar typo around line 45. retrun needs to be return
Beyond that one error you'll have to deal with is calling functions and using return value.
For example:
c[n]=struct car add();

Should be:
c[n]=add();

You don't need to specify the type returned from a function like add() - the compiler already knows from the prototype  struct car add(); that add returns a struct car.
Similar thing here:
display(struct car c[],n);

should simply be:
display(c,n);

Again the compiler knows that display takes an array of car structures from the prototype void display(struct car c[],int n); so you just have to specify a car array variable - c in this case.
Once the OP starts to play with his program there is a bug on this line that will produce undesired output, but I will leave that as an exercise for them to figure out:
printf("\n%d\t\t%s\t%d",c[n].id,c[n].carname,c[n].price);


text:
Q: "&" being replaced by "& in php include I have a php page which get response from another page as shown:
while($response!=200)
{
$response = include 'xyz.php?one='.$one.'&two='.$two.'&three='.$three.'';
}

But my link always get's something like:
domainname.com/xyz.php?one=content&two=content&three=content

And due to & getting replaced by & I am getting the page not found issue.
I have tried using %26 and directly putting & instead of &, all in vain.
Is there any other simple solution besides using string replace function of PHP to remove & and replace it with &

A: Check out html_entity_decode
$response = html_entity_decode($response)

A: I ran a test based on the code you sent and I don't have a problem.  That suggests you have something auto-magical going on in your *.ini file (magic quotes, maybe... ugh...).  Try to create the string simply as a variable to remove it from the filename context and echo it out to be sure it's right, then use the variable with your include.
$one = 'abc';
$two = 'def';
$three = "ghi";
$file= 'xyz.php?one='.$one.'&two='.$two.'&three='.$three;
echo "\n\n".$file;
$response = include $file;

A: You can't use URL parameters when accessing a local file, they have to go through the webserver. Try:
$response = file_get_contents("http://localhost/path/to/xyz.php?one='.$one.'&two='.$two.'&three='.$three);


text:
Q: JavaScript return object I am digging into some JavaScript at the moment and I have a given function from which I want to return an object similar to HashMap. Here are the contents of the function:
function(video){
    var obj = {"title":video.title, "id":video.id};
    console.log(obj);
    return obj;
}

The problem is that the console.log prints the correct values, but the return does not return them. Here is an example output:
console.log:
{title: "Die Hard", id: 2}
{title: "Avatar", id: 3}

return:
{[Object]}
{[Object]}

A: I suspect you are alerting the results to the screen.
function video(){
  return {title: "Die Hard", id: 2}
}

a = video();

console.log(a); // Object {title: "Die Hard", id: 2}
alert(a); // [object Object]

You can read up on why that is, as well as possible solutions here: Print content of JavaScript object?
However, the bottom line is: just use console.log() to inspect objects (and anything else really).


text:
Q: Доступ к элементам DOM в функции javaScript Добрый день! Подскажите, где я не понимаю. Пишу функцию на событие (Нажатия кнопки). Функция должна выводить текст на страницу html. Однако ничего не происходит. Alertом все выводится.

function adding() {

  var name = document.getElementById('new');
  name.innerHTML = "fdkk;fdl";

  //
};
<!doctype html>

  <title>Forma</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="style_f.css">

    <form>

<input type="submit" value="Отправить" id="button" onclick="adding()">

    </form>

A: Текст вставляется. Просто у вас указан type="submit", и при нажатии на кнопку страница перезагружается. Вы просто не успеваете заметить результат.

function adding() {
  var name = document.getElementById('new');
  name.innerHTML = "fdkk;fdl";
};

    <form>

        <input type="button" value="Отправить" id="button" onclick="adding()">

    </form>

Или же использовать вот такой хак:

function adding(event) {
  var name = document.getElementById('new');
  name.innerHTML = "fdkk;fdl";
};

  <form>

      <input type="submit" value="Отправить" id="button" onclick="event.preventDefault(); adding();">

  </form>


text:
Q: How to setup topics/partitions count for EmbeddedKafka listener? I am creating integration test with embedded kafka. In the setup method I simply wait for partitions assignement:
    for (MessageListenerContainer messageListenerContainer : kafkaListenerEndpointRegistry
            .getListenerContainers()) {
        ContainerTestUtils.waitForAssignment(messageListenerContainer,
                embeddedKafka.getEmbeddedKafka().getPartitionsPerTopic());
    }

This works, when I have one partition (probably there is just one listener in that case). When I assign 3 partitions, it just randomly throws an exception, that waitForAssignement was awaiting 1 partition to be assigned, but there are two of them. So

*

*Listener1 - [partition1, partition2]

*Listener2 - [partition3]

If I set manually that it needs to wait for 2 partitions, of course it will hang on the other listener. Why all partitions are not within the same listener? Maybe I am using test utils incorrectly?

A: That's how Kafka works.
If you have two consumers in the same group, one will get 2 partitions and the other will get 1 partition.
If you put the listeners in different groups, they will both get 3.


text:
Q: Small signal diagram for a PMOS What is the small signal diagram for a PMOS? Would it be the same as that of an NMOS but instead of \$I = g_m V_{sg}\$, for a PMOS we have to use \$I = g_m V_{gs}\$?
Thanks.

A: The small signal diagram would be the same just with polarities reversed, so you can write it as \$I = g_mV_{sg}\$. As long as you aware of polarities though, either way could be used.
Here and here are reasonable documents with PMOS (and NMOS) small signal models and related equations (see first link, 8th page for diagram of both together)


text:
Q: TIMESTAMP vs. DATETIME for `created` and `updated` columns I'm using PHP/MySQL and I've always used DATETIME to store created and updated values, but I'm thinking there may be a better way.
Should I be using TIMESTAMP instead, and if so, why?

A: The documentation states:

TIMESTAMP values are converted from the current time zone to UTC for storage, and converted back from UTC to the current time zone for retrieval. (This occurs only for the TIMESTAMP data type, not for other types such as DATETIME.) By default, the current time zone for each connection is the server's time. The time zone can be set on a per-connection basis, as described in Section 9.6, "MySQL Server Time Zone Support". As long as the time zone setting remains constant, you get back the same value you store. If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored. This occurs because the same time zone was not used for conversion in both directions. The current time zone is available as the value of the time_zone system variable.

So you may want to use TIMESTAMP if you want your date/time stored in UTC instead of in the current time zone.

A: Timestamps are stored in UTC time in the database. Then, depending on your timezone setting, any time you fetch it it will automatically adjust the offset appropriately. If you are concerned with setting timezones for your application then definitely go with Timestamps.


text:
Q: mod_rewrite not allowing a-z So here is my question..
This is the url I have:
/category.php?cat=8
this is the url im trying to achieve:
/parties-events/kitchen/
Within the database the category has a  id, main, sub, main_slug and sub_slug
This: /main_slug/sub_slug/
I had this
RewriteRule ^([a-z]+)\/?$ $1.php [NC]
RewriteRule ^([a-z]+)\/([0-9]+)\/?$ category.php?param=$1&param2=$2 [NC]

Which outputs and works fine: /category/8/
BUT.. It only works with numbers, nothing else. I get a not found page if I use and letters.
But I'm lost as to the htaccess regex to just use the main and sub slugs and not only numbers.
Any help would be appreciated.

A: In this rule:
RewriteRule ^([a-z]+)\/([0-9]+)\/?$ category.php?param=$1&param2=$2 [NC]

The ([a-z]+) bit means "one or more letters between a and z"
The ([0-9]+) bit means "one or more numbers between 0 and 9"
It appears that what you are asking will be accomplished by replacing the [0-9] with another [a-z]. However, if you want to accept any character, and not just a-z and/or 0-9, replace both of them with just ([^/]+) which means "one or more not-slash characters".


text:
Q: taking input value as Enum Member in Angular First of all, I've achieved the required using regular string type, but I want to make my code strong-typed or well-controlled so to speak,
So, I have a function that takes an argument with type Enum
  createdAccountHandler(_accountName: string, _accountStatus:statusEnum) {
    this.createdAccount.emit({name: _accountName, status: _accountStatus});
  }

but the problem is that I'm taking this "_accountStatus" from HTML Select element as follows
       <select class="form-control" #accountStatus>
          <option *ngFor="let st of StatusList | slice:3:6" value="{{st}}">{{st}}</option>
        </select>
       <div
       class="btn btn-primary"
       (click)="createdAccountHandler(accountName.value, accountStatus.value)"
       >Add Account</div>

So, is there any way to transform the string returned from the Select element.value  as Enum,
especially since I'm already looping through my Enum to display only the allowed values as options?


text:
Q: DATE_ICAL and strtotime in PHP I have dates in my database in local British times (i.e. GMT in the winter and BST in the summer). I want to convert them to DATE_ICAL for displaying into iCalendar format. I have tried both the following.
date(DATE_ICAL, strtotime($row['FixtureDate']);
date(DATE_ICAL, strtotime($row['FixtureDate'].' UTC');

My first date for example is 12:45 BST. If I use the first statement I get 20140809T124500Z and the second I get 20140809T134500Z. Neither shows the right date in Google.
The second is obviously wrong because my time is not a UTC time, I think I need to convert my time to a UTC time as that's what DATE_ICAL wants? But how do I do that?
My server is British. I only care about British times and British users.

A: Finally figured it out, I needed to use GMDATE not DATE with ICAL format
define('DATE_ICAL', 'Ymd\THis\Z');
GMDATE(DATE_ICAL, strtotime($row['FixtureDate']));


text:
Q: How to use pig with cassandra? I know that cassandra has hadoop integration, but it seems to be for a combination cassandra/hadoop cluster using cassandra's own imitation.
But is there a loader that can be used with pig in a separate hadoop cluster that can load/store to/from a separate cassandra cluster? It seems this does not actually exist but want to confirm.

A: What exactly are you using PIG for ?
Moreover, I would suggest to have a look at Storm, it seems to be a viable alternative for your use case.


text:
Q: Status Unavailable in net use command using psexec We connected to remote computer using psexec. We are running .bat file which initiates scanstate.exe to scan computer files and settings to remote network location \\server\path1.
The scanstate error is:
"An error occurred processing the command line. Invalid store path; check the store parameter and/or file system permissions."

Scanstate is using remote disk location: \\server\path1
When we execute net use via psexec session:
    Status       Local     Remote                    Network

    -------------------------------------------------------------------------------
    Unavailable  F:        \\server\path1           Microsoft Windows Network
    Unavailable  G:        \\server\path2           Microsoft Windows Network

The command completed successfully.

When we run scanstate from desktop directly (not from psexec), the disks are available  and everything works.
When we try map drive via psexec session with domain admin user privileges:
C:\WINDOWS\system32>net use F: \\server\path1 /user:domain\user1 Password1
System error 1312 has occurred.

A specified logon session does not exist. It may already have been terminated.

How to access remote network drive via psexec?

A: https://portal.nutanix.com/page/documents/kbs/details?targetId=kA07V000000LUutSAG
This is due to the below group policy.  In order to pass the credentials to map the share this policy will need to be disabled.
Network access: Do not allow storage of passwords and credentials for authentication
Note: Mapping without credentials works with this policy enabled.

*

*Open the Local Group Policy Editor (gpedit.msc).

*Go to Computer Configuration > Windows Settings > Security Settings > Local Policies > Security Options, under group policy editor.

*Find the policy Network access: Do not allow storage of passwords and credentials for authentication, and set it to disabled or not configured.


text:
Q: Can`t save .pdf document which sended from .Net api I got an Api which return File, i write response into this.getPDFBuffer, here you can see it.
Main problem is that if I use my function it downloads an empty file, but if i use Postman to perform an request it saves correctly
//this.getPDFBuffer contains response.data:
      var file = new Blob([this.getPDFBuffer], {type: 'application/pdf'});
      var url = window.URL.createObjectURL(file);
      var link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download','download');
      link.click();

I expect download a file

A: This is not a full answer but:
On line 4 and line 5, I suggest using a link.href = url; instead of setAttribute(). For line 5, it is link.download = "download";. This could fix the problem, but this is not meant to be a fix, just a tip.
You also have to document.body.appendChild(link) probably after line 5 so it gets displayed in the HTML.
Also, on line 5, you might have to set different parameters(see https://www.w3schools.com/TAGS/att_a_download.asp).
Changed code:
var file      = new Blob([this.getPDFBuffer], {type: 'application/pdf'});
var url       = window.URL.createObjectURL(file);
var link      = document.createElement('a');
link.href     = url;
link.download = "download"; // Maybe 'link.download;'

document.body.appendChild(link)
link.click();


text:
Q: How can I hide specific Windows update? Two months ago Microsoft has released update (part of another question) which is causing problems to my software. I've found solution how to uninstall it, but after uninstallation, Windows installed it again.
I know the update mustn't be hidden without user permission - this is not a part of my question.
I'm looking for a way how to hide this update. I accept just any solution, but I prefer Batch or VB-script.

A: Read What is the "Get Windows 10" Tray Item and How Do You Remove It? and follow it mutatis mutandis:

*

*To uninstall an update (e.g. KB3035583):

*

*Manually: first open Windows Update and click "Installed Updates" in the bottom-left corner. To quickly find KB3035583, you can sort by name. Once you've located it, right-click and choose "Uninstall". Restart the computer then.

*Or programmatically  wusa /uninstall /KB:3035583 using Windows Update Standalone Installer

*If you have Windows updates set to download and install automatically, this means that if you uninstall this update, it will be reinstalled automatically a few days later. To hide the KB3035583 update and prevent it from being reinstalled, right-click on it in the Windows Update application and select "Hide update".

*

*To hide an update programmatically, see Opmet's answer to another question at SuperUser: How to disable the "Get Windows 10" icon shown in the notification area (tray)?


text:
Q: Entry point for java web application I need to know where i can start a cron in my java web app.  I need this cron to run daily and be rescheduled if the server restarts. Do java web application have hook where i can do this?
----edits----
Im using quartz to schedule a task which will pull down and parse a csv file and store it in a database. I need to know where i should schedule it to run the first time

A: You might want to use a ServletContextListener.  It supports two methods that run when an web app is started and ended. This article goes over setting one up.  You can start the Quartz scheduler in the Initialize method and shut it down in the Destroy method.


text:
Q: How to make dynamic div overflow without fixed height I'm trying to create a scrolling element without a fixed height parent. I want #SECTION1 of my code to be scrollable to show the rest of the images. I can't seem to find a way to do this. I've attempted to set #SECTION1 to a fixed height but it forces my images to be squashed. Any help would be appreciated. Thank you.
Here is my code:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  text-decoration: none;
}

 ::-webkit-scrollbar {
  width: 15px;
}

/* Track */

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* Handle */

::-webkit-scrollbar-thumb {
  background: #888;
}

/* Handle on hover */

::-webkit-scrollbar-thumb:hover {
  background: #555;
}

html,
body {
  margin: 0;
  padding: 0;
  height: 100vh;
  overflow: hidden;
}

/*----------SECTION 1----------*/

header {
  height: 80px;
  background-color: black;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

#header-wrapper {
  display: flex;
  width: 55%;
  justify-content: space-between;
  align-items: center;
}

#logo {
  width: 70px;
}

nav a {
  color: white;
  padding: 20px;
  font-family: 'Roboto';
  font-size: 0.8em;
  font-weight: bold;
}

@media only screen and (max-width: 750px) {
  nav {
    display: none;
  }
}

#mobile-menu {
  color: white;
  font-size: 1.3em;
}

@media only screen and (min-width: 750px) {
  #mobile-menu {
    display: none;
  }
}

#body-wrapper {
  display: flex;
  height: 100%;
}

aside {
  width: 300px;
  height: 889px;
  background-color: #0c0c0c;
  display: flex;
  align-items: center;
  padding-top: 50px;
  flex-direction: column;
}

#aside-wrap {
  width: 70%;
}

#user-info {
  display: flex;
  margin: 10px;
  margin-left: 0;
  margin-bottom: 50px;
  justify-content: center;
  align-items: center;
  font-family: 'Roboto';
  font-weight: 400;
}

#user {
  font-size: 40px;
  color: white;
  margin-right: 20px;
}

aside h3 {
  color: white;
  font-size: 1.2em;
}

#hello {
  color: white;
  font-size: 20px;
}

#box-1 {
  color: #808080;
  margin-bottom: 60px;
}

#box-1 p {
  margin: 20px;
  margin-left: 0;
  font-family: 'Roboto';
  font-size: 0.9em;
}

#box-2 {
  color: #808080;
}

#box-2 p {
  margin: 20px;
  margin-left: 0;
  font-family: 'Roboto';
  font-size: 0.9em;
}

#section1 {
  background-color: #191919;
  /*background: linear-gradient(rgba(0,0,0,0.3),rgba(0,0,0,0.3)),
url("listen_background.jpg");*/
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  width: 100%;
  overflow: auto;
}

#section1-wrapper {
  width: 80%;
  display: flex;
  font-family: 'Roboto';
  padding-top: 50px;
  padding-bottom: 50px;
  align-items: center;
  flex-direction: column;
}

#section1 h1 {
  color: white;
  font-size: 3em;
  margin-bottom: 50px;
  text-align: center;
}

.image-box {
  max-width: 280px;
  margin: 20px;
}

img {
  max-width: 100%;
}

#image-row-1,
#image-row-2,
#image-row-3,
#image-row-4 {
  width: 100%;
  margin-bottom: 50px;
  display: flex;
  justify-content: space-between;
}

@media only screen and (max-width: 1080px) {
  #image-row-1,
  #image-row-2,
  #image-row-3,
  #image-row-4 {
    flex-direction: column;
    align-items: center;
  }
}

/*----------------SECTION 2--------------*/

#pusher {
  height: 889px;
  width: 300px;
}

#player {
  height: 80px;
  width: 100%;
  position: fixed;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: black;
}

@media only screen and (max-width: 750px) {
  #player {
    height: auto;
  }
}

#player-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 80%;
}

@media only screen and (max-width: 750px) {
  #player-wrapper {
    flex-direction: column;
  }
}

.button-controls {
  color: white;
  margin: 20px;
}

#player-bar {
  width: 100%;
  height: 3px;
  background-color: white;
}

#player-filler {
  width: 50%;
  height: 100%;
  background-color: #2A4B5A;
}

#timeline {
  width: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

@media only screen and (max-width: 750px) {
  #timeline {
    width: 100%;
  }
}

#timeline p {
  color: white;
  margin: 20px;
}

#share,
#phone {
  color: white;
  margin: 20px;
}

@media only screen and (max-width: 750px) {
  #share,
  #phone {
    display: none;
  }
}

  <meta charset="utf-8">
  <title>Flo Music</title>
  <link rel="stylesheet" type="text/css" href="listen.css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">

Emmanuel

Your Library

Recently Played

Songs

Playlist

Your Library

Recently Played

Songs

Playlist

HOME

New Releases

0:00

0:00

A: Flex items are set to flex-shrink: 1 by default. This means they can shrink to prevent an overflow of the container. In your case, you may need to disable this feature (flex-shrink: 0).

Also, consider using height: 100vh, instead of height: 100% on your flex container. Percentage heights are tricky and often require the parent to have a defined height.
See this post for details: Working with the CSS height property and percentage values

Lastly, remove justify-content: center from your flex container. It makes content inaccessible via scroll in some cases.
See this post for details: Can't scroll to top of flex item that is overflowing container

Make these adjustments to your code:
#body-wrapper {
  display: flex;
  /* height: 100%; */
  height: calc(100vh - 80px); /* subtract footer height */
}

#section1 {
  background-color: #191919;
  display: flex;
  align-items: center;
  /* justify-content: center; */ /* remove to avoid scrolling problems */
  flex-direction: column;
  width: 100%;
  overflow: auto;
}

#section1-wrapper {
  width: 80%;
  display: flex;
  font-family: 'Roboto';
  padding-top: 50px;
  padding-bottom: 50px;
  align-items: center;
  flex-direction: column;
  flex-shrink: 0; /* add to disable flex default shrinking feature */
}

jsFiddle demo

A: You should change your overflow property in the #section1
#section1-wrapper {
overflow: scroll;
}


text:
Q: Ion-select multiple="true" does not function within ngFor I notice that when attempt to use ion-select within ngFor on a list that is set dynamically with a function, the lists did not get rendered to the DOM.
On the other hand, the DOM renders correctly if I take the individual element outside of the ngFor construct, OR if I do not use multiple="true".
Any suggestions on how to get around this?
Example:
1/ Fails to render:
<ion-item *ngFor="let t of getMyListOfFields()">
  <ion-label>{{t.FieldName}}</ion-label>
  <ion-datetime displayFormat="YYYY/MM/DD" [(ngModel)]="t.FieldValue" *ngIf="t.DataType == 'date'"></ion-datetime>
  <ion-input type="text" [(ngModel)]="t.FieldValue" *ngIf="!t.LookupID && t.DataType != 'date'"></ion-input>
  <ion-select multiple="true" [(ngModel)]="t.FieldValue" *ngIf="t.LookupID">
    <ion-option *ngFor="let l of t.Lookups" [value]="l.ID">{{l.Text}}</ion-option>
  </ion-select>
</ion-item>

2/ Renders correctly:
<ion-item>
  <ion-label>Test List</ion-label>
  <ion-select multiple="true" [(ngModel)]="model.TestItem.FieldValue"  *ngIf="model.TestItem && model.TestItem.LookupID">
          <ion-option *ngFor="let l of model.TestItem.Lookups" [value]="l.ID">{{l.Text}}</ion-option>
  </ion-select>
</ion-item>

A: Okay, for those interested, I find a workaround to the issue. If I replace the function call and provide a static list instead in the ngFor, there are no issues and the DOM renders, with the multi-select functioning correctly.
Curious why the function call would prevent it from rendering correctly. Is there a bug somewhere?


text:
Q: Python app crashes when emit signal from callback I use my c++ library from python application with QT. It uses callback to communicate with UI.
My library is 'ts'. The problem is that my program crashes sometimes.
As I understood it crashes when call to emit(), but it happens rarely.
The simplified version of my program looks like this:
import ts
...
class Parser(QObject):

    sig = Signal(ts.ProgramDescriptions)

    ts = ts.Ts()

    def init(self):
        self.ts.SetProgramChangeCB(SetProgramListCB)

    ...

class Ui_Dialog(QMainWindow):
    def __init__(self, pars):
        self.parser = pars
    ...

def SetProgramListCB(programDesc):
    print "SetProgramListCB"
    ui.parser.sig.emit(programDesc)

def SetProgramList(programDesc):
    print "SetProgramList"

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    Dialog = QDialog()

    parser = Parser()
    parser.init()
    parser.sig.connect(SetProgramList, Qt.QueuedConnection)

    parser.Start()

    ui = Ui_Dialog(parser)

    ...

Help!

A: After finding out that the cause of crash is C++ exception (with help of phihag), I changed my code in this way, and that fixed the problem:
def SetProgramListCB(programDesc):
    try:
        print ui.ravisParser.sig
        ui.ravisParser.sig.emit(programDesc)
    except:
        print "Error"

In case of proper work I have (output):
<PySide.QtCore.Signal object at 0x01DD88C0>
<PySide.QtCore.Signal object at 0x01DD88C0>
<PySide.QtCore.Signal object at 0x01DD88C0>
...

And in case of Error:
Error
<PySide.QtCore.Signal object at 0x01DD88C0>
<PySide.QtCore.Signal object at 0x01DD88C0>
<PySide.QtCore.Signal object at 0x01DD88C0>
...

So the reason why it crashed was that in first call to emit() signal 'sig' was not initialized.
I can't understand how it could happen, because callback is called from thread which starts when call to 'parser.Start()' which called after connect signal 'sig' :
parser.sig.connect(SetProgramList, Qt.QueuedConnection)

parser.Start()


text:
Q: How to pass results of results to another command in shell? Using the following combination of grep, ls and awk I get a list of pid that I need to kill:
grep -hP '^\d+$' `ls -lad /dir/*/pid | grep -P '/dir/\d+/pid' | awk '{ print $9 }'`

13234
18972
24322

How can I now add kill -9 command to this command combination to kill those processes?
I already using ` characters to pass awk results to grep command, so I assume I cannot use it again to pass it to kill, correct?


text:
Q: Kalman filter and Box-Cox I'm interested in wind forecasting, which I have analyzed over some time by means of ARMA methods. Now I've being reading about Kalman filtering. Kalman filter is optimal when Gaussian assumption can be hold. However, wind distributions are far from normal (with Weibull the most popular). My question is, Is it correct to transform a wind speed time series by means of Box-Cox transformation before estimating the parameters of Kalman filter, so that the normality assumption holds? If it were so, why then using particle filters?

A: Box-Cox transformation is most often used to address non-constant variance. It doesn't convert non-Gaussian noise to Gaussian generally.
Kalman filter's a very convenient and fast method of estimation of state-space models (SSM) when the errors are Gaussian, and the models are linear. There are other ways of estimating SSM though. If you wish to venture beyond ARMA, then I would suggest reading about SSM in general, not just Kalman filters. The good book on SMM is Shumway and Stoffer, it has its own R package with code and examples. The non-gaussian estimation is in section 6.10 of 2nd edition. I didn't read the 3rd edition yet.
They have a follow up book on nonlinear modeling.


text:
Q: Custom webpack config not doing it's job I'm currently trying to use a customWebpackConfig that removes all the data-cy attributes from all HTML files prior to building the application for production.
I used a tutorial I found online that really explains it all very well but sadly the data-cy attributes are still there after production build.
"architect": {
            "build": {
                "builder": "@angular-builders/custom-webpack:browser",
                "options": {
                    "customWebpackConfig": {
                        "path": "./webpack.extra.js",
                        "mergeStrategies": {
                            "externals": "append"
                        }
                    },

I'm using webpack.extra.js that should find all files ending with .html and use data-cy-loader.js for the rest
module.exports = {
module: {
    rules: [{
        test: /\.html$/,
        use: ['data-cy-loader']
    }]
},
resolveLoader: {
    alias: {
        'data-cy-loader': path.join(__dirname, 'data-cy-loader.js')
    }
}

data-cy-loader should then match data-cy attributes and replace them with ''
module.exports = function dataCyLoader(source) {
const dataAttr = 'data-cy=\"([^"]*)\"';
if(source.match(dataAttr)){
    source = source.replace(new RegExp(dataAttr, 'g'), ' ');
}
return source;

I hope anyone could point me in the right direction.


text:
Q: WCF client with ssl and username/password authentication I am trying to connect to service which is accesssible over https and need authentication.
The error I get is:

Test method
  TestProject1.UnitTest1.TestReharB2B
  threw exception:
  System.ServiceModel.Security.MessageSecurityException:
  The HTTP request is unauthorized with
  client authentication scheme
  'Anonymous'. The authentication header
  received from the server was 'Basic
  realm="Application"'. --->
  System.Net.WebException: The remote
  server returned an error: (401)
  Unauthorized..

It seems to me like that username and password is not sent to service. What am I missing?
The code:
EndpointAddress address = new EndpointAddress(
                    new Uri("https://84.52.158.151:8443/JavaStore/services/B2BService"),
                        EndpointIdentity.CreateDnsIdentity("JavaStore"),
                        new AddressHeaderCollection()
                );

BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

var client = new ReharB2BService.B2BServicePortTypeClient(binding, address);

client.ChannelFactory.Credentials.UserName.UserName = "dotNet";
client.ChannelFactory.Credentials.UserName.Password = "dotnetpwd";

client.Open();
client.getAllItems();

A: Your service returns error because there is some misconfiguration between server and client. Your client uses transport security with UserName message credentials. That means that HTTPS is used and message contains SOAP header with user name and password. But your service returns exception because it (probably IIS) expects transport security with Basic credentials. That means HTTPS and HTTP Basic authentication (HTTP header).


text:
Q: Event is not defined error in javascript only Firefox I use the following script to validate the text box to enter only numbers and (.) which means it is decimal textbox validation. It was work fine in Internet Explorer and Google Chrome. If I execute the function in FireFox I get the following Error:

Event Is not Defined.

How to solve this?
function abc(event) {

        if (event.keyCode > 47 && event.keyCode < 58) {
            return true;
        }
        if (event.keyCode == 8 || event.keyCode == 46)
        {
            return true;
        }
        return false;
    }

I call this function like this:
$('.decimalValidate').live('keypress',function(){
          var decimalid=$(this).attr("id");
          var decimalval=$('#'+decimalid).val();
          var decimalvalidate=abc(decimalval);
          if(decimalvalidate == false)
          return false;
     });

I assign this validation for text box like this:
input type="text" id="Total" class="abc"

A:    $('.decimalValidate').live('keypress',function(e){
                              var decimalvalidate=abc(e); //this will point to the event of the keypress.
                              if(decimalvalidate == false)
                              return false;
                         });

I am not sure why you did all of the decimalid and decimalval operations, but if you want the event, do as I wrote in the edited code above.
Good luck.

A: decimalval is not an Event object, and you have to pass it to the abc function in ordert to find out which key you pressed:
$('.decimalValidate').live('keypress',function(ev){
                          var decimalid=$(this).attr("id");
                          var decimalval=$('#'+decimalid).val();
                          var decimalvalidate=abc(ev);
                          if(decimalvalidate == false)
                          return false;
                     });

A: Try this
function abc(event) {
        if(!event)
           event= window.event;

        if (event.keyCode > 47 && event.keyCode < 58) {
            return true;
        }
        if (event.keyCode == 8 || event.keyCode == 46)
        {
            return true;
        }
        return false;
    }

and
$('.decimalValidate').live('keypress',function(e){
                              var decimalid=$(this).attr("id");
                              var decimalval=$('#'+decimalid).val();
                              var decimalvalidate=abc(evt); //keypress event
                              if(decimalvalidate == false)
                              return false;
                         });

A: $('.decimalValidate').on('keypress',function(event){
     var decimalid       =  $(this).attr("id");
     var decimalval      =  $('#'+decimalid).val();
     var decimalvalidate =  abc(event);

     if(decimalvalidate == false)
        return false;
});

function abc(event) {

        if (event.keyCode > 47 && event.keyCode < 58) {
            return true;
        }
        if (event.keyCode == 8 || event.keyCode == 46)
        {
            return true;
        }
        return false;
}

It helps you..


text:
Q: Uploading manifest with supportsCalling and supportsVideo fails with BadRequest I'm following these instructions to create a Teams calling bot:
https://learn.microsoft.com/en-us/microsoftteams/platform/bots/calls-and-meetings/registering-calling-bot
In my manifest.json, I have set supportsCalling and supportsVideo to true like this:
  "bots": [
    {
      "botId": "fa6ec2a6-XXXX",
      "scopes": [
        "personal",
        "groupchat",
        "team"
      ],
      "supportsFiles": false,
      "isNotificationOnly": false,
      "supportsCalling": true,
      "supportsVideo": true
    }
  ],

When I use "upload custom app" in Teams, I get an error saying "Manifest parsing has failed".
When I use "copy error details to clipboard", all I get is this:
Bad Request
If I remove supportsCalling and supportsVideo from the manifest, I am able to upload it with no errors.
I have followed the instructions to enable calling on the Teams channel and added all the Microsoft Graph permissions, but it still does not work.

A: Setting manifestVersion to devPreview fixed the problem.


text:
Q: What is a reporting server? What is the need of a reporting server?
What do I miss out by not using a reporting server and instead using a reporting library?
Reporting libraries like Jasper can easily generate a report and can be embedded anywhere, be that Servlet or a desktop application. Why then would one need a reporting server?

A: The most useful feature of a reporting server would be the ability to generate scheduled reports, the second most useful is the ability to view reports on the web, aside from that, you don't miss too much if you don't use it.

A: A reporting server usually generates reports offline or cached on demand.  This means that report you need are more likely to be pregenerated and accessible immediately rather than waiting for the report to generate.  It can also be used to generate reports which are emailed periodically.


text:
Q: changing form behavior on submit based on radio button selection I'm using Rails 3.1.0.rc5. I want to have a form with a pair of radio buttons, enable and disable, and a field to enter an integer (expire_after_days, the number of days until ticket expiration), with a hidden field for the fixed parameter subdomain_name. I'd like to be able to use the same simple form to create, edit, or delete a record, depending on which radio button is checked.
So if enable is checked, with no record found for the subdomain_name, a record would be created on form submission.
If enable is checked, and a record is found, the existing record should be updated on form submission.
And if disable is checked, the record should be deleted on form submission.
Is this a reasonable thing to do? If so, what tips do you have for how to do it?

A: It's not ideal nor restful to have all 3 actions (create, update, destroy) cramped up in just one controller method, but if you wish to continue on this dirty route here's what you could do:
def my_dirty_method
  if params[:enable].present?
    if params[:subdomain_name].present?
      # Edit subdomain
    else
      # Create subdomain
    end
  end
  if params[:disable].present?
    # Delete subdomain
  end


text:
Q: How to add data on Top position like first in first out in For and while Loop? Reverse loop maybe? I want these loops to add data on Top every time not in bottom.I did not find any solution how I can run these loop in reverse order
for($i=0;$i<count($data);$i++){
    if($i==0) {
            $html.="

            ".$data[$i][0]."
            ".$data[$i][1]."
            ".$data[$i][2]."
            ".$data[$i][3]."
";}
     else{
             $sc_=explode("-",$data[$i][3]);
            if(count($sc_)!=2){
            $html.="
".$data[$i][0]."
            ".$data[$i][1]."
            ".$data[$i][2]."
            ".$data[$i][3]."
";
            }else{
            if($sc_[0]>$sc_[1]){
                $html.="
".$data[$i][0]."
                ".$data[$i][1]."
                ".$data[$i][2]."
                ".$data[$i][3]."
";
                }
            else if($sc_[0]<$sc_[1]){
                $html.="
".$data[$i][0]."
                ".$data[$i][1]."
                ".$data[$i][2]."
                ".$data[$i][3]."
";
            }else{
                $html.="
".$data[$i][0]."
                ".$data[$i][1]."
                ".$data[$i][2]."
                ".$data[$i][3]."
";
            }
        }
    }

}

And This is the second loop in my Code
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
          $data[] = $row;
        }

I want to add data on top in every iteration like new values on line 1 every time.

A: Replace your for loop as:
for($i = count($data) - 1; $i >= 0; $i--) {
    if($i == count($data) - 1) {
         // show table head

In this case you will take items from the end of $data array as $i will be decreasing.


text:
Q: Children Fixed positioned element not aligned to Parent Relative positioned element I have a div which is positioned as relative and whose height is 38px inside this I have another div whose position is set as absolute and the top property is 38px and the left property is 0. But I can see that from the left its not aligned to the parent element rather it looks as I have set the left property to 1px which results in a kind of left 1px margin from the parent element.
So whats really happening?

A: I guess that's due to the fact that you cannot place child element upon the border of the parent element. so for example if your parent has border-width:5px then:

see? your child div starts exactly after 5px(the width of the border of your parent div), and since it is inside the parent div, it cannot just stand upon the border(sorry for the bad english)it doesnt matters whether you position your element in such a way that it appears outside the parent div, it is still gonna follow the parent-child positioning rule.
Solution:
you can either set:
left:-1px;

or
margin-left:-1px;

on your child element. Looks hacky but thats all we can do.hope it helps
Demo : http://jsfiddle.net/s4v89/1/


text:
Q: Build Custom JDK, delete useless libs How can I delete useless libraries from my JDK and it's possible?

A: Yes, this is possible and documented by Oracle.
For our project we use the following "cleanup script". Yours may be different, see comments (for instance: we do not use JavaFX).
#!/bin/sh
# Remove all not-needed files, see http://www.oracle.com/technetwork/java/javase/jre-8-readme-2095710.html
# Documentation
rm -f jre/README.txt
rm -f jre/THIRDPARTYLICENSEREADME.txt
rm -f jre/THIRDPARTYLICENSEREADME-JAVAFX.txt
rm -f jre/Welcome.html
# optional files
rm -f jre/lib/ext/jfxrt.jar
rm -f jre/lib/ext/access-bridge.jar
rm -f jre/lib/ext/access-bridge-32.jar
rm -f jre/lib/ext/nashorn.jar
rm -f jre/bin/rmid.*
rm -f jre/bin/rmiregistry.*
rm -f jre/bin/tnameserv.*
rm -f jre/bin/keytool.*
rm -f jre/bin/kinit.*
rm -f jre/bin/klist.*
rm -f jre/bin/ktab.*
rm -f jre/bin/policytool.*
rm -f jre/bin/orbd.*
rm -f jre/bin/servertool.*
rm -f jre/bin/javaws.*
rm -f jre/lib/jfr.*
# can be deleted when private application runtime is used (like launch4j)
rm -f jre/bin/java.exe
# launch4j uses javaw.exe. So do NOT delete!
rm -f jre/bin/javacpl.exe
rm -f jre/bin/jabswitch.exe
rm -f jre/bin/java_crw_demo.dll
rm -f jre/bin/JavaAccessBridge-32.dll
rm -f jre/bin/JavaAccessBridge.dll
rm -f jre/bin/JAWTAccessBridge-32.dll
rm -f jre/bin/JAWTAccessBridge.dll
rm -f jre/bin/WindowsAccessBridge-32.dll
rm -f jre/bin/WindowsAccessBridge.dll
rm -f jre/bin/wsdetect.dll
rm -f jre/bin/deploy.dll
rm -f jre/bin/javacpl.cpl
rm -f jre/lib/deploy.jar
rm -f jre/lib/plugin.jar
rm -Rf /s /q jre/bin/dtplugin
rm -Rf /s /q jre/bin/plugin2
rm -Rf /s /q jre/lib/deploy
# JavaFX related
rm -f jre/lib/javafx.properties
rm -f jre/lib/jfxswt.jar
rm -f jre/bin/decora_sse.dll
rm -f jre/bin/fxplugins.dll
rm -f jre/bin/glass.dll
rm -f jre/bin/glib-lite.dll
rm -f jre/bin/gstreamer-lite.dll
rm -f jre/bin/javafx_font.dll

Windows version:
:: Remove all not-needed files, see http://www.oracle.com/technetwork/java/javase/jre-8-readme-2095710.html
:: Documentation
del jre\README.txt
del jre\THIRDPARTYLICENSEREADME.txt
del jre\THIRDPARTYLICENSEREADME-JAVAFX.txt
del jre\Welcome.html
:: optional files
del jre\lib\ext\jfxrt.jar
del jre\lib\ext\access-bridge.jar
del jre\lib\ext\access-bridge-32.jar
del jre\lib\ext\nashorn.jar
del jre\bin\rmid.*
del jre\bin\rmiregistry.*
del jre\bin\tnameserv.*
del jre\bin\keytool.*
del jre\bin\kinit.*
del jre\bin\klist.*
del jre\bin\ktab.*
del jre\bin\policytool.*
del jre\bin\orbd.*
del jre\bin\servertool.*
del jre\bin\javaws.*
del jre\lib\jfr.*
:: can be deleted when private application runtime is used (like launch4j)
del jre\bin\java.exe
:: launch4j uses javaw.exe. So do NOT delete!
del jre\bin\javacpl.exe
del jre\bin\jabswitch.exe
del jre\bin\java_crw_demo.dll
del jre\bin\JavaAccessBridge-32.dll
del jre\bin\JavaAccessBridge.dll
del jre\bin\JAWTAccessBridge-32.dll
del jre\bin\JAWTAccessBridge.dll
del jre\bin\WindowsAccessBridge-32.dll
del jre\bin\WindowsAccessBridge.dll
del jre\bin\wsdetect.dll
del jre\bin\deploy.dll
del jre\bin\javacpl.cpl
del jre\lib\deploy.jar
del jre\lib\plugin.jar
rmdir /s /q jre\bin\dtplugin
rmdir /s /q jre\bin\plugin2
rmdir /s /q jre\lib\deploy
:: JavaFX related
del jre\lib\javafx.properties

A: delete more jfx stuff:
del jre\lib\jfx*.*
del jre\bin\jfx*.*


text:
Q: PDF External Signature
Client=My application,
Server=MSSP(Mobile Signature Services Provider)
Server is sign only the hash values.
Data to be sign:
*Base64 encoded SHA-1 digest of data to be signed. (28 characters)
*Base64 encoded SHA-256 digest of data to be signed. (44 characters)
*Base64 encoded SHA-384 digest of data to be signed. (64 characters)
*Base64 encoded SHA-512 digest of data to be signed. (88 characters)
*Base64 encoded DER encoded PKCS#1 DigestInfo to sign.
I want to external signature for pdf. I wrote the below code. But I get an error when opened the document with adobe.
Error:
modified or corrupted after the document is signed
Note: I use MSSP(Mobile Signature Service Provider) architecture. DataToBeSigned.length should be 44 for SHA256 algorithm.
My operation code:
  import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfDate;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignature;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfString;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.PdfPKCS7;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.HashMap;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 *
 * @author murat.demir
 */
public class PdfSignOperation {

    private byte[] content = null;
    private X509Certificate x509Certificate;
    private PdfReader reader = null;
    private ByteArrayOutputStream baos = null;
    private PdfStamper stamper = null;
    private PdfSignatureAppearance sap = null;
    private PdfSignature dic = null;
    private HashMap<PdfName, Integer> exc = null;
    private ExternalDigest externalDigest = null;
    private PdfPKCS7 sgn = null;
    private InputStream data = null;
    private byte hash[] = null;
    private Calendar cal = null;
    private byte[] sh = null;
    private byte[] encodedSig = null;
    private byte[] paddedSig = null;
    private PdfDictionary dic2 = null;
    private X509Certificate[] chain = null;

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public PdfSignOperation(byte[] content, X509Certificate cert) {
        this.content = content;
        this.x509Certificate = cert;
    }

    public byte[] getHash() throws Exception {
        reader = new PdfReader(new ByteArrayInputStream(content));

        baos = new ByteArrayOutputStream();
        stamper = PdfStamper.createSignature(reader, baos, '\0');
        sap = stamper.getSignatureAppearance();

        sap.setReason("Test");
        sap.setLocation("On a server!");
        sap.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
        sap.setCertificate(x509Certificate);

        dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setContact(sap.getContact());
        dic.setDate(new PdfDate(sap.getSignDate()));
        sap.setCryptoDictionary(dic);

        exc = new HashMap<PdfName, Integer>();
        exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
        sap.preClose(exc);

        externalDigest = new ExternalDigest() {
            @Override
            public MessageDigest getMessageDigest(String hashAlgorithm)
                    throws GeneralSecurityException {
                return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
            }
        };

        chain = new X509Certificate[1];
        chain[0] = x509Certificate;

        sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
        data = sap.getRangeStream();
        cal = Calendar.getInstance();
        hash = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
        sh = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
        sh = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256"));
        return sh;
    }

    public String complateToSignature(byte[] signedHash) throws Exception {
        sgn.setExternalDigest(signedHash, null, "RSA");
        encodedSig = sgn.getEncodedPKCS7(hash, cal, null, null, null, CryptoStandard.CMS);
        paddedSig = new byte[8192];

        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
        dic2 = new PdfDictionary();

        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
        sap.close(dic2);

        return Base64.encodeBytes(baos.toByteArray());
    }

}

My test code :
  public static void main(String[] args) throws Exception {
    TokenService.refreshAllTokens();
    String alias = "alias";
    String pin = "1234";
    TokenService.setAliasPin(alias, pin);

    File pdf = new File("E:/sample.pdf");
    FileInputStream is = new FileInputStream(pdf);
    byte[] content = new byte[is.available()];
    is.read(content);

    X509Certificate certificate = null;
    for (CertInfo certInfo : TokenService.getCertificates().values()) {
        if (certInfo.cert != null) {
            certificate = certInfo.cert;
        }
    }

    PdfSignOperation operation = new PdfSignOperation(content, certificate);

    byte[] hash = operation.getHash();

    //simule control for mobile signature.
    String encodeData = Base64.encodeBytes(hash);
    if (encodeData.length() != 44) {
        throw new Exception("Sign to data must be 44 characters");
    }

    // This function is local in the test run function (Simulated MSSP mobile signature)
    // return  a signed message digest
    byte[] signedData = TokenService.sign(encodeData, alias);

    //Combine signed hash value with pdf.
    System.out.println(operation.complateToSignature(signedData));
}

SignedPDF
Update:
I tried with the old library version and successful signature operation. My new code:
InputStream data = sap.getRangeStream();

X509Certificate[] chain = new X509Certificate[1];
chain[0] = userCert;

PdfPKCS7 sgn = new PdfPKCS7(null, chain, null, algorithm, null, false);

MessageDigest digest = MessageDigest.getInstance("SHA256", "BC");
byte[] buf = new byte[8192];
int n;
while ((n = data.read(buf, 0, buf.length)) > 0) {
    digest.update(buf, 0, n);
}
byte hash[] = digest.digest();
logger.info("PDF hash  created");
Calendar cal = Calendar.getInstance();

byte[] ocsp = null;
byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
sh = MessageDigest.getInstance("SHA256", "BC").digest(sh);

final String encode = Utils.base64Encode(sh);
SignatureService service = new SignatureService();

logger.info("PDF hash  sended to sign for web service");
MobileSignResponse signResponse = service.mobileSign(mobilePhone, signText, encode, timeout, algorithm, username, password, "profile2#sha256", signWsdl);

if (!signResponse.getStatusCode().equals("0")) {
    throw new Exception("Signing fails.\n" + signResponse.getStatusMessage());
}

byte[] signedHashValue = Utils.base64Decode(signResponse.getSignature());
sgn.setExternalDigest(signedHashValue, null, "RSA");

byte[] paddedSig = new byte[csize];

byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, null, ocsp);
System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
if (csize + 2 < encodedSig.length) {
    throw new Exception("Not enough space for signature");
}

PdfDictionary dic2 = new PdfDictionary();
dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
sap.close(dic2);
logger.info("Signing successful");

A: In getHash you build the signed PDF (only the actual signature area is filled with '00' instead of signature bytes), calculate the hash of the byte range and return this hash.
In your main you sign this returned hash as is.
In complateToSignature you then insert this into the prepared PdfPKCS7 structure.
This is not correct, though: The hash which is signed in a PKCS7 / CMS signature is not the hash of the document (unless you have the most primitive form of a PKCS7 container) but the hash of the signed attributes (the hash of the document is but the value of only one of these attributes), also known as authenticated attributes.
Thus, you have to generate the signed attributes using the document hash you calculated, and then (hash and) sign this structure.
Have a look at iText's MakeSignature.signDetached and work it out in parallel:
String hashAlgorithm = externalSignature.getHashAlgorithm();
PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, null, externalDigest, false);
InputStream data = sap.getRangeStream();
byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm));
Calendar cal = Calendar.getInstance();
byte[] ocsp = null;
if (chain.length >= 2 && ocspClient != null) {
    ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null);
}
byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp, crlBytes, sigtype);
byte[] extSignature = externalSignature.sign(sh);
sgn.setExternalDigest(extSignature, null, externalSignature.getEncryptionAlgorithm());

PS: When trying to transfer that code to your use case, please be aware of a major difference between the ExternalSignature method sign used here and your TokenService method sign:
ExternalSignature.sign is documented as:
/**
 * Signs it using the encryption algorithm in combination with
 * the digest algorithm.
 * @param message   the message you want to be hashed and signed
 * @return  a signed message digest
 * @throws GeneralSecurityException
 */
public byte[] sign(byte[] message) throws GeneralSecurityException;

So this method does both hash and sign.
In case of your method TokenService.sign, though, if you

use the sha256 algorithm, sign to data must be 44 characters

so the data you forward to that method seems to have to be already hashed (44 characters are needed for a base64 encoded SHA-256 hash value).
Thus, you have to calculate the hash of sh and forward this hash to TokenService.sign instead of the original signed attributes.