text:
Q: Extracting InDesign CS4 Graphics using C# and COM I'm trying to get details of the graphics in an InDesign file.  For technical reasons I'm using COM.  Not my favourite, as (discussed elsewhere in StackOverflow) you have to spend half your life casting.  In Theory (!), the code snippet belwo should work.  Intellisense shows doc.AllGraphics  as returning objects.
The CS3 scripting reference at http://www.indesignscriptingreference.com/CS3/JavaScript/Document.htm shows it as Array of Graphic
for (int g = 1; g <= doc.AllGraphics.Count; g++) {
  InDesign.Graphic graphic = (InDesign.Graphic) doc.AllGraphics[ g ];
  ....
}

However, I get this error message:

Unable to cast COM object of type
  'System.__ComObject' to interface type
  'InDesign.Graphic'. This operation
  failed because the QueryInterface call
  on the COM component for the interface
  with IID
  '{6AE52037-9E4E-442D-ADFC-2D492B4BCBEF}'
  failed due to the following error: No
  such interface supported (Exception
  from HRESULT: 0x80004002
  (E_NOINTERFACE)).

I've tried using alternative constructs to return an object and then cast this to an Indesign.Graphic.  All fail with the same error.  I can't believe that Adobe missed including this interface.
Any suggestions as to a solution so I can get the graphic content?

A: I am running Win7 64 and CS4 here and had the E_NOInterface message too.
It took me 6 hours to solve it via google, try and error. On my way thru the internet I saw your posting here and came back to write you what helped me.
During install the Com-Objects are not registered correctly. To solve this

*

*go to the folder

*

*for cs3: %ALLUSERSPROFILE%\Adobe\InDesign\Version 5.0\Scripting Support\5.0
in my case: C:\ProgramData\Adobe\InDesignVersion 5.0\Scripting Support\5.0

*for cs4: %ALLUSERSPROFILE%\Adobe\InDesign\Version 5.0\Scripting Support\6.0

*rename the file "Resources for Visual Basic.tlb" to "Resources for Visual Basic.tlb.old"

*open up a command window as administrator

*go to the indesign-Folder, in my case C:\Program Files (x86)\Adobe\Adobe InDesign CS4

*and launch indesign in the command window by typing:
indesign.exe -type

wait for the launch and then you  are good to go. with this parameter it registeres the components.
I found that solution here

A: This has just happened to me, and I landed here from Google! I managed to solve it so will add the solution here for the next time I run into it!
Simply, delete the Resources for Visual Basic.tlb file that may be at the path of C:\ProgramData\Adobe\InDesign\Version 8.0\en_GB\Scripting Support\8.0 and open InDesign as Administrator and wait for it to run.
I found the C# application to hang when I ran it next, so had to close InDesign down, and let C# open it up by itself! Example:
        Type type = Type.GetTypeFromProgID("InDesign.Application");
        Application app = (Application)Activator.CreateInstance(type);

        var doc = app.Documents.Add();

        for (var i = 0; i < 5; i++)
            doc.Pages.Add(idLocationOptions.idAtBeginning);


text:
Q: Problem with releated datatable when adding new rows to each datatable I have 2 datatable In dataset object
TransactionReasons and TransactionSubReasons.
TransactionSubReasons datatable have foreignkey IDTransactionReason from TransactionReasons.
When I add new row to TransactionReasons(for example IDTransactionReason=1) and then adding new row to TransactionSubReasons. New added row's IDTransactionReason field equals to new added row's ID(in this example 1).Until this is every thing is good.
But when I want to update my database the problem is occured.
For updating I used tableAdapterManager.UpdateAll(MYDATSET);
How can i solve this problem?
Thank for your attention!!!

A: So, what is this problem / exception exacly?
EDIT:
This exception suggest that you have an ADO.NET constraint associated with your relation (in addition to the DB constraint), but during update your child table rows don't receive the correct parent id.
Maybe the tableAdapterManager tries to update the child table first?
I suggest you try to split this into 2 operations. That is:

*

*Save the parent table (ensure in a separate program like SQL Management Studio that you got back the correct id's if they are auto generated

*Save the child table (ensure that the parent id is set properly on newly added rows
You can use a debugger to see row fields after save.
If you wanted this two operations in a transaction, have a look here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Conver "distinct on" query from Sql in Mongodb with Pymongo I am trying to convert this query from sql:
select distinct on (id13) id13, timestamp1
from oneindextwocolumnsfalse3years
where timestamp1>='2010-01-01 00:00:00' and timestamp1<='2015-01-01 00:55:00'
order by id13,timestamp1 desc

To mongodb like that:
mydb1.mongodbindextimestamp1.aggregate([

    {
        "$match": {
            "timestamp1": {"$gte": datetime.strptime("2010-01-01 00:00:00", "%Y-%m-%d %H:%M:%S"),
                          "$lte" :datetime.strptime("2015-01-01 00:55:00", "%Y-%m-%d %H:%M:%S")}
        }
    },

{
        "$group": {
            "_id":{
                "id_13":"$id13"
        },

      }
},
    {
        "$project": {
            "_id": 0,
            "id13":1,
            "timestamp1":1
        }
    },
    {"$sort": {"id13": 1,"timestamp1":-1}}

])

But it doesn't seems to work.Do you have something to suggest?I am doing something wrong but i cant find what!

A: give this pipeline a try:
db.collection.aggregate(
    [
        {
            $match: {
                timestamp: {
                    $gte: ISODate("2020-01-01"),
                    $lte: ISODate("2022-01-01")
                }
            }
        },
        {
            $group: {
                _id: "$id13", //define the grouping key
                doc: { $first: "$$ROOT" } //pick the first doc from each group
            }
        },
        {
            $replaceWith: "$doc" //promote the doc to root
        },
        {
            $project: {
                _id: 0,
                id13: "$id13",
                timestamp: "$timestamp"
            }
        },
        {
            $sort: {
                id13: 1,
                timestamp: -1
            }
        }
    ]
)

https://mongoplayground.net/p/Cwzic2cMfgd


text:
Q: Change Feed in multi-region Azure Cosmos DB I am using Cosmos DB multi-region (single region write) account. Currently it is enabled in East US and West US. The write region is West US.
The Change Feed listeners are deployed in both East US and West US. I wanted to understand, if I can specify that the listeners deployed in East US reads Change Feed from East US and listeners in West US reads Change Feed from West US. Or all the listeners will always read Change Feed from write region?

A: You can certainly make your listeners read from the closest region, which should improve your latency. You can use the PreferredLocations attribute to customize that:
var localPolicy = new ConnectionPolicy();
localPolicy.PreferredLocations.Add("East US");

// Builder initialization
.WithFeedCollection(new DocumentCollectionInfo()
{
    DatabaseName = DbName,
    Uri = new Uri(uri),
    CollectionName = feedCollection,
    MasterKey = key,
    ConnectionPolicy = localPolicy
})
.BuildAsync();


text:
Q: Interval at which the integral value may lie between
Let = $f:R \rightarrow R$ be defined as $f(x)=e^{-x} \sin x$. If $F:[0,1] \rightarrow R$ is a differentiable function such that $F(x)=\int_{0}^{x} f(t) d t$ then the value of $\int_{0}^{1}\left(F^{\prime}(x)+f(x)\right) e^{x} d x$ lies in the interval
(A) $\left[\frac{327}{360}, \frac{329}{360}\right]$
(B) $\left[\frac{330}{360}, \frac{331}{360}\right]$
(C) $\left[\frac{331}{360}, \frac{334}{360}\right]$
(D) $\left[\frac{335}{360}, \frac{336}{360}\right]$.             My approach was to take the integral to be $2f(x)e^x$ now for finding the optimum range at which the integral may lie i tried to bound the integrand with $cos\theta$ max and minimum value in that limit of integration cos1 and cos0 ,but it doesnt leads to the closest range at which options are pointing out , is there a better way to get the closest range at which it may lie ?

A: You're right that $F'=f$, but notice that $2f(x)e^x=2e^xe^{-x}\sin x=2\sin x$, so that the integral is just $2\int_0^1 \sin x\,dx=2(\cos 0 - \cos 1)$.
You will have to approximately calculate $\cos(1)$, but $1$ rad is pretty close to $60^\circ$, so it shouldn't be a problem.


text:
Q: Add custom Select2 search field into WooCommerce product data metabox I have successfully added a product search field in my edit product page, but I need to be able to clear the selection. How can I achieve this?
Alternatively: how do I manage to only be able to select 1 product if I set multiple on the select component?
My code looks like below:
add_action('woocommerce_product_data_panels', function() {
    global $post, $woocommerce;

    $product_ids = get_post_meta( $post->ID, '_stock_sync_data_ids', true );
    if( empty($product_ids) )
        $product_ids = array();
    ?>

        <?php if ( $woocommerce->version >= '3.0' ) : ?>

                <?php _e( 'Select product to sync with. (Only select 1 item)', 'woocommerce' ); ?>
                <select class="wc-product-search" style="width: 50%;" id="stock_sync_data" name="stock_sync_data[]" data-placeholder="<?php esc_attr_e( 'Search for a product…', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations">
                    <?php
                        foreach ( $product_ids as $product_id ) {
                            $product = wc_get_product( $product_id );
                            if ( is_object( $product )) {
                                echo '<option value="' . esc_attr( $product_id ) . '"' . selected( true, true, false ) . '>' . wp_kses_post( $product->get_formatted_name() ) . '</option>';
                            }
                        }
                    ?>
                </select> <?php echo wc_help_tip( __( 'Select product to syncronize stock.', 'woocommerce' ) ); ?>

        <?php endif; ?>

    <?php
});

A: You're very close with your code attempt, but I've tweaked it slightly and removed some unnecessary checks (like the WooCommerce version, as it's 3.0.. from 2017)
So you get:
// Add custom product setting tab
function filter_woocommerce_product_data_tabs( $default_tabs ) {
    $default_tabs['custom_tab'] = array(
        'label'     => __( 'Custom Tab', 'woocommerce' ),
        'target'    => 'stock_sync_data_tab',
        'priority'  => 80,
        'class'     => array()
    );

    return $default_tabs;
}
add_filter( 'woocommerce_product_data_tabs', 'filter_woocommerce_product_data_tabs', 10, 1 );

// Contents custom product setting tab
function action_woocommerce_product_data_panels() {
    global $post;

    $product_ids = get_post_meta( $post->ID, '_stock_sync_data_ids', true );
    if ( empty ( $product_ids )  ) {
        $product_ids = array();
    }
    ?>

            <?php esc_html_e( 'Select product to sync with. (Only select 1 item)', 'woocommerce' ); ?>
            <select class="wc-product-search" multiple="multiple" style="width: 50%;" id="stock_sync_data" name="stock_sync_data[]" data-placeholder="<?php esc_attr_e( 'Search for a product…', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations" data-exclude="<?php echo intval( $post->ID ); ?>">
                <?php
                foreach ( $product_ids as $product_id ) {
                    $product = wc_get_product( $product_id );
                    if ( is_object( $product ) ) {
                        echo '<option value="' . esc_attr( $product_id ) . '"' . selected( true, true, false ) . '>' . esc_html( wp_strip_all_tags( $product->get_formatted_name() ) ) . '</option>';
                    }
                }
                ?>
            </select> <?php echo wc_help_tip( __( 'Select product to syncronize stock.', 'woocommerce' ) ); // WPCS: XSS ok. ?>

    <?php
}
add_action( 'woocommerce_product_data_panels', 'action_woocommerce_product_data_panels' );

Result:

"Alternatively: how do I manage to only be able to select 1 product if I set multiple on the select component?"
Just add data-maximum-selection-length="1"

So you get:
<select class="wc-product-search" multiple="multiple" style="width: 50%;" id="stock_sync_data" name="stock_sync_data[]" data-maximum-selection-length="1"..

Related: Issue with saving value from Select2 field in WooCommerce backend


text:
Q: Error 4: Could not load file or assembly 'MySql.Data.EntityFramework or one of its dependencies. The located assembly's definition does not match I keep getting the error "Error 4: Could not load file or assembly 'MySql.Data.EntityFramework, Version=8.0.25.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)" when trying to compile my csproj. Any help would be greatly appreciated
here is my ucsdb.edmx
<?xml version="1.0" encoding="utf-8"?>

<edmx:Edmx Version="3.0" xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
  <Schema Namespace="ucsdbModel.Store" Provider="MySql.Data.MySqlClient"
ProviderManifestToken="5.6" Alias="Self"

xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator"
          xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
    <EntityType Name="Clan">
      <Key>
        <PropertyRef Name="ClanId" />
      </Key>
      <Property Name="ClanId" Type="bigint" Nullable="false" />
      <Property Name="LastUpdateTime" Type="datetime" Precision="0" Nullable="false" />
      <Property Name="Data" Type="text" Nullable="false" />
    </EntityType>
    <EntityType Name="Player">
      <Key>
        <PropertyRef Name="PlayerId" />
      </Key>
      <Property Name="PlayerId" Type="bigint" Nullable="false" />
      <Property Name="Avatar" Type="text" Nullable="false" />
      <Property Name="GameObjects" Type="text" Nullable="false" />
    </EntityType>
    <EntityContainer Name="ucsdbModelStoreContainer">
      <EntitySet Name="Clan" EntityType="Self.Clan" Schema="ucsdb" store:Type="Tables" />
      <EntitySet Name="Player" EntityType="Self.Player" Schema="ucsdb" store:Type="Tables" />
    </EntityContainer>
  </Schema>
</edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
  <Schema Namespace="ucsdbModel" Alias="Self" annotation:UseStrongSpatialTypes="false"
          xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation"
          xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
    <EntityType Name="Clan">
      <Key>
        <PropertyRef Name="ClanId" />
      </Key>
      <Property Name="ClanId" Type="Int64" Nullable="false" />
      <Property Name="LastUpdateTime" Type="DateTime" Nullable="false" />
      <Property Name="Data" Type="String" Nullable="false" MaxLength="65535"
FixedLength="false" Unicode="false" />
    </EntityType>
    <EntityType Name="Player">
      <Key>
        <PropertyRef Name="PlayerId" />
      </Key>
      <Property Name="PlayerId" Type="Int64" Nullable="false" />
      <Property Name="Avatar" Type="String" Nullable="false" MaxLength="65535"
FixedLength="false" Unicode="false" />
      <Property Name="GameObjects" Type="String" Nullable="false" MaxLength="65535"
FixedLength="false"
                Unicode="false" />
    </EntityType>
    <EntityContainer Name="ucsdbEntities" annotation:LazyLoadingEnabled="true">
      <EntitySet Name="Clan" EntityType="Self.Clan" />
      <EntitySet Name="Player" EntityType="Self.Player" />
    </EntityContainer>
  </Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
  <Mapping Space="C-S"

xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs
">
    <EntityContainerMapping
StorageEntityContainer="ucsdbModelStoreContainer"
CdmEntityContainer="ucsdbEntities">
      <EntitySetMapping Name="Clan">
        <EntityTypeMapping TypeName="ucsdbModel.Clan">
          <MappingFragment StoreEntitySet="Clan">
            <ScalarProperty Name="ClanId"
ColumnName="ClanId" />
            <ScalarProperty Name="LastUpdateTime"
ColumnName="LastUpdateTime" />
            <ScalarProperty Name="Data"
ColumnName="Data" />
          </MappingFragment>
        </EntityTypeMapping>
      </EntitySetMapping>
      <EntitySetMapping Name="Player">
        <EntityTypeMapping
TypeName="ucsdbModel.Player">
          <MappingFragment StoreEntitySet="Player">
            <ScalarProperty Name="PlayerId"
ColumnName="PlayerId" />
            <ScalarProperty Name="GameObjects"
ColumnName="GameObjects" />
            <ScalarProperty Name="Avatar"
ColumnName="Avatar" />
          </MappingFragment>
        </EntityTypeMapping>
      </EntitySetMapping>
    </EntityContainerMapping>
  </Mapping>
</edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW
HERE) -->
<Designer
xmlns="http://schemas.microsoft.com/ado/2009/11/edmx">
<Connection>
  <DesignerInfoPropertySet>
    <DesignerProperty
Name="MetadataArtifactProcessing"
Value="EmbedInOutputAssembly" />
  </DesignerInfoPropertySet>
</Connection>
<Options>
  <DesignerInfoPropertySet>
    <DesignerProperty Name="ValidateOnBuild"
Value="true" />
    <DesignerProperty Name="EnablePluralization"
Value="false" />
    <DesignerProperty Name="IncludeForeignKeysInModel"
Value="false" />
    <DesignerProperty Name="UseLegacyProvider"
Value="false" />
    <DesignerProperty Name="CodeGenerationStrategy"
Value="None" />
  </DesignerInfoPropertySet>
</Options>
<!-- Diagram content (shape and connector positions) -
->
<Diagrams></Diagrams>
</Designer>
</edmx:Edmx>

A: Need to use MySql.Data.EntityFramework.8.0.25, but the program does not have this dll file or use another version.
Click on the project's directory, right-click References and open Manage NuGet Packages.

Search for MySql.Data.EntityFramework to see Version. I hope I can help you.


text:
Q: Using Foreach to loop through children with a delay In my current project I'm trying to iterate through all the children of a parent and activate a component on each child with a time delay after each. Currently unity stops responding when this method is called, im guessing that nesting while loops in foreach loops is a bad idea? How should i be approaching this problem, I'm pretty stumped.
Any help with this would be much appreciated, this is what I'm currently doing (with little success):
float simpleTimer;

void Update()
{
    simpleTimer += Time.deltaTime;
}
public void ReelIn()
{
    foreach (Transform child in gameObject.GetComponentsInChildren<Transform>())
    {
        simpleTimer = 0;
        while (simpleTimer < 0.5f)
        {
            // do stuff here
        }
    }
}

A: You could just use a Coroutine to do that.
private void Start()
{
    StartCoroutine(ReelIn());
}

private IEnumerator ReelIn()
{
    foreach (Transform child in gameObject.GetComponentsInChildren<Transform>())
    {
        yield return new WaitForSeconds(1f);
        // do stuff here
    }
}


text:
Q: Pentaho PDI (Kettle/spoon) Meta Data Injection for text files I am interested in importing a Fixed Width file using Pentaho PDI.
I have used its main GUI tool that sets the widths graphically in Spoon.
BUT if the number of fields is very large, like a few hundred fields, it would be prone to error and take a lot of time.
In other ETL tools, I am able to import a meta-file that describes the column properties, such as name, size etc.
I see that pentaho has this thing calls Meta-Data Injection, but there is not much tutorials at all, just a couple, and either the use cases are really complex and make use of Javascript for scripting or they describe it in very abstract ways.
So hope someone who is familiar can explain my particular use case of Fixed Width files.

A: Yes,  You can use metadata injection step for applying dynamic properties like filename, fields, length datatype etc..
For that,

*

*You need to create one transformation with file input step.

*Create another transformation with the metadata injection step and where
you can add a transformation that created in step1.

*In inject Metadata tab of metadata injection step you can add length from the input step.


text:
Q: Hadoop Mapreduce Counters Can Anyone explain in detail the meaning of following File System counters?

*

*FILE_BYTES_READ

*FILE_BYTES_WRITTEN

*FILE_READ_OPS

*FILE_LARGE_READ_OPS

*FILE_WRITE_OPS

*HDFS_BYTES_READ

*HDFS_BYTES_WRITTEN

*HDFS_READ_OPS

*HDFS_LARGE_READ_OPS

*HDFS_WRITE_OPS

A: FILE_BYTES_READ is the number of bytes read by local file system. Assume all the map input data comes from HDFS, then in map phase FILE_BYTES_READ should be zero. On the other hand, the input file of reducers are data on the reduce-side local disks which are fetched from map-side disks. Therefore, FILE_BYTES_READ denotes the total bytes read by reducers.
FILE_BYTES_WRITTEN consists of two parts. The first part comes from mappers. All the mappers will spill intermediate output to disk. All the bytes that mappers write to disk will be included in FILE_BYTES_WRITTEN. The second part comes from reducers. In the shuffle phase, all the reducers will fetch intermediate data from mappers and merge and spill to reducer-side disks. All the bytes that reducers write to disk will also be included in FILE_BYTES_WRITTEN.
HDFS_BYTES_READ denotes the bytes read by mappers from HDFS when the job starts. This data includes not only the content of source file but also meta data about splits.
HDFS_BYTES_WRITTEN denotes the bytes written to HDFS. It's the number of bytes of the final output.
read operations - number of read operations such as listStatus, getFileBlockLocations, open etc.
write operations - number of write operations such as create, append, setPermission etc.
http://comphadoop.weebly.com/experiment-and-results.html


text:
Q: React-native Trim Video Is there any way to trim captured video ?
I can't find any library for that.
My environment:

*

*React-Native version: 0.36

*OS: MacOS

*Platform: Android and iOS

Thanks !.

A: Since i can't find ready library for my issue, then i write my own library
https://github.com/shahen94/react-native-video-processing
Here is it. Currenlty it's working only for iOS. In the future I'll write it for android


text:
Q: Kill a stuck process in running state I am trying to kill a du -mh command that has been stuck running for 18 hours. I have tried many kill signals kill -15, kill -2, kill -9 as root but with no luck. Are there any other techniques to kill this process?
Note this is in R running state, yet it does not appear to be responding to my kill signals.

 ps -Z 31806
 LABEL                             PID TTY      STAT   TIME COMMAND
 unconfined                      31806 ?        RN   1137:41 du

A: You could use :
kill -kill PID

This is very common command for force kill PID.


text:
Q: Ajax Load More fade effect I'm trying to make a fade effect on a load more function.
.done(function(response) {
   $('.content').append(response).hide().prependTo(".content").fadeIn("slow");
   offset += limit;
});

I'm loading my posts in content div. The first time when I click Load More it makes the fadeIn effect. When I press second time it makes the effect but to the whole .content.
My question is how to divide every load more content ?

    // with fade in effect

    // only this div with fade in effect not the whole .content

  ... etc

A: Your code is kinda of weird. I think what you actually want is just this:
.done(function(response) {
   $(response).appendTo(".content").hide().fadeIn("slow");
   offset += limit;
});

Example:
http://jsfiddle.net/0r0uv6rw/


text:
Q: Java - Storing Keypairs in KeyStore I am implementing an Hybrid Encryption project and I have generated 2 key pairs for sender and receiver keys (private and public). I have these keys in a file.
KeyPair Generation Code
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;

import Decoder.BASE64Encoder;

public class GenerateRSAKeys{

    public static void main(String[] args)
    {

        String publicKeyFilename = null;
        String privateKeyFilename = null;

        publicKeyFilename = "C:\\Users\\imjme1\\Desktop\\Work_backup\\FMS\\EPM_FILE_ENCRYPTION\\NIFT_SOLUTION\\sender_keys\\receiver_publicKey";
        privateKeyFilename = "C:\\Users\\imjme1\\Desktop\\Work_backup\\FMS\\EPM_FILE_ENCRYPTION\\NIFT_SOLUTION\\sender_keys\\receiver_privateKey";

        GenerateRSAKeys generateRSAKeys = new GenerateRSAKeys();

        generateRSAKeys.generate(publicKeyFilename, privateKeyFilename);

    }

    private void generate (String publicKeyFilename, String privateFilename){

        try {

            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

            // Create the public and private keys
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");
            BASE64Encoder b64 = new BASE64Encoder();

            SecureRandom random = createFixedRandom();
            generator.initialize(1024, random);

            KeyPair pair = generator.generateKeyPair();
            Key pubKey = pair.getPublic();
            Key privKey = pair.getPrivate();

            System.out.println("publicKey : " + b64.encode(pubKey.getEncoded()));
            System.out.println("privateKey : " + b64.encode(privKey.getEncoded()));

            BufferedWriter out = new BufferedWriter(new FileWriter(publicKeyFilename));
            out.write(b64.encode(pubKey.getEncoded()));
            out.close();

            out = new BufferedWriter(new FileWriter(privateFilename));
            out.write(b64.encode(privKey.getEncoded()));
            out.close();

        }
        catch (Exception e) {
            System.out.println(e);
        }
    }

    public static SecureRandom createFixedRandom()
    {
        return new FixedRand();
    }

    private static class FixedRand extends SecureRandom {

        MessageDigest sha;
        byte[] state;

        FixedRand() {
            try
            {
                this.sha = MessageDigest.getInstance("SHA-1");
                this.state = sha.digest();
            }
            catch (NoSuchAlgorithmException e)
            {
                throw new RuntimeException("can't find SHA-1!");
            }
        }

        public void nextBytes(byte[] bytes){

            int    off = 0;

            sha.update(state);

            while (off < bytes.length)
            {
                state = sha.digest();

                if (bytes.length - off > state.length)
                {
                    System.arraycopy(state, 0, bytes, off, state.length);
                }
                else
                {
                    System.arraycopy(state, 0, bytes, off, bytes.length - off);
                }

                off += state.length;

                sha.update(state);
            }
        }
    }

}

Now, I need to secure these keys (probably not on any disk directly).
I have searched for this case on the internet; saving keys into key stores is the way to secure keys and use the same keystore when reading keys for the use in encryption and decryption.
Can someone suggest me how to save public and private key in key store and how to read it in java?

A: The Java KeyStore API (and underlying providers) does not support storing a keypair -- that is, a privatekey and publickey (which can then be used for publickey operations like encrypt and verify). It does support storing a privatekey and a certificate chain for the publickey. The certificate chain can consist of only one certificate, especially if that certificate is a self-signed certificate (which by definition is a chain by itself). That is exactly what commandline keytool -genkeypair does: it generates a keypair and stores the privatekey plus a self-signed certificate for the publickey in the (specified or defaulted) keystore file.
If you were using only 'standard' JRE, creating a self-signed (or other) certificate in code is not very easy.
However, if you have BouncyCastle added, as you obviously do or the code you posted wouldn't work, that has numerous applicable capabilities. For a simple example of generating a cert with only bcprov (the old, deprecated X509V3CertificateGenerator) see my JAVA API to create a keystore and attaching a csr and keypair to it -- but do as I recommended there but didn't show: don't create the unneeded CSR first, instead create the cert using the desired name and publickey.
Better, if you also have or can get bcpkix, use X509v3CertificateBuilder. See examples at Self signed X509 Certificate with Bouncy Castle in Java and Generating X509 Certificate using Bouncy Castle Java .
For writing out, and reading back in, a keystore file containing this data, just see the Javadoc linked above. Note Java traditionally defaulted to JKS-format files, and you will find many older answers here and elsewhere on the web which assume that, but since Java 9 in 2017 it defaults to PKCS12-format, which is not only standard and thus (mostly) interoperable but also more secure (uses a much better PBKDF algorithm).
However, your code uses a completely bogus random generator, and as a result generates the same keypair every time. Given this, there is no real need to store it, since you can always re-generate it any time you want. In fact, there is no benefit to even having this keypairs since it provides no security at all.


text:
Q: Closing Event and Catel's MessageService, can't Cancel I'm using an ExitCommand to close the application from Menu->Exit, I've tried to implement the same exit behavior when user click on X
I've defined this in my XAML
<catel:Window x:Class="IF.Tesoreria.Client.WPF.Views.ShellView"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:catel="http://catel.codeplex.com"
          xmlns:view="clr-namespace:IF.Tesoreria.Client.WPF.Views"
          xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
          xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
          Icon="../Media/threasure.gif" Height="500" Width="800" >
<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
        <catel:EventToCommand Command="{Binding ExitCommand}"  PassEventArgsToCommand="True"/>
    </i:EventTrigger>
</i:Interaction.Triggers>
<Grid>
<!--omiss-->

And in the ViewModel I've used the following command
   public Command<CancelEventArgs> ExitCommand { get; private set; }

   #region CTor
    public ShellViewModel( IDynamicContainer dynamicContainer, IViewModelFactory viewModelFactory)
    {
        this.dynamicContainer = dynamicContainer;
        this.viewModelFactory = viewModelFactory;

        ShowInfoCommand = new Command(ShowInfoCommandExecute);
        ExitCommand = new Command<CancelEventArgs>(OnExitCommandExecute);
    }
    #endregion

private void OnExitCommandExecute(CancelEventArgs args)
    {
        var res = MessageBox.Show(Properties.Resources.DIALOG_EXIT, Properties.Resources.DIALOG_EXIT_CAPTION,MessageBoxButton.YesNo);
        //var res = messageService.Show(Properties.Resources.DIALOG_EXIT, Properties.Resources.DIALOG_EXIT_CAPTION,
        //      MessageButton.YesNo, MessageImage.Question);

        if (res == MessageBoxResult.Yes)
        {
            ICloseApplicationService closeApplicationService = this.GetServiceLocator().ResolveType<ICloseApplicationService>();
            closeApplicationService.Close();
        }
        else
        {
            args.Cancel = true;
        }
    }

If I use the MessageBox I'm able to cancel the closing event (setting args.Cancel = true). Otherwise if I use the IMessageService, when I get the result from Show it's too late
What am I doing wrong?
Thanks

A: The IMessageService in Catel is async. We are considering to implement this in a different way. In the meantime, use INavigationService.ClosingApplication event.


text:
Q: Combining 2 Tables to create a new table I have problem figuring out the SQL Script for the following :-
I have 2 tables -

and I would like to combine the 2 tables and create a new table like this: -

Any help will be very much appreciated.

A: One way to approach this is to CROSS JOIN the tables and go from there. Let's create a script to experiment with your data to see what we get.
DECLARE @JobCharges AS TABLE (
    JobNo VARCHAR(10) NOT NULL,
    Column1 INT NOT NULL,
    Column2 INT NOT NULL,
    Column3 INT NOT NULL,
    Column4 INT NOT NULL
);

INSERT INTO @JobCharges(JobNo,Column1,Column2,Column3,Column4)
VALUES
('Job01',10,20,0,50), ('Job02',60,0,70,100);

DECLARE @ModelHours AS TABLE(
    ColumnPos VARCHAR(10) NOT NULL,
    Model VARCHAR(10) NOT NULL,
    [Hours] DECIMAL(5,2) NOT NULL
);

INSERT INTO @ModelHours(ColumnPos,Model,[Hours])
VALUES
('Column1', 'Toyota', 0.5), ('Column2', 'Nissan', 0.6),
('Column3', 'Audi', 0.7), ('Column4', 'BMW', 0.8);

SELECT job.JobNo,
           job.Column1,
           job.Column2,
           job.Column3,
           job.Column4,
           hr.ColumnPos,
           hr.Model,
           hr.[Hours]
FROM @JobCharges AS job
CROSS JOIN @ModelHours AS hr;

The result of the CROSS JOIN is this:

JobNo
Column1
Column2
Column3
Column4
ColumnPos
Model
Hours

Job01
10
20
0
50
Column1
Toyota
0.50

Job01
10
20
0
50
Column2
Nissan
0.60

Job01
10
20
0
50
Column3
Audi
0.70

Job01
10
20
0
50
Column4
BMW
0.80

Job02
60
0
70
100
Column1
Toyota
0.50

Job02
60
0
70
100
Column2
Nissan
0.60

Job02
60
0
70
100
Column3
Audi
0.70

Job02
60
0
70
100
Column4
BMW
0.80

When the data looks like this, it is easy to see how to get what you want. You can use the value of ColumnPos to choose which column you want to display. So I will set up a common table expression to use the CROSS JOIN as a subquery (you could just do a subquery if you wanted), and then use a CASE statement to choose the column value you want. Also, you seemed to ignore rows where Charges were zero, so I filtered those out with a WHERE clause.
;WITH crossJoin
AS (SELECT job.JobNo,
           job.Column1,
           job.Column2,
           job.Column3,
           job.Column4,
           hr.ColumnPos,
           hr.Model,
           hr.[Hours]
    FROM @JobCharges AS job
        CROSS JOIN @ModelHours AS hr)
SELECT crossJoin.JobNo,
       crossJoin.Model,
       CASE
           WHEN crossJoin.ColumnPos = 'Column1' THEN
               crossJoin.Column1
           WHEN crossJoin.ColumnPos = 'Column2' THEN
               crossJoin.Column2
           WHEN crossJoin.ColumnPos = 'Column3' THEN
               crossJoin.Column3
           ELSE
               crossJoin.Column4
       END AS [Charges],
       crossJoin.[Hours]
FROM crossJoin
WHERE CASE
          WHEN crossJoin.ColumnPos = 'Column1' THEN
              crossJoin.Column1
          WHEN crossJoin.ColumnPos = 'Column2' THEN
              crossJoin.Column2
          WHEN crossJoin.ColumnPos = 'Column3' THEN
              crossJoin.Column3
          ELSE
              crossJoin.Column4
      END > 0
ORDER BY crossJoin.JobNo;

The result of this query is what you want.

JobNo
Model
Charges
Hours

Job01
Toyota
10
0.50

Job01
Nissan
20
0.60

Job01
BMW
50
0.80

Job02
BMW
100
0.80

Job02
Audi
70
0.70

Job02
Toyota
60
0.50


text:
Q: How can I keep my Azure WebJob running without "Always On" I have a continous webjob associated with a website and I am running that website on the Shared mode. I don't want to go to Always On option as there is no real need for my application. I only want to process the message when the calls are made to my website.
My issue is that the job keeps stopping after few minutes even though I am continuously calling a dummy keep alive method on my website at every 5 minute that posts a message to the queue that is monitored by that webjob.
My webjob is a simple console application built using the WebJob SDK that has a code like this
JobHost host = new JobHost(new JobHostConfiguration(storageConnictionSttring));
host.RunAndBlock();

and the message processing function looks like below:
public static void ProcessKeepAliveMessages([QueueTrigger("keepalive")] KeepAliveTrigger message)
{
    Console.WriteLine("Keep Alive message called on :{0}", message.MessageTime);
}

The message log for the job basically says says
[03/05/2015 18:51:02 > 4660f6: SYS INFO] WebJob is stopping due to website shutting down

I don't mind if that happen this way, but when the website starts with the next call to keep alive, the webjob is not started. All the messages are queued till I go to the management dashboard or the SCM portal as shown below
https://mysite.scm.azurewebsites.net/api/continuouswebjobs

I can see the status like this:
[{"status":"Starting","detailed_status":"4660f6 - Starting\r\n","log_url":"https://mysite.scm.azurewebsites.net/vfs/data/jobs/continuous/WebJobs/job_log.txt","name":"WebJobs","run_command":"mysite.WebJobs.exe","url":"https://mysite.scm.azurewebsites.net/api/continuouswebjobs/WebJobs","extra_info_url":"https://mysite.scm.azurewebsites.net/azurejobs/#/jobs/continuous/WebJobs","type":"continuous","error":null,"using_sdk":true,"settings":{}}]

I would really appreciate if someone can help me understand what is going wrong here.

A: I've run into a similar problem. I have a website (shared mode) and an associated webjob (continuous type). Looking at webjob logs, I found that the job enters stopped state after about 15 min. of inactivity and stops reacting to trigger messages. It seems contradictory to the concept of continuous job concept but, apparently, to get it running truly continuously you have to subscribe to a paid website. You get what you pay for...
That said, my website needs to be used only about every few days and running in a shared mode makes perfect sense. I don't mind that the site needs a bit extra time to get started - as long as it restarts automatically. The problem with the webjob is that once stopped it won't restart by itself. So, my goal was to restart it with the website.
I have noticed that a mere look at the webjob from Azure Management Portal starts it. Following this line of thinking, I have found that fetching webjob properties is enough to switch it to the running state. The only trick is how to fetch the properties programmatically, so that restarting the website will also restart the webjob.
 Because the call to fetch webjob properties must be authenticated, the first step is to go to Azure Management Portal and download the website publishing profile. In the publishing profile you can find the authentication credentials: username (usually $<website_name>) and userPWD (hash of the password). Copy them down.
Here is a function that will get webjob properties and wake it up (if not yet running):
class Program
{
    static void Main(string[] args)
    {
        string websiteName = "<website_name>";
        string webjobName = "<webjob_name>";
        string userName = "<from_publishing_profile>";
        string userPWD = "<from_publishing_profile>";
        string webjobUrl = string.Format("https://{0}.scm.azurewebsites.net/api/continuouswebjobs/{1}", websiteName, webjobName);
        var result = GetWebjobState(webjobUrl, userName, userPWD);
        Console.WriteLine(result);
        Console.ReadKey(true);
    }

    private static JObject GetWebjobState(string webjobUrl, string userName, string userPWD)
    {
        HttpClient client = new HttpClient();
        string auth = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ':' + userPWD));
        client.DefaultRequestHeaders.Add("authorization", auth);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var data = client.GetStringAsync(webjobUrl).Result;
        var result = JsonConvert.DeserializeObject(data) as JObject;
        return result;
    }
}

You can use a similar function to get all webjobs in your website (use endpoint https://<website_name>.scm.azurewebsites.net/api/webjobs). You may also look at the returned JObject to verify the actual state of the webjob and other properties.

A: If you want the WebJob to not stop you need to make sure your scm site is alive.
So the keep-alive requests should go to https://sitename.scm.azurewebsites.net and these requests need to be authenticated (basic auth using your deployment credentials).


text:
Q: Merge multiple rows of dataframe together if followed by an empty row in R I have the following dataframe:
location <- "https://www.mofa.go.jp/announce/info/conferment/pdfs/2013_sp.pdf"
out <- tabulizer::extract_tables(location)
final <- do.call(rbind, out)
final <- as.data.frame(final) %>%
  janitor::row_to_names(row_number = 2) %>%
  janitor::clean_names()

Unfortunately, due to extraction issues with tabulizer::extract_table (see this thread), the dataframe is unclean.
A data point spans over multiple rows, followed by empty rows (rows 20 and 26 in the screenshot):

Is it possible to automatically merge mutliple rows together into a single row if they have an empty row afterwards (or if there is no row afterwards, as in the last row of the dataframe)?
In other words, rows 13-19 should form a single row, and rows 21-25 should also serve as a single row. The columns are correct.
I would be grateful for your help!

A: Data is messy because you can have empty rows between same group (rows 126 and 127). I've defined starting of a group when decoration != "". It would be easier to define groups with nationality because it has ( in it (problem are people from Taiwan).
library(tidyverse)
library(data.table)

tidyPage <- function(dt){

  setDT(dt)
  dt <- dt[, map(.SD, as.character)]
  dt[, flag := !decoration == ""]
  dt <- dt[which.max(flag):.N]
  dt[, group := rleid(flag)]
  dt[flag == TRUE, flag := c(TRUE, rep(FALSE, .N - 1)), by = group]
  dt[, group := cumsum(flag)]

  split(dt, dt$group) %>%
    map_dfr(~map_chr(select(.x, -flag, -group), str_c, collapse = " ")) %>%
    mutate(across(where(is.character), str_squish))
}

location <- "https://www.mofa.go.jp/announce/info/conferment/pdfs/2013_sp.pdf"
out <- tabulizer::extract_tables(location) %>%
  map(~
    as.data.frame(.x) %>%
      janitor::row_to_names(row_number = 2) %>%
      janitor::clean_names()
  ) %>%
  map_dfr(tidyPage)


text:
Q: Get Mouse State without access to MouseEventArgs? I have a form with many, many controls. I need to detect if the mouse is down or if it's up. Most of the time, I don't have MouseEventArgs.
Is there a quick and easy way to tell if the mouse is down without mouseEventArgs?
Is there an alternative, or is something like this the only way?:
foreach (Control c in this.Controls)
{
    c.MouseUp += new MouseEventHandler(globalMouseUp);
    c.MouseDown += new MouseEventHandler(globalMouseDown);
}

bool isMouseUp = true;

private void globalMouseDown(object sender, MouseEventArgs e)
{
    isMouseUp = false;
}

private void globalMouseUp(object sender, MouseEventArgs e)
{
    isMouseUp = true;
}

A: ChecK Control.MouseButtons static property:
if (Control.MouseButtons == MouseButtons.Left)
{
}

A: You can try checking with a timer:
private void timer1_Tick(object sender, EventArgs e) {
  this.Text = "Mouse Is " + (Control.MouseButtons == MouseButtons.Left);
}


text:
Q: Calculate the difference in sums (revenue) between two groups in A/B test Requests for a quote come in completely independently, and our system assigns each to either A or B randomly (50/50% split). B has slightly different logic, that is what we are testing.
Quotes usually aren't purchased (let's call it a \$0 purchase), but when they are it's usually for < $2 (this happens around 0.01% of the time).
I would like to be able to calculate for our experiment how much Group B's new logic changed (if at all) the revenue (sum of the purchase prices).
I am not a stats expert (please, ELI5!), and so I'm not sure about how to set up the hypothesis testing / calculations.
Purchase price is not normally distributed, so perhaps a non-parametric Mann-Whitney is best, but scipy really only gives a way to calculate the p-value. I care about the p-value, but I'm really more curious about the effect difference.
Here's a histogram of the purchase prices (with no purchase as \$0):

Practically, I'm looking for a straightforward way to do this in Python.

Attempt with a t-test as suggested:
from scipy import stats

df = get_data_from_db(experiment_name='blah')

# two columns: price, name of group
a = df[(df.price > 0) & (df.name == 'A')].price.values
b = df[(df.price > 0) & (df.name == 'B')].price.values

# probability of sale (non-zeros only!)
p_a = len(a) / len(df)
p_b = len(b) / len(df)

statistic, pvalue = stats.ttest_ind(a, b, equal_var=False)

print(f'N={len(df)}, N_a={len(a)}, N_b={len(b)}, p_a={round(p_a, 5)}, p_b={round(p_b, 5)}')
print(f'statistic={round(statistic, 2)}, pvalue={round(pvalue, 5)}')

output:
N=1894166, N_a=116, N_b=178, p_a=6e-05, p_b=9e-05
statistic=-3.09, pvalue=0.0022

A: I wasn't happy with my old answer.  Here is a better one in my opinion.

I would like to be able to calculate for our experiment how much Group B's new logic changed (if at all) the revenue (sum of the purchase prices).

Ignoring the \$0 purchases, let the $i^{th}$ customer's purchase in group $X$ be denoted by $y_{x,i}$.  The revenue from group $X$ is then $\sum_i y_{x,i} = R_x$.  If you want to know how much group B's logic changed the revenue, then you should examine the expected revenue per 100,000 purchasing customers (or some other number).
We have theorems about how the revenue (sums of iid random variables) are distributed. In short, the revenue per N customers is
$$R_x \sim \mathcal{N}(N\mu_x, N\sigma^2_x)$$
Where $\mu_x$ and $\sigma^2_x$ are the mean and variance of $y_{x,i}$.
The distribution of the differences in revenue is then
$$R_B - R_A \sim \mathcal{N}(N\mu_B - N\mu_a, N\sigma^2_B + N \sigma^2_A)$$
From here, you can compute a 95% confidence interval for the difference in revenue.  You don't have access to the $\mu$'s and $\sigma$'s, but you can estimate them from your data. Here is some python code simulating and verifying these results
import numpy as np
from scipy.stats import gamma, norm
import matplotlib.pyplot as plt

N = 1000 #1000 customers
n_sims= 1000 #Number of simulations

# Difference in means of 1 unit

groupA = gamma(10)
A = groupA.rvs(size = (n_sims, N))

groupB = gamma(11)
B = groupB.rvs(size = (n_sims, N))

# Distrbution of differences in revenue
D = B.sum(axis=1) - A.sum(axis=1)

# Now, plot on top the normal distribution
fig, ax = plt.subplots(dpi = 120)
plt.hist(D, edgecolor = 'white', bins = 20, density = True)

x = np.linspace(600,1400)
true_dens = norm(loc = N*groupB.mean() - N*groupA.mean(), scale = np.sqrt(N*groupA.var() + N*groupB.var()))
est_dens = norm(loc = D.mean(), scale = D.std())
ax.plot(x, true_dens.pdf(x), color = 'red', label = 'True Dist')
ax.plot(x, est_dens.pdf(x), color = 'C1', label = 'Estimated Dist')
plt.legend()
plt.title('Difference in Revenue')
plt.xlabel('Revenue from B - Revenue from A')

In this example, I have simulated your experiment 1000 times.  Customer purchase amounts are drawn from a gamma distrubition, and the mean of this distribution changes with the group.  Each time, the difference in revenue is computed and plotted as a histogram.
In this simulation, we would expect group B to yield an additional $1000 in revenue over group A per 1000 customers. That makes sense; the real difference between groups is 1 unit.  However, because of the uncertainty in the data, it would be best to instead give a confidence interval rather than a single number.  Luckily, this can be done by computing...
est_dens.ppf([0.025, 0.975])

I still get the feeling this isn't exactly what you want, so just let me know if this helps at all.


text:
Q: How to add a specific meta tag to a PHP page for Wordpress? Can anyone please help me or point me at the right direction?
I'm trying to add a meta tag to a PHP page in a single wordpress page but just wondering if I'm doing it correctly?
 <meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript">

Where should I put that code into?
Under the get header part?
The other pages on the website somehow already got the meta tag inserted automatically via Yeost SEO plugin, but it's just one page that cannot be added with meta tag via Wordpress panel.
Dev team mentioned that it has to be added manually in the .php page but I'm lost right now on what to do.


text:
Q: Is it possible to save a generated image in Codename One? My question is related to  this previous question. What I want to achieve is to stack images (they have transparency), write a string on top, and save the photomontage / photocollage with full resolution.
    @Override
protected void beforeMain(Form f) {

    Image photoBase = fetchResourceFile().getImage("Voiture_4_3.jpg");
    Image watermark = fetchResourceFile().getImage("Watermark.png");

    f.setLayout(new LayeredLayout());
    final Label drawing = new Label();
    f.addComponent(drawing);

    // Image mutable dans laquelle on va dessiner (fond blanc)
    Image mutableImage = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
    drawing.getUnselectedStyle().setBgImage(mutableImage);
    drawing.getUnselectedStyle().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FIT);

    // Paint all the stuff
    paints(mutableImage.getGraphics(), photoBase, watermark, photoBase.getWidth(), photoBase.getHeight());

    // Save the collage
    Image screenshot = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
    f.revalidate();
    f.setVisible(true);
    drawing.paintComponent(screenshot.getGraphics(), true);

    String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
    try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
        ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
    } catch(IOException err) {
        err.printStackTrace();
    }

}

public void paints(Graphics g, Image background, Image watermark, int width, int height) {

    g.drawImage(background, 0, 0);
    g.drawImage(watermark, 0, 0);
    g.setColor(0xFF0000);

    // Upper left corner
    g.fillRect(0, 0, 10, 10);

    // Lower right corner
    g.setColor(0x00FF00);
    g.fillRect(width - 10, height - 10, 10, 10);

    g.setColor(0xFF0000);
    Font f = Font.createTrueTypeFont("Geometos", "Geometos.ttf").derive(220, Font.STYLE_BOLD);
    g.setFont(f);
    // Draw a string right below the M from Mercedes on the car windscreen (measured in Gimp)
    g.drawString("HelloWorld",
            (int) (848 ),
            (int) (610)
            );

}

This is the saved screenshot I get if I use the Iphone6 skin  (the payload image is smaller than the original one and is centered). If I use the Xoom skin this is what I get  (the payload image is still smaller than the original image but it has moved to the left).
So to sum it all up : why is the saved screenshot with Xoom skin different from the one I get with Iphone skin ? Is there anyway to directly save the  graphics on which I paint in  the paints method so that the saved image would have the original dimensions ?
Thanks a lot to anyone that could help me :-)!
Cheers,

A: You can save an image in Codename one using the ImageIO class. Notice that you can draw a container hierarchy into a mutable image using the paintComponent(Graphics) method.
You can do both approaches with draw image on mutable or via layouts. Personally I always prefer layouts as I like the abstraction but I wouldn't say the mutable image approach is right/wrong.
Notice that if you change/repaint a lot then mutable images are slower (this will not be noticeable for regular code or on the simulator) as they are forced to use the software renderer and can't use the GPU fully.
In the previous question it seems you placed the image with a "FIT" style which naturally drew it smaller than the containing container and then drew the image on top of it manually... This is problematic.
One solution is to draw everything manually but then you will need to do the "fit" aspect of drawing yourself. If you use layouts you should position everything based on the layouts including your drawing/text.


text:
Q: Defining a global variable to run in a defined PYTHON So i'm writing an RPG text based game for a school assignment although i'm having troubles with making a global variable for the player health as i have written the battle logic within a defined function. At the moment, each time the function plays through it sets the playerHealth to 100 although i want it to make the playerHealth equal to the last time it was modified. For example: if i went into a battle and lost 10 health making my health 90, the next time i battle it would be set to 90 health.
def battle():
  playerHealth = 100
  enemyHealth = 20

  while enemyHealth > 0:

  attack = input('Melee or Ranged Attack?\n> ').lower()
  if attack[0] == 'm':
      chance = random.randint(0,2)
      if chance == 0:
          print('***********')
          print('You missed!')
          print('***********')
          print('You receive 4 damage')
          playerHealth -= 4
          print('')
          print('Player Health = ' + str(playerHealth))

      else:
          print('You hit the enemy, also causing damage to yourself')
          print('Enemy receives 3 damage')
          print('Player receives 1 damage')
          enemyHealth -= 4
          playerHealth -= 1
          print('')
          print('Enemy Health = ' + str(enemyHealth))
          print('Player Health = ' + str(playerHealth))

  elif attack[0] == 'r':
      chance = random.randint(0,2)
      if chance == 0:
          print('***********')
          print('You missed!')
          print('***********')
          print('The enemy attacks you causing 3 damage')
          playerHealth -= 3
          print('')
          print('Player Health = ' + str(playerHealth))

      else:
          print('-----------')
          print('Direct hit!')
          print('-----------')
          print('Enemy receives 2 damage')
          enemyHealth -= 2
          print('')
          print('Enemy Health = ' + str(enemyHealth))

print('---------------------')
print('You killed the enemy!')
print('---------------------')

So then afterwards i would use:
if "enemy" in deadZone[currentArea1]:
  battle()

A: def battle(player_health, enemy_health):
    ...
    ...
    return player_health, enemy_health

player_health, enemy_health = battle(100, 20)

A: Initialize it outside the function, pass it to the function, and have the function return it.
def battle(playerHealth):
    ...
    return playerHealth

...

if "enemy" in deadZone[currentArea1]:
    playerHealth = battle(playerHealth)


text:
Q: Upper and Lower Darboux integral of a piecewise function $f(x)=x$ and $f(x)=0$. Let $0<a<b$. Find the upper and lower Darboux integrals for the function $$f(x)=x$$ if $x\in[a,b]\cap\mathbb{Q}$ and $$f(x)=0$$ if $x\in[a,b]-\mathbb{Q}$.
I am so lost on this problem. Any hints or solutions are greatly appreciated.

A: Any interval in any subdivision of $[a,b]$ must contain a rational and irrational point, since the intervals are not singletons nor empty. This is because the irrationals and rationals are both dense in $\mathbb{R}$. We then have that the supremum of $f$ on any non-empty, non-singleton closed interval $[x,y]$ is $\sup[x,y] = y$ and the infimum of $f$ on any interval is $0$.
So the upper sum of any uniform partition $P_n:a=t_0< t_1< ...<t_n=b$, with $t_k = a+\frac{k(b-a)}{n}$ must be $$U(f,P_n) =\sum_{k=1}^{n} (t_k-t_{k-1}) t_k=\sum^{n}_{k=1} (\frac{b-a}{n}) (t_k)=\sum^{n}_{k=1} (\frac{b-a}{n})(a+\frac{k(b-a)}{n}) = \sum^{n}_{k=1} (a(\frac{b-a}{n})+(\frac{b-a}{n})\frac{k(b-a)}{n}) = a(b-a) + \frac{(b-a)^2}{n^2}\sum^{n}_{k=1} k $$
$$= a(b-a) + \frac{(b-a)^2}{n^2}\frac{1}{2} (n)(n+1)= a(b-a) + \frac{1}{2} (b-a)^2(1+\frac{1}{n})  $$
since the supremum of any interval must be on the right hand side.
Now take the infimum of all the upper sums of the uniform partitions, and you'll note that it is, $$a(b-a) + \frac{1}{2} (b-a)^2(1) = ab-a^2 + \frac{1}{2}b^2-ab+\frac{1}{2}a^2 = \frac{1}{2}b^2-\frac{1}{2}a^2$$
So the upper integral is at most $$\frac{1}{2}b^2-\frac{1}{2}a^2$$.
If $Q = \{q_0,...,q_N\}$ is any partition of $[a,b]$, then
$$U(f, Q) = \sum_{i=1}^N q_i (q_i-q_{i-1}) =  \sum_{i=1}^N q_i^2 -\sum_{i=1}^Nq_i q_{i-1} \geq \sum_{i=1}^N q_i^2 - \frac{1}{2} \sum_{i=1}^N (q_i^2 + q_{i-1}^2) $$$$= \frac{1}{2} \sum_{i=1}^N (q_i^2 - q_{i-1}^2) =\frac{1}{2}(\sum_{i=1}^N q_i^2 - \sum_{i=1}^N q_{i-1}^2) = \frac{1}{2}(b^2-a^2)$$
The inequality is because:
$$(x-y)^2 \geq 0 \implies x^2-2xy+y^2 \geq 0 \implies -2xy \geq -x^2-y^2 $$$$\implies 2xy \leq x^2 +y^2 \implies xy \leq \frac{1}{2}(x^2+y^2)$$
The last equality is because the squares cancel (telescoping sum) for all $q_i \neq a,b$.
So the upper integral is at least $\frac{1}{2}(b^2-a^2)$ since it is the greatest lower bound of the upper sums of all the partitions.
Hence the upper integral is  $\frac{1}{2}(b^2-a^2)$.
The lower sum of any partition of $[a,b]$ must be $0$ as the infimum on any of the subintervals is $0$.
So the supremum of the lower sums over any partition must be $0$. Hence the lower integral is $0$.
Does that get you started?

A: Let us analyse the upper sum: $U_{f,P} = \sum_{i=1}^n(x_i - x_{i-1})M_i$ where $M_i = \sup_{x\in[x_{i-1}, x_i]} f(x)$. So, we have to look for a $\sup$ for any interval $[x_{i-1}, x_i]$. Since $\mathbb{Q}$ is dense in $\mathbb{R}$, any interval contains rational numbers, and hence, $\sup f(x)$ is equal to $x_i$ (even if $x_i$ is irrational, there is a sequence of rational numbers with $x_i$ as its limit). Looks a lot like a Riemann sum for a function $f(x) = x$. So, your upper integral should look like $\frac{b^2 - a^2}{2}$.
With the same reasoning, you find out that the lower integral would be $0$.


text:
Q: Right Sidebar appears below content - Drupal Zen Subtheme I am trying to create a new theme for my Drupal site. I am working with Drupal 6.20 and Zen's latest version.
I have made quite a few changes to the layout of the theme and now my right sidebar appears below the main content.
You can see the problem here (not dynamically generated - saved from a local copy) : http://testcheckchecktest.whackk.com/grab/test1.html
Most of the layout CSS can be found here : http://testcheckchecktest.whackk.com/grab/test1_files/layout-fixed.css
CSS that might be the problem :
.sidebar-second #content {
  width: 800px;
  margin-left: 0; /* LTR */
  margin-right: -800px; /* LTR */ /* Negative value of #content's width + left margin. */
}

.region-sidebar-second {
  float: left; /* LTR */
  width: 180px;
  margin-left: 800px; /* LTR */ /* Width of content + sidebar-first. */
  margin-right: -980px; /* LTR */ /* Negative value of .region-sidebar-second's width + left margin. */
  padding: 0; /* DO NOT CHANGE. Add padding or margin to .region-sidebar-second .section. */
}

.region-sidebar-second .section {
  margin: 0 0 0 0px; /* LTR */
  padding: 0;
}

Please, let me know if you can figure out what the problem is..

A: Sometimes it depends where the sidebar is placed within the HTML code. I would recommend floating both the sidebar as well as the content, this could help.
Best of luck!


text:
Q: Related field in biblatex : page I would like to use the "related" field provided by the biblatex package.
But as I read the documentation, it implies to use only a entry key, and I would like a part of a book, not all the book.
So I would like to precise page (because I could use the book with different pages related to different entries).
What I expect to have as output will be :
Author 1, Title 1, (meta datas)... see Author 2, Title 2, (meta datas), p. xxx ; Author 3, Title 3 (meta datas) ... p. yyy etc.
(In fact, it will quite more complexe, but the idea is the same : link to precise page of other book)
I was thinking to do something like this :
@book{key,
     ...}
@book{key2,
     crossref={key},
     pages={xxx}
}
@book{key3,
     ...}
@book{key4,
     crossref={key2},
     pages={yyyy}
}
@book{key5,
     related={key2, key5}
...
}

But I would like to avoid "false" subentry.
Do you have any idea ?

A: Ok, I found a method, which I present it, in a simplified way (because it's a integreated in a more global project. For full details, see https://github.com/maieul/biblatex-manuscripts-philology/commit/cc76e0cd0a7d6952d407fa83229e1baeac89a27d.)
First, in the .bib file, create field "catalog", which will contain text formated as if it was arguments for cites commands:
@type{key,
  catalog={[xx]{key1}[yy]{key2}}
  }

In your .dbx file (see the handbook), say you want to have new field catalog:
\DeclareDatamodelFields[type=field,datatype=literal]{catalog}
\DeclareDatamodelEntryfields{catalog}

And in bbx file, say how you want to construct the final field
\DeclareStyleSourcemap{
    \maps[datatype=bibtex]{
        \map[overwrite]{
        \step[fieldsource=catalog,final]
        \step[fieldset=catalog,fieldvalue={\cites}]
        \step[origfieldval,fieldset=catalog,append]
        }
  }
}

So the field will be automatically transformed to
\cites[xx]{key1}[yy]{key2}

So, finally, call the field in finentry macro:
\renewbibmacro{\usebibmacro{catalog}\finentry} % new finentry macro
\newbibmacro{catalog}{%
\ifbibliography{}% print the catalogs only in final bibliography
    {\finentrypunct\setunit{}\par\unspace\printfield{catalog}}}%Check the punct, add a par break
    {}%
}
\DeclareFieldFormat{catalog}{% Format of the field
  \textbf{Cat.} % Should be more clean : with language string. See my full code
  #1%
}

A: I checked all the options of the related field. It seems there is no way of adding informations such as pages after the related reference.
But, there is a workaround : you could set the relatedstring in such way this information will be provided. The biblatex-examples.bib file provided with the package shows such examples.
Here is a MWE:
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{filecontents}
\usepackage[style=verbose,hyperref]{biblatex}
\renewcommand*{\newunitpunct}{\addcomma\space}
\bibliography{biblio}
\begin{filecontents}{biblio.bib}
}
@Article{doody,
  author       = {Doody, Terrence},
  title        = {Hemingway's Style and Jake's Narration},
  year         = 1974,
  volume       = 4,
  number       = 3,
  pages        = {212-225},
  hyphenation  = {american},
  related      = {matuz:doody},
%  relatedstring= {\autocap{e}xcerpt in}, % this was the original example with no page mention.
  relatedstring= {cited p.42 in :}, % but you could rephrase the field like this in this line.
  journal      = {The Journal of Narrative Technique},
  annotation   = {An \texttt{article} entry cited as an excerpt from a
                  \texttt{collection} entry. Note the format of the
                  \texttt{related} and \texttt{relatedstring} fields},
}

@Collection{matuz:doody,
  editor       = {Matuz, Roger},
  title        = {Contemporary Literary Criticism},
  year         = 1990,
  volume       = 61,
  publisher    = {Gale},
  location     = {Detroit},
  pages        = {204-208},
  hyphenation  = {american},
  annotation   = {A \texttt{collection} entry providing the excerpt information
                  for the \texttt{doody} entry. Note the format of the
                  \texttt{pages} field},
}
\end{filecontents}
\begin{document}

\noindent\cite{matuz:doody}\\
\cite{doody}

\printbibliography
\end{document}

If you absolutely need a solution with the page after the related references, I am afraid you will have to get your hands dirty.

A: Advertisement : This is not a solution but a lead to a possible one. I have not enough place to explain it in a comment, so I create (improperly) an answer.

There is perhaps a solution using a biber feature. I discover this feature in a TeX.SE post (see the accepted answer) which lists advantages of biber. One of these features is :

Very flexible configuration file "sourcemap" option which can be used
to change the .bib data as it is read by Biber, without changing the
actual data source itself. You can use this to do all sorts of things
like drop certain fields, add fields, conditionally drop/add fields,
change fields using full Perl 5.14 regular expressions (see Biber
manual section 3.1.1).
This last feature is particularly interesting for you as you can
potentially map your pure BibTeX .bib files into the biblatex model on
the fly as Biber reads them but without altering the files. It's also
very useful for dropping fields like abstract which often cause
trouble due to LaTeX reserved characters.

The author refereed to section 3.1.1 of biber manual but it is in fact the section 3.1.2 (entitled "The sourcemap option") which is relevant :

The datasource drivers implement a mapping from datasource entrytypes
and fields into the Biblatex data model. If you want to override or
augment the driver mappings you can use the sourcemap option which
makes it possible to, for example, have a datasource with non-standard
entrytypes or fields and to have these automatically mapped into other
entrytypes/fields without modifying your datasource. Essentially, this
alters the source data stream which Biber uses to build the internal
Biblatex data model and is an automatic way of editing the datasource
as it is read by Biber.

The 3.1.2 section contains examples and precise explanations.
To sum up, the idea is to use biber in order to change a reference (for your problem you would like to add pages mention) without actually changing the .bib file. This way you don't have to create false references to get your bibliography (with related references) right.
I have no idea how it works exactly (and not the time to try) but I believe it could be a solution to your problem.


text:
Q: Problem in understanding the overflow flag (OF) as defined by the IMUL instruction I've confusion in why imul sets OF in the following instructions
mov  al, 48
mov  bl, 4
imul bl      ; AX = 00C0h, OF = 1

but NOT in the below instructions
mov  ax, 48
mov  bx, 4
imul bx      ; DX:AX = 000000C0h, OF = 0

A: IMUL sets the overflow flag when the low half of the result, interpreted as a signed integer of the appropriate size, does not equal the mathematical result of multiplying the two input numbers.
The mathematical result of multiplying 48 by 4 is 192.  The value left in AL after imul bl is C0h.  As a signed 8-bit integer, that represents the number -64.  Mathematically, 192 and -64 are not the same number, so overflow must be set.
After imul bx, the value left in AX is 00C0h.  As a signed 16-bit integer, that represents the number 192.  So the overflow flag is not set.
Equivalently, the overflow flag is set if sign-extending the low half would yield a different value from the full product.  When you sign-extend the 8-bit value C0h to 16 bits, you get FFC0h, which does not equal 00C0h, so overflow is set.  When you sign-extend the 16-bit value 00C0h to 32 bits, you get 000000C0h, which does equal the actual 32-bit result, so overflow is not set.
Equivalently, the overflow flag is cleared only if every bit of the high half of the result is equal to the sign bit of the low half.  The sign bit of the 8-bit value C0h is 1, but the high half is not FFh, it is 00h, so overflow is set.  The sign bit of the 16-bit value 00C0h is 0, and the high half is 0000h, so overflow is cleared.

A: OF tells you whether you can truncate the double-width full result back to the input width without changing its value.  (When interpreted as a 2's complement integer for imul1, unsigned binary integer for mul.)
0xC0 is the bit-pattern for a negative 8-bit number, but 0x00C0 is a positive 16-bit number.
That's what you want to know if you're using imul or mul  as part of a sequence of other 8-bit or 16-bit operations like add, without planning to use the high half of the result.
(Or could be useful to fall back to an extended-precision version that does handle the wider size, if the narrow version is fast enough to be worth branching for.)
If you were already going to use the full width of the output, don't check OF/CF; widening multiply can't overflow in the sense of losing any output bits.  The product of two N-bit numbers can always be represented in 2N bits.

Footnote 1: Including the 2 and 3 operand forms like imul cx, dx, 123 that don't write the high half anywhere.  Normally you'd use that form for non-widening signed or unsigned math, but if you want to detect when an unsigned multiply wrapped, your best bet is to just use mul even though that forces you to use EAX and have the output in EDX:EAX.  See imulq and unsigned long long overflow detection in C and asm


text:
Q: many to many retreiving book & author name error laravel Unable to display all books name and author name as list. Getting error. If I return the books and authors variables in controller (index method) I get the data as array. But unable to access them in view. Also as mentioned in commented code (in Book Controller) below, code from laravel documentation shows error.
Book Model
class Book extends Model
{
 protected $guarded = [];

 public function authors(){
    return $this->belongsToMany('App\Models\Author')->withTimestamps();
 }
}

Author Model
class Author extends Model
{
 public $guarded = [];

 public function books(){
    return $this->belongsToMany('App\Models\Book')->withTimestamps();
 }
}

Book Controller
 public function index()
{
    $query = Book::with('authors')->get();
    Pls Read the commented lines below -
    //foreach ($query as $book) {
    //return $book->authors->author_name;  //Error: Property [author_name] does not exist on this collection instance.
    //}
    // (above code is given in laravel documentation but shows error : why?)
    foreach($query as $b){
     $books[] = $b->book_name;
     $authors[] = $b->authors->first()->author_name;
    }
    return view('books.index', compact('books','authors'));
}

public function create()
{
    return view('books.create');
}

public function store(validateAuthorBook $request)
{
    $validated = $request->validated();
    if($validated){
        $book = new Book();
        $book->book_name = $request->book_name;
        $book->save();

        $author = new Author();
        $author->author_name = $request->author_name;
        $author->save();

        $book->authors()->attach($author);
    }

    return back()->with('status', 'Insert Successful!');
}

View (index.blade.php)
  @foreach($books as $b)

        {{$loop->iteration}}
        {{$b->book_name}}
        //how to get author name
        @endforeach

error
Facade\Ignition\Exceptions\ViewException
Trying to get property 'book_name' of non-object (View:
D:\ProgrammingSSD\laragon\www\ulclibrary\resources\views\books\index.blade.php)

A: You are getting error because you are making $book a string in array ($books[] = $b->book_name;). You shouldn't do anything with $books collection in controller, and could send it directly to view.
Controller:
public function index()
{
    $books = Book::with('authors')->get();
    return view('books.index', compact('books'));
}

View (one line, split authors with comma):
@foreach($books as $book)

        {{ $loop->iteration }}
        {{ $book->book_name }}
        {{ $book->authors->pluck('author_name')->implode(', ') }}

@endforeach

View (loop, split authors with new line):
@foreach($books as $book)

        {{ $loop->iteration }}
        {{ $book->book_name }}

            @foreach($book->authors as $author)
                {{ $author->author_name }}

            @endforeach

@endforeach


text:
Q: Javascript createElement and append child node I'm trying to create an element and append a child node to it, but my return is just a string without the element.
I'm first creating the element with
const li = document.createElement('li');
Secondly, I'm creating the text node with:
const text = document.createTextNode('hello');
Finally I'm appending the text to the li with:
const newMessage = li.appendChild(text);
Results for console.log(newMessage) is just a string of the message. Output in the dom is just a string also. I'm expecting the complete li element with the text node. I've also tried using innerHTML instead of appendChild.
Seems like a huge noob question but I'm not sure what I'm missing?
Thanks,

A: Append the li element to the dom too, to show it.

const li = document.createElement('li');
const text = document.createTextNode('hello');
var a=li.appendChild(text);
document.getElementById("list").appendChild(li)
console.log(a)

A: Node.appendChild()
Return value

The returned value is the appended child except when the given child is a DocumentFragment, in which case the empty DocumentFragment is returned.

You do not need to assign the li.appendChild in a variable:

const li = document.createElement('li');
const text = document.createTextNode('hello');
li.appendChild(text);
console.log(li.appendChild(text).nodeName); // #text
document.querySelector('ul').appendChild(li);

A: You have to append your li into the DOM for it to appear. You can do it by querying a parent element and using appendChild on it:
document.querySelector('ul').appendChild(li);

The appendChild function returns the node that was just appended. In your case, newMessage will be the text node appended to your li, see the MDN appendChild doc.

const li = document.createElement('li');
const text = document.createTextNode('hello');
const newMessage = li.appendChild(text);

document.querySelector('ul').appendChild(li);

console.log(newMessage);


text:
Q: Conditions on correlation parameter for positive (semi) definitiveness of variance-covariance matrix Consider a 3-variate random vector normally distributed with mean $\mu$ and variance-covariance matrix
$$
\Sigma=\begin{pmatrix}
1 & \rho & \rho\\
\rho & 1 & \rho\\
\rho & \rho & 1
\end{pmatrix}
$$
Could you help me to understand under which conditions on $\rho$ $\Sigma$ is positive semi-definite and under which conditions on $\rho$ $\Sigma$ is positive definite?
We know that $\rho\in [-1,1]$. Since $Det(\Sigma)=1-3\rho^2+2\rho^3$, we have that $Det(\Sigma)\geq 0$ iff $\rho\geq -0.5$. Is this sufficient?

A: These two statements are equivalent

*

*$\Sigma$ is positive definite

*All eigenvalues of $\Sigma$ are positive
The eigenvalues of $\Sigma$ are $\{1-\rho, 1-\rho,1 + 2\rho\}$, which implies that we require
$$
1 - \rho > 0 ~~~\mbox{and}~~~ 1 + 2\rho > 0
$$
or equivalently
$$
-1/2 < \rho < 1
$$
For the semi-definite case you can change "$<$" by "$\leq$"

A: This is an approach, note that you can write $\Sigma$ as
$$
\Sigma = \rho e'e + (1 - \rho)I,
$$ with $I$ the identity matrix and $e = (1,1,1)'$. We can take $O$, the matrix that consist of the orthonamal vectors $e/\sqrt{3},u,v$ and note that rotating perservs the question and the new sigma matrix (it preserves the eigen values)
$$
\Sigma_2 = O'\Sigma O = 3 \rho \,\text{diag}(1,0,0) + (1 - \rho) I = \text{diag}(2\rho + 1, 1 - \rho, 1 - \rho)
$$ And we have found all roots and the other answer apply.


text:
Q: Inserting golang slice directly into postgres array I have a problem with inserting slice into postgres array directly and can't find a simple solution.
Given:
favorites := []int{1,2,3,4,5}
// need to
_, err = db.Exec(fmt.Sprintf("UPDATE users SET favorites = '{%v}';", favorites))

Because of input is '{[1,2,3,4,5]}' instead of '{1,2,3,4,5}' I have an error.
I am using default SQL package and "github.com/lib/pq" postgres driver.

A: You should use pq.Array(favorites) to insert it correctly. As you can see in the source code
It would be like:
favorites := []int{1,2,3,4,5}

query:= "UPDATE users SET favorites = $1;"

_, err = db.Exec(query, pq.Array(favorites))

A: using pq.array to the respective golang slice will help you to insert the array.
q = q.Values(result.Id, result.Text, result.CreatedAt, pq.Array(result.EditHistoryTweetIds))

here EditHistoryTweetIds will be golang slice.


text:
Q: Is a multipurpose theme an alternative to modifying or creating a theme from scratch? Some experience using Wordpress, but not much experience developing with Wordpress.  In two months, I will be tasked with programming a Wordpress website for a church.  They are currently developing their "look and feel", and when done I am supposed to "program it in".  I am not sure how much they understand about how Wordpress works, however.
In the past few days I have been acquainting myself with HTML, CSS, MYSQL, PHP, and two books on Wordpress Theme development in case I have to modify a theme for them.  In the meantime, I advised them to go on the Internet and google "Wordpress Theme church" to see if there would be something that would suit their needs that maybe I could modify slightly if need be.
I am not keen on doing extra programming if I can help it, because I have concerns with the church being able to debug and maintain the website if I should have to leave prematurely for some reason.  I also have concerns about them being able to pick a theme from the Internet altogether.
Tonight, however, I was beginning to watch a tutorial on Wordpress, and I noticed an advertisement for a multipurpose theme that claimed it was the easiest way to build a website, but without hardly any coding.  That sounded good to me, but I am looking for an opinion if multipurpose themes are flexible enough that a person wouldn't need to search for a specialized theme to modify or build one from scratch?  What would be the advantages and disadvantages of the different approaches?

A: In my opinion, multi-purpose themes are the worst thing you can use, especially if you have specific goals in mind. Whatever theme you choose, you can use it without any code changes, and in the same time, if you run into problems with multi-purpose theme and need to make changes to the code, you will need a lot more time to do it then with simpler niche themes.
If you need church theme, there are specialized themes and even theme shops dedicated to church themes. If you find the right theme, you will not need to make any code changes. And, even if you need to do it, the simpler theme is simpler to modify.
My advice: when you have a specific goal in mind, stay away from multipurpose themes. And stay away from any shop claiming that their theme is 'easiest' to build a website with.


text:
Q: Is there a list of all places in SF config where UI error messages can be defined? When creating an Account I encountered an error message:

Looks like a custom message but I searched over every possible place I know where custom error messages can be created and didn't find it. These places were:

*

*Duplicate rules

*Validation rules

*Account triggers (looking for addError() method)

Probably I just don't know about every possibility, so the question is:
Is there a list of possible places where UI error messages can be defined?
And if not - could someone who knows it, provide such a list?

A: You should take the help of a tool like 'Eclipse' or 'VS Code' to be able to search across all the metadata objects to find this error string "A Record with.....". It could be a custom label, so try searching for this in the custom labels (Setup->Custom Labels). Otherwise try to put a debug on your user and check the debug log where this is coming from to know the exact truth.
There is no such centralized place of errors in general. In programming practice we use custom labels to store such error messages and reference that label in the apex or lightning code.


text:
Q: How to access laravel eloquent relationship data using AJAX? I can easily access my relationship data from Laravel blade. However, whenever I try to access them from AJAX it shows undefined or error. I have tried all the way but can't solve it. Please help.
My Controllers Code:
 public function store(Request $request){

    $task_name = $request->task_name;
    $empId = $request->empName;
    $catId = $request->catName;
    $desName = $request->desName;
    $start = $request->start_date;
    $end = $request->end_date;

    $inputs = array();
    $task_start_date = Carbon::parse($start)->format('Y-m-d');
    $task_end_date = Carbon::parse($end)->format('Y-m-d');

    $inputs['name']= $task_name;
    $inputs['user_id']= $empId;
    $inputs['cat_id']= $catId;
    $inputs['des']= $desName;
    $inputs['start_date']= $task_start_date;
    $inputs['end_date']= $task_end_date;

    $tasks = Task::create($inputs);
    $table =  "";

    $items = Task::all();

    foreach ($items as $item){

        $table .="
";
        $table .=" ";
        $table .=$item->taskCategory->name;
        $table .=" 	";
        $table .="
";
        $table .="";
    }

    $temps = Task::with('taskCategory')->get();

    return response()->json([
        $tasks,
        'table'=>$table,
        'temps'=>$temps

    ]);

}

My Eloquent Model Code:
 public function taskCategory(){

    return $this->belongsTo(TaskCategory::class,'cat_id','id');
}

My ajax code in laravel Blade:
 $(document).on('submit','#add_company_form', function(event){
        event.preventDefault();
        $.ajax({
            url:config.routes.task_post,
            method:"POST",
            data:new FormData(this),
            dataType:'JSON',
            contentType: false,
            cache: false,
            processData: false,
            success:function(data)
            {
                if(data.id!=""){
                    // toastr.success('We do have the Kapua suite available.', 'Turtle Bay Resort', {timeOut: 5000})
                    //console.log(data);
                    toastr.options = {
                        "debug": false,
                        "positionClass": "toast-bottom-right",
                        "onclick": null,
                        "fadeIn": 300,
                        "fadeOut": 2000,
                        "timeOut": 2000,
                        "extendedTimeOut": 2000
                    };

                    var rowCount = $('#order-listing >tbody >tr').length+1;
                    $.each(data.temps, function (key, val) {

                        // console.log(val.taskCategory.name);
                        $('#companyappend').append(`<tr class="unqcompany` + val.id + `">

        ` + rowCount + `
        ` + val.taskCategory.name+ `

            <button class="btn btn-outline-primary companyshow commonbtn" data-id="` + val.id + `" data-toggle="modal" data-target="#view_company_modal"></button>
            <button type="button" class="btn btn-outline-success editcompany commonbtn" data-companyname="` + val.name + `"  data-id="` + val.id + `" data-toggle="modal" data-target="#exampleModal"></button>
            <button type="button" class="btn btn-outline-danger btn-icon-text deletecompany commonbtn"  data-id="` + val.id + `">

            </button>

`);
                    });
                    toastr.success('Task was Created successfully');
                    $('#add_company_form').trigger('reset');
                    // console.log(data.table);
                    // $('#companyappend').html(data.table);
                }else{
                    alert("Failed to store");
                }
            }
        })
    });

This is to say that I can access my relationship data from blade easily. But in AJAX it throws an error or undefined. Please Help me.


text:
Q: Xcode 9 Beta 5 on High Sierra Beta 6 I currently using Xcode 9 Beta 5 on High Sierra Beta 6 to updated my Apps for Swift 4 and iOS 11...
But after I launch an App on Simulator or Device launchd_sim eats up all CPU.
It only goes down when I quit Xcode and restart it...
Anyone solution for this?

A: As Beta-Stadium on both (High Sierra and Xcode 9) is finished, I could be a good Idea to test on productivity Environment and close this ticket, if the problem is solved. Otherwise you could open a new ticket on stable Release of the Software.


text:
Q: Using a Python script with Selenium on my cPanel I have python script that I usually use on my PC. The script uses Selenium web driver, it collects data from a source, and stores it into my local MySQL db. I would like to automate it on my cPanel web-server instead of always running it from my PC and storing the data into my MySQL db in my cPanel. Maybe through a cron job. I'm using Selenium because, in order to collect my data, I need to complete input and select fields.
In short, I have no idea how to do this. I've never done this before and I feel like I'm running in circles trying to find out the best way to do it. Does anybody have any ideas or suggestions on where to get started? Many thanks!


text:
Q: Receive response from Instagram API call with AngularJS To authenticate a user in an app using the Instagram API, you redirect the user to the URL https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code.
Once the user signs in on this page, Instagram then makes a GET request to the redirect URI (REDIRECT-URI in the above URL). This call to the redirect URI contains a code which you must then include in a POST request to https://api.instagram.com/oauth/access_token to exchange for an access token which is sent in a JSON form in the response.
So I'm receiving the redirect call and making the request for the access token with my Express API and this works fine and I get the form with the access token.
app.get('/redirect', function(req, res){
    if(req.query.error){
        console.log('Error authenticating user');
        console.log(req.query.error);
    }
    else{
        request.post(
                     'https://api.instagram.com/oauth/access_token',
                     {form:{
                             client_id: 'my_client_id',
                                 client_secret: 'my_client_secret',
                                 grant_type: 'authorization_code',
                                 redirect_uri: 'http://localhost/redirect',
                                 code: req.query.code
                                 }
                     },
                     function(error, response, body){
                         if(!error && response.statusCode == 200){
                             console.log(body);
                             //HOW DO I GET THIS RESPONSE TO ANGULAR?
                             res.json({
                                     access_token: body.access_token,
                                         full_name: body.full_name,
                                         username: body.username,
                                         profile_picture: body.profile_picture,
                                         id: body.id
                                         });
                             return;
                         }
                         else{
                             console.log(response);
                             console.log(body);
                         }
                     }

                     );
    };

My question is: how to I send the access token (or error response) back to Angular?
In other words, how does Angular receive the response from a request it did not make (since the response I want to receive is from the request made with NodeJS's request)?
Initially I tried to make the first GET to https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code with Angular but I don't think this can be done because the user should be directed to the Instagram URL to sign in.

Update:
When Instagram makes the GET /redirect?code=xxxxxx, it sends the request to my API but also changes the page URL to http://localhost/redirect?code=xxxxxx. I can receive the access token in my API and send it to my client-side but because of the above URL, the page is just displayed as the text of the response and not my index.html with ng-view. How do I get the page to be my index.html in this situation?
I've tried with angular-router the following ways but neither worked:
.when('/redirect', {
        templateUrl: 'views/success.html',
                controller: 'Controller'
                        })

and
.when('/success', {
        templateUrl: 'views/success.html',
                controller: 'Controller'
                        })
.when('/redirect', {
        redirectTo: '/success'
                        })

A: What I ended up doing (and I'm not sure this is optimal):
Once I receive the response from the call made from Node, I store the access token from the response, body.access_token, in the req.session.user object provided by the express-session npm package and then I redirect the user to the home page with res.redirect('/#/home');.
app.get('/redirect', function(req, res){
if(req.query.error){
    console.log('Error authenticating user');
    console.log(req.query.error);
}
else{
    request.post(
                 'https://api.instagram.com/oauth/access_token',
                 {form:{
                         client_id: 'my_client_id',
                             client_secret: 'my_client_secret',
                             grant_type: 'authorization_code',
                             redirect_uri: 'http://localhost/redirect',
                             code: req.query.code
                             }
                 },
                 function(error, response, body){
                     if(!error && response.statusCode == 200){
                           console.log('Success making POST to Insta API for token, making new session object');
                           console.log('token:', (JSON.parse(body).access_token), '\n');
                           req.session.user = {};
                           req.session.user.token  = JSON.parse(body).access_token;
                           req.session.save();
                           res.redirect('/#/home');
                     }
                     else{
                         console.log(error);
                         res.redirect('/#/login');
                     }
                 }

                 );
};

This way, Angular doesn't need to receive the access token after redirecting the user to Instagram's authorization page because the access token is saved in the req.session.user object which is then accessible on the backend for the duration of the session.
You can then use the access token in any requests to the Instagram API from your backend (initiated by a call to your API from Angular), e.g. by concatenating it to whatever the endpoint is for your Instagram API call like so:
var endpoint = 'https://api.instagram.com/v1/users/self/follows?access_token=' + req.session.user.token;
This method also works well with the session management functionality of express-session since a session is only created when the user can be authenticated by Instagram. See here for a quick tutorial on how to integrate session management into your app.


text:
Q: POWERSHELL: Defrag Script Fails to Analyze When I try to run this script I keep getting errors indicating the defrag portion fails to run: "Method invocation failed because [Selected.System.Management.ManagementObject] does not contain a method named 'DefragAnalysis'."
$drives = Get-WmiObject Win32_Volume |Where { $_.drivetype -eq '3' -and $_.driveletter} |Select-Object driveletter
#|select driveletter="C:\"

foreach($drive in $drives)
{
$report = $drive.DefragAnalysis()
$report.DefragAnalysis
}

So what am I missing?
I get this error in PS 4.0 and 5.1:
PSVersion 5.1.14409.1018

A: ...and wouldn't you know I found the solution on Petri.com:
$Servers = Get-Content d:\batch\input\servers.txt
ForEach ($Server in $Servers){
$analysis = Get-DefragAnalysis -Driveletter C: -Computername $Server
}


text:
Q: Traversing web page in javascript
Possible Duplicate:
How to iterate through a DOM tree?

Could you advise me how to write the following pseudocode in javascript?
for each child of <body>:
  if (tag.haschildren):
    for each tag.child:
       do some action;

thank you

A: var els = document.getElementsByTagName("*");
for (var i = 0, ii = els.length; i < ii; i++) {
  for (var j = 0, jj = els[i].childNodes.length; j < jj; j++) {
    action(els[i].childNodes[j]);
  }
}


text:
Q: How to print from iPad using bluetooth? I have a printer which supports the printing over the bluetooth network .
I searched for printing from iOS and went through the Apple documentation on  UIPrintInteractionController class . But no where it has been specified whether it can use bluetooth to make the connection to the printer or not ? I know it works on the Wifi .
Can any one suggest any tutorial or any link on printing from iPad using bluetooth ( if at all possible )
 Please help me with this !!!!

A: The AirPrint protocol uses a WiFi network to detect compatible devices. I don't think it's possible to print via Bluetooth in iOS as of yet.


text:
Q: Get current date as String warning deprecated toGmtString() issue I want to get the current date day/month/year min:sec in Android so I have used the follow code
String data="";
Calendar c = Calendar.getInstance();
data=c.getTime().toGMTString();

But Eclipse notify me that the method .toGMTString(); is deprecated.
How could I get the current date as formatted String avoiding the use of this deprecated method?

A: From the Android documentation:

This method is deprecated.
  use DateFormat

Since the GMT string is represented as 22 Jun 1999 13:02:00 GMT, we can use SimpleDateFormat (subclass of the abstract DateFormat) like so:
SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
String asGmt = df.format(c.getTime()) + " GMT";

Might want to double-check that format, but this'll get you started. Have a look at this IDEOne code.

A: The method toGMTString() from the type Date is deprecated.
you can check this for different types of date formations.
In your case use
SimpleDateFormat dfDate  = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss");
String data="";
Calendar c = Calendar.getInstance();
data=dfDate.format(c.getTime());
System.out.println(data);//==========> 17/Oct/2012 08:36:52

If you want to print month number instead of month name
use
SimpleDateFormat dfDate  = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String data="";
Calendar c = Calendar.getInstance();
data=dfDate.format(c.getTime());
System.out.println(data);//==========> 17/10/2012 08:36:52


text:
Q: Changing images with text I'm making a game in which based on the choice the player makes, it will bring up new text to choose from. I'm trying to connect images to that text so they pull up with every choice. Right now, my text is working, but my images are no pulling up.
What am I doing wrong here?
  <script type ="text/javascript">
    const textElement = document.getElementById('text')
    const optionButtonsElement = document.getElementById('option-
     buttons')

    let state = {}

    function startGame() {
        state = {}
        showTextNode(1)
                         }

      function showTextNode(textNodeIndex) {
     const textNode = textNodes.find(textNode => textNode.id ===
     textNodeIndex)
      textElement.innerText = textNode.text
      document.getElementById('img').src=textNode.img
      while (optionButtonsElement.firstChild) {

   optionButtonsElement.removeChild(optionButtonsElement.firstChild)
        }

        textNode.options.forEach(option => {
            if (showOption(option)) {
            const button = document.createElement('button')
            button.innerText = option.text
            button.classList.add('btn')
            button.addEventListener('click', () =>
            selectOption(option))
            optionButtonsElement.appendChild(button)
                }
            })
         }

        function showOption(option) {
        return option.requiredState == null ||
        option.requiredState(state)
            }

        function selectOption(option) {
        const nextTextNodeId = option.nextText
        if (nextTextNodeId <= 0) {
        return startGame()
            }
        state = Object.assign(state, option.setState)
        showTextNode(nextTextNodeId)
            }

        const textNodes = [
        {
        id: 1,
        Image:url('invitation.jpg'),
        text: "You are cordially invited to celebrate Sir Troy
        Bennet's 70th birthday! RSVP to attend the event this
        evening at the Cherry Hill mansion.",
        options: [
        {
        text: 'RSVP',
        nextText: 2
        },
        {
        text: "I'm going to stay home",
        nextText: 24
        }
         ]
          },

A: This is going to need more context such as a reproducable example on JSFIDDLE or CODEPEN... however based on what I can see your code says;
textNode.img

When you are looking for;
textNode.Image

On line 17;
document.getElementById('img').src=textNode.img

So you have to change Image:url('invitation.jpg'), to be img:url('invitation.jpg'), or update textNode.img to be textNode.Image as mentioned above.


text:
Q: Extract value of JavaScript variable using selenium java When I try to extract using
JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("return myArray;"));

I get exception

org.openqa.selenium.WebDriverException: unknown error: myArray is not
  defined

myArray is a JavaScript variable that is populated by an ajax call.
Please help

A: I don't have much familiarity with selenium, but looks like 'myArray' is not found into context due to some error. It is not initialized, which might be due to an error in the Ajax call.

A: I think you should try this. It may solve your problem.
JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("return myArray"));