text:
Q: in QLIK, how do I add data from table B to table A based on conditions in table A still not completely understanding how to do certain things in qlik.

*

*I have a table payments, which includes a payment status, and a reference_key

*I have a table payment references which has a reference_key and a
reference_number.

payments has like 100 fields in it.
I just want to end up with a field in payments which has the reference number if the status is paid, and is blank if it's not - and I'm finding it oddly hard to do.
in sql it would just be
   select
        payments.*,
        case when status='paid' then reference_number else '' end as reference_number
   from
       payments
       inner join references on payments.reference_key = references.reference_key

but I'm having a real trouble doing this in qlik - what I tried to do is
    left join (payments)
    load reference_key, reference_number from [references.qvd](qvd)
    where status = 'paid';

but that just gives me field "status" is not found - because of course the status isn't in references.
The only thing I can come up with that works is create rename payments to payments_temp, join to references - create another payments_temp_2 table with a calculated field with if() in that one - then create a new payments table from payments_temp_2 which drops the reference_number column and renames calculated_reference_number to reference_number - which ends up about ~350 lines of code.
clearly I'm doing something wrong - but how do I do it - it seems such a simple thing - and such a common problem?
Note - any number of lines of payments, with all difference statuses - could all be joining to the same reference number

A: Probably not code length efficient as sql code but the principle is the same. What you can do, in advance, is to prepare the new reference_number field (based on the status) in separate table (without loading the full table). Then join to the main table, drop the orignal reference_number and rename the new field to reference_number
// Join both references and payments tables but load only the required fields
// reference_key, reference_number and status
TempTable:
Load
  Distinct
  reference_key,
  reference_number
from
 references.qvd (qvd);

inner join (TempTable)

Load
  Distinct
  status,
  reference_key
from
 payments.qvd (qvd)
;

// perform the "if" statement calculation
ReferenceNumberStatus:
Load
  reference_number,
  reference_key,
  if(status = 'paid', reference_number, '') as reference_number_status
Resident
  TempTable
;

// we dont need this table anymore
Drop Table TempTable;

// load full payments table
// and join the table with the status calculation
Payments:
Load
  *
from
 payments.qvd (qvd)
;

join (Payments)

Load
  reference_number,
  reference_number_status
Resident
  ReferenceNumberStatus
;

// we dont need this table anymore
Drop Table ReferenceNumberStatus;

// drop the original reference_number
Drop Field reference_number from Payments;
// rename the new reference_number_status field to reference_number
Rename Field reference_number_status to reference_number;


text:
Q: PKCS11 token, receiving error CKR_ATTRIBUTE_TYPE_INVALID when executing keystore.getKey() I use java 1.8 and the following code works for many USB pkcs11 devices but this week I found a new model of a token that when I execute "keystorePkcs11.getKey(alias, pass);" I receive the error CKR_ATTRIBUTE_TYPE_INVALID. This token has a single certificate
This is the full code source I used to do the test:
package pkcs11test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.KeyManagerFactory;
import sun.security.pkcs11.SunPKCS11;
import sun.security.pkcs11.wrapper.CK_TOKEN_INFO;
import sun.security.pkcs11.wrapper.PKCS11;
import sun.security.pkcs11.wrapper.PKCS11Exception;

public class PKCS11Test {
    public static void main(String[] args) {
        try {
            char[] pass = "******".toCharArray(); // PIN of the token
            String dllFile = "D:\\temp\\cryptoide_pkcs11.dll"; // DLL file used to acces the token
            String configFile = "config.cfg"; // config file
            PKCS11 p11 = PKCS11.getInstance(dllFile, "C_GetFunctionList", null, false);
            long[] slots = p11.C_GetSlotList(true);
            for (int j = 0; j < slots.length; j++) {
                CK_TOKEN_INFO tokenInfo = p11.C_GetTokenInfo(slots[j]);
                System.err.println("Token found at position "+j+
                    " label "+new String(tokenInfo.label).toUpperCase().trim()+
                    " model "+new String(tokenInfo.model).toUpperCase().trim()+
                    " manufacturerID "+new String(tokenInfo.manufacturerID).toUpperCase().trim()+
                    " utcTime "+new String(tokenInfo.utcTime).toUpperCase().trim()+
                    " serial "+new String(tokenInfo.serialNumber).toUpperCase().trim());

                PrintStream out = new PrintStream(new FileOutputStream(configFile));
                out.print("name=SmartCard\r\n"+"library="+dllFile+"\r\nslotListIndex="+slots[j]+"\r\n");
                out.close();

                SunPKCS11 tempProv = new sun.security.pkcs11.SunPKCS11(configFile);
                KeyStore keystorePkcs11 = KeyStore.getInstance("pkcs11", tempProv);
                keystorePkcs11.load(null, pass);
                KeyManagerFactory kKeyManagerFactory = KeyManagerFactory.getInstance("sunx509");
                //kKeyManagerFactory.init(keystorePkcs11, null);

                Enumeration<String> enume = keystorePkcs11.aliases(); // read aliases from token
                while(enume.hasMoreElements()) { // token has a single certificate
                    String alias = (String) enume.nextElement();
                    System.err.println(alias);
                    Certificate cert = keystorePkcs11.getCertificate(alias);
                    System.err.println("Cert to string "+cert.toString());
                    **keystorePkcs11.getKey(alias, pass);** // Error is HERE
                    PrivateKey priv = (PrivateKey)(keystorePkcs11.getKey(alias, pass));
                }
            }
        } catch (IOException | PKCS11Exception | KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
            Logger.getLogger(PKCS11Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

And the full output and error is:
Token found at position 0 label MTOKEN CRYPTOID model E manufacturerID LONGMAI utcTime  serial AE09D489************
A certificate object
Cert to string [
[
  Version: V3
  Subject: CN=**************, SURNAME=************, GIVENNAME=************, SERIALNUMBER=*************, EMAILADDRESS=**************, OU=OG, O=*****************, L=****, ST=******, C=RO, T=*****
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11

  Key:  Sun RSA public key, 2048 bits
  ...............................
]
Exception in thread "main" java.security.ProviderException: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_ATTRIBUTE_TYPE_INVALID
    at sun.security.pkcs11.P11KeyStore.engineGetKey(P11KeyStore.java:330)
    at java.security.KeyStore.getKey(KeyStore.java:1023)
    at pkcs11test.PKCS11Test.main(PKCS11Test.java:55)
Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_ATTRIBUTE_TYPE_INVALID
    at sun.security.pkcs11.wrapper.PKCS11.C_GetAttributeValue(Native Method)
    at sun.security.pkcs11.wrapper.PKCS11$SynchronizedPKCS11.C_GetAttributeValue(PKCS11.java:1623)
    at sun.security.pkcs11.P11KeyStore.loadPkey(P11KeyStore.java:1298)
    at sun.security.pkcs11.P11KeyStore.engineGetKey(P11KeyStore.java:315)
    ... 2 more

Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Iterating through Models Attributes in Backbone? I have a model that requests a JSON file like below:
[
{
    "ModifiedOn": "2015-04-08 11:17:28.0",
    "BuildingCode": "AU1010A1",
    "BuildingName": "REGUS - BRISBANE",
    "ActionRequired": "A"
},
{
    "ModifiedOn": "2015-04-08 11:17:28.0",
    "BuildingCode": "BR1044A1",
    "BuildingName": "RIO SUL - RIO DE JANEIRO",
    "ActionRequired": "A"
}]

In the console I can see the attributes like so

However when I try and access the model attributes like so, I am getting undefined.
console.log(this.model.attributes.length);

I tried parsing to JSON but that failed.
Do I have to access each individual object in the attributes array my model has?

A: Its an object so you can use Object.keys(this.model.attributes).

A: You can use something like this one.
//for array[object{}, object{},...]
for(var i = 0; i <data.length;i++)
{
    foreach(var key in data[i])
    {
        //print out the attributes for data[i].
        console.log(key);
        //print out the attribute values.
        console.log(data[i][key]);
    }
}

[EDIT]
//for object{object{}, object{},...}
foreach(var childObject in data)
{
    foreach(var key in childObject)
    {
        //print out the attributes for childObject.
        console.log(key);
        //print out the attribute values.
        console.log(childObject[key]);
    }
}

Hope it helps.

A: You can use toJSON(), for in loop to iterate through model attributes
var attrs = this.model.toJSON();
for(key in attrs){
   console.log((key + " -> " + attrs[key]);)
}


text:
Q: MongoDB: Is it possible to have shorter Id for a record or shorter unique Id for a record? I am using PHP + MongoDB. Is it possible to have shorter Id for a record or shorter unique Id for a record?
When I use Id in URL, it is too long. I want it to be shorter. Please advice.

A: As rightly said by @sevenseacat, the ObjectIDs can't be cut short.
Instead, you can always override your _id value to a user-defined number or string. This would allow you to have a smaller value that you can pass in a URL.


text:
Q: Codename One Simulator Screenshots of 6.5" iPhone for App Store Connect? My app is ready for release so I need to make the required screenshots for App Store Connect. I use the CN1 simulator to do that.
Today Apple requires 4 screen sizes if the app is for both iPhones and iPads:

*

*iPhone 6.5" 1284 x 2778

*iPhone 5.5" 1242 x 2208

*iPad Pro 3rd gen 12.9" 2048 x 2732

*iPad Pro 2nd gen 12.9" 2048 x 2732

For 3 & 4 the CN1 skin 'iPadPro' can be used (and I can upload identical screenshots if I understand correctly), for 2 the skin 'iPhone8Plus' can be used, but which skin can be used for 1, the iPhone 6.5"?
From help.apple.com:

For iPhone, screenshots for 6.5-inch iPhone Xs Max and 5.5-inch
devices (iPhone 6s Plus, iPhone 7 Plus, iPhone 8 Plus) are required.
These screenshots will scale down for smaller device sizes.
Screenshot specifications:
6.5 inch (iPhone 12 Pro Max, iPhone 11 Pro Max, iPhone 11, iPhone XS Max, iPhone XR), 1284 x 2778 pixels (portrait), Required if app runs
on iPhone.

I don't see any appropriate skins in the CN1 skin download list. Is there one that can be used?
P.S. My app supports 8 languages and let's say I want to show 5 different screenshots, do I really have to provide 8 x 5 x 4 = 160 screenshots? How do other developers deal with this?

A: I suggest using one of the app screenshot generator companies like these to generate screenshots in the various resolutions for iOS/Android. There are many such companies you can search for, these are a few:
https://theapplaunchpad.com/
https://app-mockup.com/
https://www.appstorescreenshot.com/
https://launchkit.io/
https://play.google.com/store/apps/details?id=cn.gavinliu.snapmod&hl=en_US
This is the best approach as it will always work (even if a new phone comes out tomorrow or requirements change). Notice I'm not affiliated with any of these companies... I did use a few of them for our apps.
Making a skin isn't hard but isn't trivial either. I built a tool a while back that generates skins but it's unmaintained. I find it easier to just add a skin in the project directly here:
https://github.com/codenameone/codenameone-skins/tree/master/Phones/iPhoneX
See the iPhoneX skin. The main challenges here are:

*

*Finding an image of the iPhone where the screen is actually in correct pixel proportions (this is surprisingly hard)

*Then generating the images that represent the screen surface areas

*Editing the properties file for correct font size, pixel density etc.
Then you can just add it to the bash script in the root/XML build and run the script to generate a skin file. Ideally also submit a PR to the project.
I'm not asking you to do that. I'm just not sure when we'll get around to this bug as there are many issues and tasks in queue and most people pick the first option for appstore submissions (or use physical device screenshots).


text:
Q: Is it possible to redirect stdout twice with dup2? I have a problem when I used dup2 direct stdout first to a temporal file, and after to a common file. This is a portion my code:
FILE* fdArch=fopen("file.txt","w");

    char nameBuff[100];

    memset(nameBuff,0,sizeof(nameBuff));

    strncpy(nameBuff,"/tmp/myTmpFile-XXXXXX",sizeof("/tmp/myTmpFile-XXXXXX"));

    int fdNewFile=mkstemp(nameBuff);

    if(fdNewFile==-1){
        perror("error creating temporal file");
    }

    dup2(fdNewFile,STDOUT_FILENO);

    read(fd[0], readbuffer, sizeof(readbuffer));

    char *argv[]={ "/home/user/workspace/CProgram/Debug/program", readbuffer, NULL};

    execv(argv[0],argv);

    close(fdNewFile);

    dup2(fileno(fdArch),STDOUT_FILENO);

    char *argv1[]={"/usr/bin/sort",nameBuff, NULL};

    execv(argv1[0],argv1);

    fclose(fdArch);

    unlink(nameBuff);

I run an external program called program and the out is redirected with dup2 to a temporal file, well this works fine, but after when I redirect with dup2 the stdout to fdArch and run sort over the temporal file, the out is not redirected to fdArch.
Is there an error of concept or something is missing?

A:
I run an external program called program and the out is redirected with dup2 to a temporal file, well this works fine, but after when I redirect with dup2 the stdout to fdArch and run sort over the temporal file,the out is not redirected to fdArch. Is there an error of concept or something is missing?

Your usage of dup2() is fine, but you do have a major error: the execv() function does not return, except when it fails.  It, and all the other functions in its family, replace the program in which it is called with the one specified.  Thus, in fact you never do redirect stdout a second time or run /bin/sort.  If you want to do those things, then you should fork(), perform the execv() in the child process, and have the parent wait() for it to complete before continuing.


text:
Q: How to validate user input email format in a batch script? I would like to get users to enter their email address before running the script and i am doing it like below:
:input
set /p email="Please enter your email address: "
(echo %email% | findstr "@ [] "%email:~7,1%"==""" >nul 2>&1) && (ECHO valid email >nul) || (echo This is not a valid email address.Please try again.) && GOTO Input

With the above code i am able to check on any blank space, presence of @ and atleast 7 chars in the email (i.e even if user types dummy a@b.com) but i am not sure how to check the case where user could just type (@b.com) where nothing is before @. Also i would like to disable or silent "TAB" for the users in the input field so that they can't use TAB.
I am open to doing this whole email format check in any other way?

A: You can try this solution :
@echo off
echo Type your e-mail address :
Set /p "Email="
Call :CheckValidMail %Email%
cls
IF "%errorlevel%" EQU "0" (
    Color 0A
    echo %Email% is valid
) else (
    Color 0C
    echo %Email% is not valid
)
pause & Exit
::*********************************************************************************
:CheckValidMail <Email>
(
echo If IsValidEmail("%~1"^) = True Then
echo    Wscript.Quit(0^)
echo Else
echo    Wscript.Quit(1^)
echo End If
echo Function IsValidEmail(strEAddress^)
echo    Dim objRegExpr
echo    Set objRegExpr = New RegExp
echo    objRegExpr.Pattern = "^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[\w-\.]*[a-zA-Z0-9]\.[a-zA-Z]{2,7}$"
echo    objRegExpr.Global = True
echo    objRegExpr.IgnoreCase = False
echo    IsValidEmail = objRegExpr.Test(strEAddress^)
echo    Set objRegExpr = Nothing
echo End Function
)>"%tmp%\%~n0.vbs"
Cscript /nologo "%tmp%\%~n0.vbs"
Exit /b
::*********************************************************************************


text:
Q: Actual process for fractions to decimals? Alright. I want to get a fraction into decimal. Without a calculator.

$\frac{15}{7} = 2.14285714$

Basically, what are the steps for manually getting that decimal result?

A: You could try standard box form long division like you were taught to divide integers and decimals in elementary school.
Also these numbers are rational so they will always terminate or repeat.

A: Ordinary long division:
   2.1428571...
 --------------
7)15.0000000...
  14
  ---
   1 0
     7
   ---
     30
     28
     --
      20
      14
      --
       60
       56
       --
        40
        35
        --
         50
         49
         --
          10

and so on. Note that this remainder of $10$ repeats an the earlier one, so the whole cycle will repeat: the quotient is $2.142857142857142857\dots$.

A: I have a java class I wrote for java that represents rational numbers using the Bignteger class for the numerator and denominator. Besides basic operations, it also includes an instance method for converting to a repeating decimal and a static method for the reverse converson. Here they are:
public String toRepeatingDecimalString()
{
    if (den.equals(BigInteger.ONE))
        return num.toString();
    BigInteger d = new BigInteger(den.toString());
    long pow2 = 0;
    long pow5 = 0;
    BigInteger two = new BigInteger("2");
    BigInteger five = new BigInteger("5");
    BigInteger ten = two.multiply(five);
    while (d.mod(two).equals(BigInteger.ZERO)) {
        d = d.divide(two);
        pow2++;
    }
    while (d.mod(five).equals(BigInteger.ZERO)) {
        d = d.divide(five);
        pow5++;
    }
    long nonrep = Math.max(pow2, pow5);
    String decimal = num.abs().divide(den).toString() + ".";
    if (num.signum() < 0) decimal = "-" + decimal;
    BigInteger rem = num.abs().mod(den);
    for (long i = 0; i < nonrep; i++) {
        rem = rem.multiply(ten);
        decimal += rem.divide(den).toString();
        rem = rem.mod(den);
    }

    if (!rem.equals(BigInteger.ZERO)) {
        BigInteger stop = new BigInteger(rem.toString());
        decimal += "[";
        rem = rem.multiply(ten);
        decimal += rem.divide(den).toString();
        rem = rem.mod(den);
        while (!rem.equals(stop)) {
            rem = rem.multiply(ten);
            decimal += rem.divide(den).toString();
            rem = rem.mod(den);
        }
        decimal += "]";
    }
    return decimal;

}

and
public static Fraction fromRepeatingDecimalString(String repDecStr)
{
    int index = repDecStr.indexOf('.');
    if (index == -1)
        return new Fraction(new BigInteger(repDecStr), BigInteger.ONE);
    else {
        int sign = 1;
        if (repDecStr.startsWith("-"))
            sign = -1;
        BigInteger intPart = (sign == 1 ? new BigInteger(repDecStr.substring(0,index)) :
                              (new BigInteger(repDecStr.substring(1,index))).negate());
        String fpart = repDecStr.substring(index+1);
        BigInteger TEN = new BigInteger("10");
        index = fpart.indexOf('[');
        if (index == -1) {
            BigInteger d = TEN.pow(fpart.length());

            if (sign == 1)
                return new Fraction(intPart.multiply(d).add(new BigInteger(fpart)),d);
            else
                return new Fraction(intPart.multiply(d).subtract(new BigInteger(fpart)),d);
        }
        else {
            if(!(fpart.endsWith("]")))
                throw new NumberFormatException();
            String nonrep = fpart.substring(0,index);
            String rep = fpart.substring(index+1,fpart.length()-1);
            BigInteger part1 = TEN.pow(nonrep.length());
            BigInteger part2 = TEN.pow(rep.length()).subtract(BigInteger.ONE);
            BigInteger full = part1.multiply(part2);
            if (nonrep.equals(""))
                nonrep = "0";

            if (sign == 1)
                return new Fraction(full.multiply(intPart).add(part2.multiply(new BigInteger(nonrep)))
                                    .add(new BigInteger(rep)),full);
            else
                return new Fraction(full.multiply(intPart).subtract(part2.multiply(new BigInteger(nonrep)))
                                    .subtract(new BigInteger(rep)),full);

        }
    }
}

The fraction is reduced to lowest terms by the class constructor.


text:
Q: How to Implement Dynamic Menu (Drawer) items in React Native this is the scenario:
In Home Route, there is a dropdown which contains SubSystems and based on each subSystem menu items are different. So, when I change subSystem, Menu Items of drawer should update.
I have implemented my drawer to get dynamic items like below code. But, the problem is that when then SubSystems are loaded I go to get the menu items after that I update the menuData state the whole component recompiles and it falls into a loop.
How Can I Overcome This Problem ?

MY CODE
StackNavigationManager.js
import {AuthContext} from './context';

const StackNavigationManager = () => {
const [menuData, setMenuData] = React.useState([]);

const authContext = React.useMemo(() => ({
validateMenuData: menuData => {
      setMenuData(menuData);
    },
  }));

const DrawerScreen = ({route, navigation}) => (
    <Drawer.Navigator
      drawerContent={props => <CustomDrawerContent {...props} />}>
      <Drawer.Screen
        name="HomeDrawer"
        component={Home} />
    </Drawer.Navigator>
  );

function CustomDrawerContent(props) {
    return (
      <SafeAreaView style={{flex: 1}}>
        <DrawerItemList {...props} />
        <FlatList
          data={menuData}
          keyExtractor={data => data.id.toString()}
          renderItem={({item}) => {
            return (
              <DrawerItem
                label={item.name}
                onPress={() => alert(item.id)}></DrawerItem>
            );
          }}
        />
      </SafeAreaView>
    );
  }

return (<AuthContext.Provider value={authContext}>
      <NavigationContainer>
        <Stack.Navigator
          initialRouteName={initialRoute}>

          <Stack.Screen
            name="Home"
            component={DrawerScreen}
            options={{
              headerShown: false,
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>
    </AuthContext.Provider>);

Context.js
import React from 'react';

export const AuthContext = React.createContext();

Home.js
import {AuthContext} from './context';

const home = ({navigation}) => {

const {validateMenuData} = React.useContext(AuthContext);

React.useEffect(() => {
   console.log('MOUNTED EFFECT');
   getSubSystems();

   return () => {
      isMounted = false;
      console.log('UNMOUNTED EFFECT');
    };
  }, []);

const getSubSystems = async () => {
    const subSystemModel = {
      isActive: true,
      isVisible: true,
    };
    fetchSubSystemData(
      subSystemModel,
      response => {
        if (response.list !== null) {
          let listData = [...response.list];

          fetchMenuAction(
            listData[0].id,
            response2 => {
              validateMenuData([...response2.list]);
            },
          );
        }
      },
      () => {},
    );
  };


text:
Q: How does liquibase select a schema if it is not explicitly specified? I would like to use a columnExists precondition for my changeset,
but specifying an exact schema is not possible since we gonna run the thing on multiple environments, and schema names might differ.
The question is, will the schema liquibase chooses be equivalent of
select sys_context('USERENV', 'CURRENT_SCHEMA') from dual;

We are talking about Oracle here if it matters.

A: In Oracle there is a one-to-one relationship between user and schema.
The user account you use to log into Oracle is the default schema unless you have actively changed it in the session.
I was going to answer "just leave out the schema" until I saw that Liquibase requires the schemaName for the columnExists precondition (which is kind of stupid I think)
So you can't really use columnExists, and you will need a <sqlCheck> instead:
<preConditions onFail="HALT">
  <sqlCheck expectedResult="1">
    select count(*)
    from user_tab_columns
    where column_name = 'SOME_COLUMN'
      and table_name = 'SOME_TABLE'
  </sqlCheck>
</preConditions>

user_tab_columns contains the columns of the tables the current user owns (i.e. created).


text:
Q: Why jest fails with "component is part of the declaration of 2 modules"? I'm getting the following exception within executing a test in an angular (nx) project:
Error: Type FooComponent is part of the declarations of 2 modules: FooComponentModule and FooComponentModule! Please consider moving FooComponent to a higher module that imports FooComponentModule and FooComponentModule. You can also create a new NgModule that exports and includes FooComponent then import that NgModule in FooComponentModule and FooComponentModule.

The thing is I'm getting this exception only in IntelliJ (2022.3.1, MacOS) when I use the build-in jest integration. A colleague with Windows is getting this exception everywhere.
I was trying to execute the test app.component.spec.ts in my test project. The test should be executed successfully – everywhere not only in the CLI.
The craziest thing is: I copied the command IntelliJ is executing within the build-in jest integration to the build-in terminal and it just works
I'm really unsure where to address this issue. Is this an issue with jest? Angular? NX? IntelliJ?
Update:
It seems to be an nx related issue. I created a simple clean angular project with jest and the same prerequisites (like lib, path aliases) and everything worked as expected.
Update 2:
I created an issue in the nx repo: https://github.com/nrwl/nx/issues/14494

A: I've found the solution for the issue.
// jest.preset.js
const nxPreset = require('@nrwl/jest/preset').default;

module.exports = {
  ...nxPreset,
  moduleNameMapper: {
    '@nx-test-project/my-lib/(.*)$': '<rootDir>/../../libs/my-lib/src/$1',
  }
};

See https://github.com/iceteabottle/nx-test-project/commit/b376c06f78cd14a5304b71908b2dfe4e8e854ed0
The issue is caused by webpack's path aliases. Jest itself doesn't understand these aliases obviously. See https://gitlab.com/gitlab-org/gitlab/-/issues/299576

A: It's not really the solution of the main problem but to use standalone components instead of SCAM Components would help and avoid the exception.


text:
Q: How to calculate the difference between consecutive sets of two columns in a column range using dplyr I would like to calculate the difference between consecutive columns in a range of columns using dplyr.
For example, using the iris data set I would want to be able to specify the range Sepal.Width:Petal.Width and have a dataframe that contained the original iris data and the differences between the consecutive columns from Sepal.Width:Petal.Width:
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species diff1 diff2
1          5.1         3.5          1.4         0.2  setosa   2.1   1.2
2          4.9         3.0          1.4         0.2  setosa   1.6   1.2
3          4.7         3.2          1.3         0.2  setosa   1.9   1.1
4          4.6         3.1          1.5         0.2  setosa   1.6   1.3
5          5.0         3.6          1.4         0.2  setosa   2.2   1.2
6          5.4         3.9          1.7         0.4  setosa   2.2   1.3

Someone posted a solution loops and lapply (Calculate the difference between consecutive, grouped columns in a data.table) but I'm specifically looking for a dplyr solution.

A: Here's a less advanced approach using dplyr and tidyr verbs. First I gather the columns for differencing into long format, then take their differences vs. previous column, strip out NA's for the first columns which have no previous column, rename the column, spread out, and attach onto the original.
library(tidyverse)
iris %>%
  bind_cols(iris %>%
    rowid_to_column() %>%
    gather(col, val, Sepal.Width:Petal.Width) %>%
    group_by(rowid) %>%
    mutate(val = abs(val - lag(val))) %>%
    filter(!is.na(val)) %>%
    mutate(col = paste0("diff_", col)) %>%
    spread(col, val)  %>%
    select(contains("diff"))
  )

    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species rowid diff_Petal.Length diff_Petal.Width
1            5.1         3.5          1.4         0.2     setosa     1               2.1              1.2
2            4.9         3.0          1.4         0.2     setosa     2               1.6              1.2
3            4.7         3.2          1.3         0.2     setosa     3               1.9              1.1
4            4.6         3.1          1.5         0.2     setosa     4               1.6              1.3
5            5.0         3.6          1.4         0.2     setosa     5               2.2              1.2
6            5.4         3.9          1.7         0.4     setosa     6               2.2              1.3
7            4.6         3.4          1.4         0.3     setosa     7               2.0              1.1

A: Here is an option with tidyverse.  We select the range of columns, remove the first and last column in to a list of data.frames, then use reduce to get the difference between set of equal dimension datasets, and rename the columns
library(dplyr)
library(purrr)
library(stringr)
out <- iris %>%
      select(Sepal.Width:Petal.Width) %>%
      {list(.[-length(.)], .[-1])} %>%
      reduce(`-`) %>%
      rename_all(~ str_c("diff", seq_along(.))) %>%
      bind_cols(iris, .)

head(out)
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species diff1 diff2
#1          5.1         3.5          1.4         0.2  setosa   2.1   1.2
#2          4.9         3.0          1.4         0.2  setosa   1.6   1.2
#3          4.7         3.2          1.3         0.2  setosa   1.9   1.1
#4          4.6         3.1          1.5         0.2  setosa   1.6   1.3
#5          5.0         3.6          1.4         0.2  setosa   2.2   1.2
#6          5.4         3.9          1.7         0.4  setosa   2.2   1.3

Or another approach is to loop through index of columns select the columns, reduce it to a single column with - and bind with the original dataset
map_dfc(3:4, ~ iris %>%
                select(.x-1, .x) %>%
                transmute(diff = reduce(., `-`))) %>%
     bind_cols(iris, .)

A: You could also use grepl and which to get the column indices..
start <- which(grepl("Sepal.Width", colnames(iris)))
end <- which(grepl("Petal.Width", colnames(iris)))

for (i in start:(end-1)) {
eval(parse(text = paste0("iris$diff",i-1," <- iris[,",i,"]-iris[,",i,"+1]")))
}


text:
Q: form_for with slim does not work I am using rails 4.0.2 with ruby 1.9.3. When I use rails scaffold generator like this rails g scaffold Person name:string everything works correctly. But i want to use Slim language for templating, so i added gem 'slim' to my Gemfile. Then changed the file _form.html.erb to this:
- form_for(@person) do |f|
  .field
    == f.label :name
    == f.text_field :name

  .actions
    == f.submit

changed the name to _form.html.slim. But now my form and anything else inside is not rendered at all. Meanwhile if i add  something else outside of the form_for, they work. What's the problem here?

A: It should be the following. Note that you need to render the form, since form is a html element.
= form_for(@person) do |f|
  .field
    == f.label :name
    == f.text_field :name

  .actions
    == f.submit


text:
Q: My JFrame isn't displaying the JLabel with a picture Me and a friend are making a game, and well, neither of us know how do GUI. I'm  also inexperienced in Java(amateur C++ programmer), so there's what you're working with here when it comes to my understanding of what I'm doing.
I written code to display a JFrame with a JLabel with an Image. And the code loads fine, but the picture isn't there.
Here is what I got:
package game;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Pic extends JFrame{
    private static final long serialVersionUID = 1L;

    public Pic(){
        JFrame pic = new JFrame("JFrame");
        JLabel player = new JLabel();
        ImageIcon player_icon = new ImageIcon(getClass().getResource("/res/Untitled.bmp"));
        player.setIcon(player_icon);
        player.setVisible(true);
        player.setSize(100, 100);
        pic.setVisible(true);
        player.setLocation(25, 25);
        pic.setSize(200, 200);
    }

    public static void main (String[] args){
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Pic();
            }
        });
    }
}

This isn't part of the game itself but a test run with a random sprite put in a package named res.
Now my Question: What did I do wrong to where I can't see my picture, and how can I fix this?
I would also really appreciate a detailed answer/link that could help with learning GUIs as well as I can't seem to understand some of the older explanations I found on here.

A: ImageIcon doesn't support bmp file format, it supports gif, jpeg and png
Instead, try using ImageIO.  See Reading/Loading an Image for more details
BufferedImage img = ImageIO.read(getClass().getResource("/res/Untitled.bmp"));
ImageIcon player_icon = new ImageIcon(img);

Also, you're not adding the JLabel to anything...
pic.add(label);

Also...
player.setVisible(true);
player.setSize(100, 100);

Are pointless, Swing components are visible by default and the frame is using a layout manager
It might help to keep Creating a GUI With JFC/Swing book marked.
You will probably also find How to Use Labels of some use as well

A: you forgot to add the jlabel to jframe..
pic.add(player);

A:
but the picture isn't there.

I don't see where you add the label to the frame:
pic.add( label );

I would also really appreciate a detailed answer/link that could help with learning GUIs

Start with the Swing tutorial. See How to Use Icons.

A: EDIT: Ok thanks for pointing that out madprogrammer. Learned something new
On your other question, a good gui tutorial, I found the GUI section of this book very helpful

A: This can be possible solution !!
ImageIcon player_icon = new ImageIcon(getClass().getResource("/res/Untitled.bmp"));
JLabel player = new JLabel(player_icon); //add Image in JLabel
pic.add(player);  // add this label in JFrame


text:
Q: Flutter, How to fit width in Column to first child This is my code .
 ConstrainedBox(
      constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height * 0.5),
      child: (message.caption != null)
          ?  Column(
                children: [
                  Flexible(
                    child: ImageLoader(message: message, controller: _),
                  ),
                   Container(
                    child: Padding(
                      padding: const EdgeInsets.only(top: 8.0),
                      child: BubbleText(
                          message: message,
                          fromCaption: true,
                          account: account),
                    ),
                  ),
                ],

          )
          : ...

This is what my column looks like with 2 children

Here is how I want it to look

A: if you want to dynamic width you must use statefull widget, because you have storing first child width. So below code will works for your sitution
class Challenge extends StatefulWidget {
  const Challenge({Key? key}) : super(key: key);

  @override
  _ChallengeState createState() => _ChallengeState();
}

class _ChallengeState extends State<Challenge> {
  final GlobalKey _firstChildKey = GlobalKey();
  double? childWidth;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final RenderBox renderBoxRed = _firstChildKey.currentContext.findRenderObject();
      final size = renderBoxRed.size;
      setState(() {
        childWidth = size.width;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return ConstrainedBox(
        constraints: BoxConstraints(maxHeight: size.height * 0.5, maxWidth: childWidth ?? size.width * .2),
        child: Column(
          children: [
            Flexible(
              key: _firstChildKey,
              child: ImageLoader(message: message, controller: _),
            ),
            Container(
              child: Padding(
                padding: const EdgeInsets.only(top: 8.0),
                child: BubbleText(message: message, fromCaption: true, account: account),
              ),
            ),
          ],
        ));
  }
}

A: It actually amazes me how often does this need arise and how no one has wrote a package about this yet.
So I did: https://pub.dev/packages/flex_with_main_child
It'll look something like this:
ColumnWithMainChild(
  mainChild: Flexible(
    child: ImageLoader(message: message, controller: _),
  ),
  childrenBelow: [
    Container(
      child: Padding(
        padding: const EdgeInsets.only(top: 8.0),
        child: BubbleText(
            message: message,
            fromCaption: true,
            account: account),
      ),
    ),
  ],
)


text:
Q: Turn IIS7 HTTP Error Handling Off? I just got setup on my first Windows Server 2008 / IIS7.5 server for a contest I am participating in. I can't for the life of me figure out how to turn OFF error handling COMPLETELY. The only options I see are:

*

*Custom

*Detailed

*Detailed Local, custom for remote

I want to turn the feature off completely, and I don't see any way to do that. Am I missing something?
My Situation:
I have a RESTful PHP framework that catches exceptions and emits an HTTP 500 status if the exception has not already been handled. It then puts the specified exception message in the response body and sends it to the browser. This works fine in Apache - the correct headers are sent and the message is displayed to the user. In IIS, however, the response for 4xx and 5xx HTTP status codes is always intercepted and injected with some other prepared message or HTML file, and that's exactly what I don't want it to do anymore. Please help!

A: After some more extensive searching, I found the answer here:
http://blogs.msdn.com/webdevelopertips/archive/2009/08/24/tip-93-did-you-know-php-and-custom-error-pages-configuration.aspx
The solution is to manually edit your web.config file with this custom "httpErrors" entry:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpErrors existingResponse="PassThrough" />
    </system.webServer>
</configuration>

However, due to IIS 7.0 "lockdown" feature you might get a "This configuration section cannot be used at this path. This happens when the section is locked at a parent level." error. To solve that, execute the following in the command prompt:
cd C:\Windows\System32\inetsrv

appcmd unlock config /section:httpErrors

A: In IIS Manager -> Site -> Error Pages, right-click each error page and choose 'Remove'.
Unfortunately there is not a way to tell IIS not to interfere from the script side, so it's always an annoying deployment issue.


text:
Q: Convert multiple date formats stored as text I have a column that is a date column that is stored as text.
This has three formats in it.

*

*dd mmm yyyy

*MM/dd/yyyy

*yyyy-mm-dd

I need to convert all these to one format. Im hoping 112 (yyyymmdd)
can anyone help as I keep getting an out of range error.
I have got it to return this correctly
CONVERT(varchar(10), ISNULL(CAST(cf3.FieldValue as date),CAST('01/01/1900' as date)),101)

But I cant seem to then convert to yyyymmdd format without the range error.

A: Input:
01 Jan 1900
12/5/2013
2013-12-10

Query:
SELECT CONVERT(VARCHAR, CONVERT(DATE, TestColumn), 112)
FROM tblTestTable

Output:
19000101
20131205
20131210

Using SQL Server 2008 R2

A: You can use combination of STR_TO_DATE with DATE_FORMAT to achieve desired results.
SELECT
IFNULL(
  DATE_FORMAT(STR_TO_DATE(COL_NAME, '%d %b %Y'), '%Y%m%d'),
  IFNULL(
    DATE_FORMAT(STR_TO_DATE(COL_NAME, '%d-%m-%Y'), '%Y%m%d'),
    DATE_FORMAT(STR_TO_DATE(COL_NAME, '%Y-%m-%d'), '%Y%m%d')
  )
) FROM TABLE_NAME;

STR_TO_DATE will convert the string into a datetime datatype and then DATE_FORMAT will convert datetime into the desired format('%Y%m%d' -> 'yyyymmdd').

A: declare @mydate datetime = '2017-03-20'

select RIGHT('0' + CAST(DATEPART(DD,@mydate) as nvarchar(max)),2) + ' ' + UPPER(CAST(DATENAME(month,@mydate) AS VARCHAR(3))) + ' ' + CAST(DATEPART(YEAR, @mydate) as nvarchar(MAX)) as 'dd mmm yyyy',
RIGHT('0' + CAST(DATEPART(DD,@mydate) as nvarchar(max)),2) + '/' + RIGHT('0' + CAST(DATEPART(MONTH, @mydate) as nvarchar(Max)),2) + '/' + CAST(DATEPART(YEAR, @mydate) as nvarchar(MAX)) as 'dd/mm/yyyy',
CAST(DATEPART(YYYY,@mydate) as nvarchar(max)) + '-' + RIGHT('0' + CAST(DATEPART(MONTH, @mydate) as nvarchar(Max)),2) + '-' + RIGHT('0' + CAST(DATEPART(DD, @mydate) as nvarchar(MAX)),2) as 'yyyy-mm-dd'

You can manually get the corresponding dateparts of the date and perform the formatting yourself. (if format needed is not readily available)


text:
Q: Jenkins dotnet lambda deploy-serverless Could not execute because the specified command or file was not found I am new to CI/CD and trying to deploy a simple serverless function through Jenkins and getting error.
Here are my steps

*

*Create a new project using dotnet new serverless.AspNetCoreWebAPI

*Configured Git source {GitHub} where this project is located.

*Added following lines in Build Step
`export PATH=$PATH:/usr/local/share/dotnet:/usr/local/bin
dotnet lambda deploy-serverless`
After running the above command I get the error

/usr/local/share/dotnet/dotnet lambda deploy-serverless Could not execute because the specified command or file was not found. Possible reasons for this include:
  You misspelled a built-in dotnet command.
  You intended to execute a .NET Core program, but dotnet-lambda does not exist.
  You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.
  Build step 'Execute shell' marked build as failure Finished: FAILURE

Needless to say I can successfully run dotnet lambda deploy-serverless if using terminal window.
Any idea what's wrong here?

A: Install first below command in CMD

dotnet tool install -g Amazon.Lambda.Tools

Then you can find dotnet command in cmd.

A: Solved the issue finally.

Compared the .csproj files one for successful lambda deployment and one where it was failing. Noticed that following lines were the difference. It worked as soon as I added the below in my project file.

<ItemGroup><DotNetCliToolReference Include="Amazon.Lambda.Tools" Version="2.2.0" /></ItemGroup>

It will be still interesting to know that why dotnet lambda deploy-serverless works from terminal window for the same project without the above line but not from inside jenkins job.


text:
Q: Arduino Timer Library and void pointer I use this timer Library : https://github.com/JChristensen/Timer/tree/v2.1
code example :
int afterEvent = t.after(10000, doAfter, (void*)0);

void doAfter(void *context)
{
    Serial.println("stop the led event");
    t.stop(MyledEvent);
}

Documentation :

The context is a void pointer, so it can be cast to any other data
    type. Its use is optional, if you don't need it, just code (void*)0 as
    in the above examples, but be sure that the callback function
    definitions have it in their argument list

int8_t after(unsigned long duration, void (callback)(void), void*
  context);

I need to put a argument in "afterEvent" ( for futur use in "doAfter" ), I don't understand how to do this .Can you explain me how to do a argument list on  this "doAfter" and how to put the argument on "t.after" ?
My test :
int afterEvent = t.after(10000, doAfter(5), (void*)0);

void doAfter(int x, void *context)     { ..code... }

Error :

error: declaration of 'int type' shadows a parameter
error: arguments to function 'void doAfter(int, void*)'error: too few

Thanks

A: If you need any parameters to your function then they need to be passed in via the context pointer that's what it is there for.  So a simple example might be the following:
void doAfter(void *my_param) {
     int x = *(int *)my_param;

     ..... your code here ...

}

And then to call it you would just do
const int input_param = 5;
int afterEvent = t.after(10000, doAfter, (void *)&input_param);

If you needed to pass more than one parameter then that can be done with a struct:
struct param_list {
     int param1;
     double param2;
};

void doAfter2(void *context)
{
      struct param_list *params = context;

      .... code here can access params with params-> ..

}

struct param_list p = {1, 2.0};
int afterEvent = t.after(10000, doAfter2, (void *)&p);


text:
Q: Nexus OSS: publish to static mirror Do you know a way to configure Nexus OSS so that it publishes the artifact repository to a remote server in a form that can be statically served, e.g. by Apache Httpd? I'd like to use this static copy to serve only my own artifacts, so the nexus server could actively trigger an update in case there is something new published.
Technically, I think it should be possible to create the metadata for the repo and store them in a static file, but I'm not sure with that. Any hints appreciated.
If there is another repo manager to achieve that, it would be fine for me as well.
I clearly understand the advantages to use the repo manager directly, but due to IT rules I can run Nexus only internally and it would be necessary to have these artifacts available in a (private) repo copy on the Internet as well.

A: A typical way to solve this IT requirement of only exposing known servers like Apache httpd is to setup Apache httpd as a reverse proxy as documented here.
You can use that approach in a more restrictive way by only exposing a specific repository or better repository group (so you can combine snapshots and releases) and tying that together with a specific user or a specifically restricted setup of the anonymous user that is used by default when no credentials are passed through.
Also if you need more help feel free to contact us in the user mailinglist or on hipchat.


text:
Q: Python Pyinstaller MSYS problem with PyQtWebKit web_browser.py
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'web_browser.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(779, 257)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName("verticalLayout")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

web_browser_main.py
from web_browser import *
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QUrl
from PyQt5.QtWebKitWidgets import QWebView , QWebPage
import sys
class TestBrowserCode:
    def __init__(self):
        self.app = QtWidgets.QApplication(sys.argv)
        self.mainWindow = QtWidgets.QMainWindow()
        self.main_ui = Ui_MainWindow()
        self.main_ui.setupUi(self.mainWindow)
        self.mainWindow.showMaximized()

        self.open_google()

        sys.exit(self.app.exec_())

    def open_google(self):
        self.google_url = 'http://www.google.com'

        self.main_ui.chat_browser = QWebView()
        self.main_ui.chat_page = QWebPage()
        self.main_ui.chat_browser.setPage(self.main_ui.chat_page)
        self.main_ui.chat_browser.setUrl(QUrl(self.google_url))

        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)

        self.main_ui.chat_browser.setMinimumSize(QtCore.QSize(0, 398))
        self.main_ui.chat_browser.setMaximumSize(QtCore.QSize(16777215, 398))

        self.main_ui.chat_browser.setSizePolicy(sizePolicy)
        self.main_ui.chat_browser.setStyleSheet("background-color:white;border:1px solid #dadada;")

        self.main_ui.verticalLayout.addWidget(self.main_ui.chat_browser)

        self.main_ui.chat_browser.show()

program = TestBrowserCode()

*

*Run the code from source:

Χρήστος@Chris-pc MINGW64 /c/python/scripts/Papinhio player/notes
$ python web_browser_main.py
(The site is displayed correct)

*Make an .exe file (full result here)

Traceback (most recent call last):
  File "C:/Python/Scripts/Papinhio player/notes/web_browser_main.py", line 4, in

    from PyQt5.QtWebKitWidgets import QWebView , QWebPage
  File "", line 991, in _find_and_load
  File "", line 975, in _find_and_load_unlocked
  File "", line 657, in _load_unlocked
  File "", line 556, in module_from_spec
  File "", line 1101, in create_module
  File "", line 219, in _call_with_frames_removed
  File "", line 991, in _find_and_load
  File "", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'PyQt5.QtWebKit'
[17208] Failed to execute script web_browser_main

Result error import PyQt5.QtWebKitWidgets
All that inside msys2 mingw64 console.
How can I compile the above files?

A: pyinstaller --onefile --hidden-import PyQt5.QtWebKit web_browser_main.py

The upper code includes the missing module QtWebKit.
I suggest to use --onedir instead of --OneFile because I think the output exe is more stable.
(I had a Segmentfault runtime error after some seconds in an application like the web_browser_main app)
Works now!!!

A: The upper code includes the missing module QtWebKit. I suggest to use --onedir instead of --OneFile because I think the output exe is more stable. (I had a Segmentfault runtime error after some seconds in an application like the web_browser_main app)
Works now!!!


text:
Q: Generate images from AVAssetImageGenerator gives same image duplicates for different times I am trying to generate thumbnail images from a video using the following code. It does generate UIImages but the images are all the same at different time. For example, for a video which lasts 3 seconds, it will generate 6 images but all the images are the same image for the very beginning of the video. Any ideas on what I did wrong?
let asset = AVAsset(url: videoURL)
                let imageGenerator = AVAssetImageGenerator(asset: asset)

                let scale = 2
                let step = 1
                let duration = Int(CMTimeGetSeconds(asset.duration) * Double(scale))
                var epoches = [NSValue]()
                for i in stride(from: 1, to: duration, by: step) {
                    //let time = CMTimeMake(Int64(i), Int32(scale))
                    let time = CMTimeMakeWithSeconds(Double(i)/Double(scale), Int32(scale))
                    let cgImage = try! imageGenerator.copyCGImage(at: time, actualTime: nil)
                    let uiImage = UIImage(cgImage: cgImage)
                    self?.imagePool.append(uiImage)
                    epoches.append(NSValue(time: time))
                }

A: By default AVAssetImageGenerator gives itself very generous tolerances when fetching frames for a given time. If you use copyCGImage's actualTime you'll see in practice that it's something like one or two seconds, although technically it's kCMTimeFlags_PositiveInfinity, so in your short video half of your frames will be duplicates.
So set the tolerances to something smaller to see unique frames:
imageGenerator.requestedTimeToleranceBefore = CMTimeMake(1, 15)
imageGenerator.requestedTimeToleranceAfter = CMTimeMake(1, 15)


text:
Q: Unity 3d How to reset a counter on a trampoline when you stop bouncing I started coding with unity and C# a week ago so forgive me if this is a dumb question.
I have made a trampoline in unity, the player jumps on it and it bounces the player up, higher each time using simple if statements and a counting integer.
My playerController script is set in the unity inspector. The trampoline acts as intended, it's working fine.
However, I would like it if the player would reset their momentum after leaving the trampoline and touching the ground.
Currently, after leaving the trampoline and getting back on it, they are bouncing as high as they were when they left it. So the counting integer needs to be reset.
I thought to do this with a simple check of the players "isgrounded" function and if true reset the trampolines jumpCount to 0.
But this isn't working. I have no idea why. To me, it seems like it should. The isgrounded is evaluating to true but the "else if (playerFP.groundCheck == true)" isnt activating.
Heres my code:
public class Trampoline : MonoBehaviour
{
    public PlayerMovement1stPerson playerFP;
    [SerializeField] int jumpCount = 0;

    private void OnTriggerEnter(Collider collision)
    {
        if (jumpCount == 0 && collision.gameObject.tag == "Player" )
        {
            Debug.Log("Bounce 1 activated");
            playerFP.velocity.y = 5;
            jumpCount ++;
        }

        else if (jumpCount == 1 && collision.gameObject.tag == "Player")
        {
            playerFP.velocity.y = 10;
            jumpCount ++;
        }

        else if (jumpCount == 2 && collision.gameObject.tag == "Player")
        {
            playerFP.velocity.y = 15;
            jumpCount ++;
        }

        else if (jumpCount >= 3 && collision.gameObject.tag == "Player")
        {
            Debug.Log("Max Bounce");
            playerFP.velocity.y = 15;
        }

        else if (playerFP.groundCheck == true)
        {
            Debug.Log("Bounces reset");
            jumpCount = 0;
        }
    }
}

I'd really appreciate any tips.

A: Your bouncing (and ground check code) is being ran inside the Trampoline's OnTriggerEnter method. This means that the check will ONLY happen when the player enters the trampoline's trigger, not when the player lands on any ground.
Move the if check outside of the OnTriggerEnter method. The Update() method inside the Trampoline script would work, but the cleanest implementation would be to store the bouncing information within the player, rather than each trampoline instance. (That also allows a player to bounce on multiple trampolines without losing the height between them)


text:
Q: Path & Highlights Panel have no data available to display component contents I created a new custom object and created an account and a contact which are required fields on that object. I also created an instance of the custom object and saved it. The problem I am having is that when I add the path or the highlights panel to a record page in the lightning app builder, each of them display the message "No data available to display component contents." Do you have any idea why that might be happening? My custom object is deployed, my path is active, and it has the first step all filled out.
Edit - View In Lightning:

When I was just an admin without Lightning permissions the view in app builder showed the specific error I mentioned. After I gave myself Lightning permissions it now shows up blank, although the highlights panel now has info.
I have only filled out the first step, but this is what my path setup looks like:

A: I just figured out the problem! I had only one record type, master. I was having trouble with something else and thought adding a specific record type might help so I added anther called sales. At that point I deactivated the master one.  Well, I did not assign the sales record type to the system admin profile. I went back and checked activate on the master path and it now appears! Thanks @Rao for putting the idea about checking activation status in my head!

A: 1) Did you setup path for this object?
2) If you go to edit page on the custom object and click on the path component, you will see configure the path in the right side panel.
Note: If you do not see your custom object as an option when setting up path, create a picklist for the custom object and the picklist that shows available objects to create path will automatically show your custom object.


text:
Q: Access 2010 Query pulling data that matches a label value I have a system where a lecturer logs on, when he logs on his username value is put through to a label on the next page, from there, he will be able to view two columns of information, and only if the column on the right's value is the same as whats in the label.
Is it possible to pull this value from a textbox or something I can store on this page?
Would this almost be possible?
SELECT [moduleID], [lecturerID] FROM [Teaching] WHERE [lecturerID] = label1.text

A: Yes, you can. You will need to reference the form name that contains the control where the ID is stored. Something like the following should work:
SELECT MyTable.*
FROM MyTable
WHERE MyTable.LectureID=[Forms].[Form1].[txtID]

I would probably put the LectureID into a text box instead of a label and either lock the control so it can't be edited or make the control invisible so the user doesn't see it.


text:
Q: Magento backend new order, new customer - email field missing we have th strangest problem. In admin/sales_order_create/index the email field is missing. We actually found this in 2 stores.
The form is loaded here
app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Account.php
// add system required attributes
foreach ($customerForm->getSystemAttributes() as $attribute) {
    /* @var $attribute Mage_Customer_Model_Attribute */
    if ($attribute->getIsRequired()) {
        $attributes[$attribute->getAttributeCode()] = $attribute;
    }
}

It seems that $attribute->getIsRequired() is not true for $attribute->getAttributeCode()=="email"
I have seen this for the 3rd time now in 3 stores.
Question: Where and how can the required-ness of the "email" attribute be changed? (so we don't see this problem anymore)

A: We changed this line to:
    if ($attribute->getIsRequired()||$attribute->getAttributeCode()=="email") { // TEMP MODIFICATION
        $attributes[$attribute->getAttributeCode()] = $attribute;
    }

But I don't know how the required-ness of the "email" attribute changed. If someone has an answer to that I am very interested

A: I have checked and solved. You can make Email field require.
Please update below code
protected function

addAdditionalFormElementData(Varien_Data_Form_Element_Abstract $element)

{

switch ($element->getId()) {

case 'email':

$element->setRequired(1);

$element->setClass('validate-email');

break;

}

return $this;

}

In app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Account.php.


text:
Q: Powershell: Filter Hashtable - and get back a Hastable Filtering a Hashtable using GetEnumerator always returns a object[] instead of a Hashtable:
# Init Hashtable
$items = @{ a1 = 1; a2 = 2; b1 = 3; b2 = 4}
# apply a filter
$filtered = $items.GetEnumerator() | ?{ $_.Key -match "a.*" }
# The result looks great
$filtered
  Name                           Value
  ----                           -----
  a2                             2
  a1                             1
# … but it is not a Hashtable :-(
$filtered.GetType()
  IsPublic IsSerial Name                                     BaseType
  -------- -------- ----                                     --------
  True     True     Object[]                                 System.Array

Is there a nice solution to this problem?
Thanks a lot for any Help!,
kind regards,
Tom

A: Here's an even simpler function, it even has include and exclude functionality
function Select-HashTable {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory,ValueFromPipeline)][Hashtable]$Hashtable,
        [String[]]$Include = ($HashTable.Keys),
        [String[]]$Exclude
    )

    if (-not $Include) {$Include = $HashTable.Keys}

    $filteredHashTable = @{}
    $HashTable.keys.where{
        $PSItem -in $Include
    }.where{
        $PSItem -notin $Exclude
    }.foreach{
        $filteredHashTable[$PSItem] = $HashTable[$PSItem]
    }
    return $FilteredHashTable
}

Examples:
$testHashtable = @{a=1;b=2;c=3;d=4}
$testHashTable | Select-HashTable -Include a

Name                           Value
----                           -----
a                              1

$testHashTable | Select-HashTable -Exclude b
Name                           Value
----                           -----
c                              3
d                              4
a                              1

$testHashTable | Select-HashTable -Include a,b,c -Exclude b

Name                           Value
----                           -----
a                              1
c                              3

A: As the accepted answer was resulting in a BadEnumeration exception for me (but still worked), I modified it to not throw an exception and also made sure that the original HashTable is not modified by cloning it first:
# Init Hashtable
$items = @{ a1 = 1; a2 = 2; b1 = 3; b2 = 4}

$filtered = $items.Clone()

$items.Keys | ForEach-Object {
    if ($_ -notmatch "a.*") {
        $filtered.Remove($_)
    }
}

A: On a modern PowerShell (5+ as far as I remember) you can use reduce pattern. For that you need to use this form of ForEach-Object:
$Hashtable.Keys
    | ForEach-Object -Begin {
        $FilteredHashtable = @{}
    } -Process {
        if ($_ -eq 'Example') {
            $FilteredHashtable[$_] = $Hashtable[$_];
        }
    } -End {
        $FilteredHashtable
    }

Yes, this snippet will return Hashtable.

A: $filtered is an array of dictionary entries. There's no single cast or ctor for this as far as I know.
You can construct a hash though:
$hash = @{}
$filtered | ForEach-Object { $hash.Add($_.Key, $_.Value) }

Another workflow:
# Init Hashtable
$items = @{ a1 = 1; a2 = 2; b1 = 3; b2 = 4}

# Copy keys to an array to avoid enumerating them directly on the hashtable
$keys = @($items.Keys)
# Remove elements not matching the expected pattern
$keys | ForEach-Object {
    if ($_ -notmatch "a.*") {
        $items.Remove($_)
    }
}

# $items is filtered


text:
Q: Create a barcode image in java using jasperreports, without saving the image on disk I need to create a barcode image in java using jasperreports, currently I'm doing this saving the image file on disk, but I need to do it without saving the image on disk. I need to create the barcode image in memory an then send it to iReport as a parameter.
This is what I have done:
Map<String, Object> parameters = new HashMap<String, Object>();
String imagePath = "\\\\netw\\barCode.jpg";
parameters.put("rutaCodigoBarrasVal", imagePath);

Barcode barCode = BarcodeFactory.createPDF417("1234567890");
barCode.setDrawingText(false);
barCode.setBarHeight(33);
barCode.setBarWidth(207);

FileOutputStream fOS = new FileOutputStream(imagePath);
BarcodeImageHandler.writeJPEG(barCode, fOS);
fOS.close();

What can I do?

A: You should first try to write the Barcode into a byte array or InputStream, looking at your library documentation.
JasperReports supports passing an image as a InputStream parameter, and draw that in the report.
InputStream imageStream = ...;
parametros.put("image", imageStream );

From JasperReports, receive that parameter as java.io.InputStream, then draw it with an image widget and the following properties:
Image Expression: $P{image}
Expression Class: java.io.InputStream
I hope it helps.

A: Finally this is what I did using barcode4j library:
ByteArrayOutputStream os = new ByteArrayOutputStream();
PDF417Bean barCode = new PDF417Bean();
boolean antiAlias = false;
int orientation = 0;
int dpi = 300;

BitmapCanvasProvider canvas = new BitmapCanvasProvider(dpi, BufferedImage.TYPE_BYTE_BINARY, antiAlias, orientation);

BarcodeDimension dim = new BarcodeDimension(207, 42);
canvas.establishDimensions(dim);
barCode.setColumns(7);
barCode.generateBarcode(canvas, codeToConvert);
canvas.finish();

String mime = MimeTypes.MIME_JPEG;
os = new ByteArrayOutputStream();

final BitmapEncoder encoder = BitmapEncoderRegistry.getInstance(mime);
encoder.encode(canvas.getBufferedImage(), os, mime, dpi);
fis = new ByteArrayInputStream(os.toByteArray());


text:
Q: Phantom Data in Python BST Preorder I have a python function for finding the preorder of Binary Search Trees.
class Node:
  def __init__(self, val = 0, left = None, right = None):
    self.val = val
    self.right = right
    self.left =

class Tree:
  def __init__(self, root=None):
    self.root = Node(root) if type(root) != Node else root

  def add(self, val):
    node = self.root
    found = False
    while not found:
      if node.val >= val:
        if node.left is None:
          node.left = Node(val)
          found = True
        else:
          node = node.left
      else:
        if node.right is None:
          node.right = Node(val)
          found = True
        else:
          node = node.right

def preorder(node, output = []):
  output += [node.val]
  if node.left is not None:
    preorder(node.left, output)
  if node.right is not None:
    preorder(node.right, output)
  return output

This works fine on the first call, but every time I run it after the data from previous calls shows up. For example:
 preorder(tree.root)
[3, 3, 3, 3, 2, 1, 5, 4, 5]
 preorder(tree.root)
[3, 3, 3, 3, 2, 1, 5, 4, 5, 3, 3, 3, 3, 2, 1, 5, 4, 5]
 preorder(tree.root)
[3, 3, 3, 3, 2, 1, 5, 4, 5, 3, 3, 3, 3, 2, 1, 5, 4, 5, 3, 3, 3, 3, 2, 1, 5, 4, 5]

This is easily remedied by adding a empty list to the input parameters, for example:
 preorder(tree.root, [])
[3, 3, 3, 3, 2, 1, 5, 4, 5]
 preorder(tree.root, [])
[3, 3, 3, 3, 2, 1, 5, 4, 5]

I have my solution to the problem, but my question is why is this occurring? The preorder function doesn't seem to be changing the state of the tree, and I would assume that output would be set to the default value of [] unless a different list is given. Any information would be appreciated. Thank you!


text:
Q: How do I use a class inside another class? I need to create a processing app with 4 buttons (each having different strokecolor, fillcolor and textSize). I have followed the instructions given to me from uni and created 3 classes, for buttons, styles and styleCollection. i am stuck at this point:
"Modify the display function in the Button class to use the text label of the button to get the
Style associated with that name from the StyleCollection and use the background, fill,
stroke, and text size from that style to style the button using those settings.
Now display your buttons on the canvas. Update your draw function to display the buttons.
Use a while or for statement to iterate through the array of buttons, calling the display
function of each button. ."
I have tried to modify the button.display function but it keeps saying nullPointerException error.
//Setup tab
String message;
String[] styleNames={"dark","light","red","blue"};
StyleCollection styles;
Style currentStyle;
Button b1;
Button[] buttons;
float bx=150;

void setupButtons(){
  buttons = new Button[styleNames.length];
  for (int index=0;index<styleNames.length;index++){
    buttons[index]= new Button(bx,500);
    buttons[index].setLabel(styleNames[index]);
    bx=bx+150;
  }
}

void setupStyles(){
  styles = new StyleCollection();
  Style darkStyle= new Style("dark",0,255,255,15);
  styles.addStyle(darkStyle);
  Style lightStyle= new Style("light",255,0,0,15);
  styles.addStyle(lightStyle);
  Style redStyle= new Style("red",#D69797,#FF0000,#FF0000,15);
  styles.addStyle(redStyle);
  Style blueStyle= new Style("blue",#8788EA,#0000FF,#0000FF,15);
  styles.addStyle(redStyle);
  styles.setDefaultStyle(blueStyle);

  currentStyle=styles.getDefaultStyle();
}

void setup(){
  size(800,600);
  setupStyles();
  setupButtons();
  bx = 150;
  b1 = new Button(100,200);

  message = ("Lorem Ipsum is simply dummy text of the printing and typesetting industry. " +
  "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, "+
  "when an unknown printer took a galley of type and scrambled it to make a type "+
  "specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, "+
  "remaining essentially unchanged. It was popularised in the 1960s with the release of "+
  "Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing "+
  "software like Aldus PageMaker including versions of Lorem Ipsum.");
  println(styleNames.length);
}

void draw(){

  background(currentStyle.getBackground());
  fill(currentStyle.getFillColor());
  textSize(currentStyle.getTextSize());
  text(message,100,100, width/2,height);
  buttons[0].display();
  buttons[1].display();
  buttons[2].display();
  buttons[3].display();
}

class Style{
  private int fillColor;
  private int strokeColor;
  private int bgColor;
  private int textSize;
  private String name;

  public Style(String nm, int bgCol, int strCol, int fC, int tSize){
    name=nm;
    bgColor=bgCol;
    strokeColor=strCol;
    fillColor=fC;
    textSize=tSize;
  }

  public String getSName(){ return name;}
  public int getBackground(){return bgColor;}
  public int getFillColor(){return fillColor;}
  public int getStrokeColor(){return strokeColor;}
  public int getTextSize(){return textSize;}
  public String toString(){return name+ " "+bgColor;}

}

import java.util.HashMap;
class StyleCollection{
  private HashMap <String,Style> styles;

  public StyleCollection(){
    styles= new HashMap <String, Style>();
  }

  public void addStyle(Style s){
    styles.put(s.getSName(),s);
  }
  public void setDefaultStyle(Style sD){
    styles.put("default", sD);
  }
  public Style getStyle(String stname){
    return styles.get(stname);
  }

  public Style getDefaultStyle(){
    return styles.get("default");
  }

}

class Button{
  StyleCollection s;
  private float x,y,w,h;
  private String label;
  Style format;

  public Button(float _x, float _y){
    s=new StyleCollection();
    x=_x;
    y=_y;
    w=100;
    h=75;
  }
  public void display(){
    format = s.getStyle(label);
    fill(255);
    rect(x,y,w,h);
    textAlign(CENTER);
    fill(0);
    //textSize(format.getTextSize());
    text(label,x+w/2,y+h/2);
  }

  public void setLabel(String _label){
    label=_label;
  }
  public String getText(){
    return label;
  }

  boolean isInside(float _mx, float _my){
    float mx,my;
    mx=_mx;
    my=_my;
    if((mx>x)&&(mx<x+w)&&(my>y)&&(my<y+h)){
      return true;
    }
    else{
      return false;
    }
  }
}