Q: Using ManagementObjectSearcher to get an exact BitLocker WMI value Good Day All,
I am having an issue with ManagementObjectSearcher. I am trying to query the exact value that i want but cannot find any reference to the precise syntax requirements and I continually receive an error when trying to finish out the code to be what I need it to be.
the specific portion of code that is presenting the issue is when I check for the drives Encryption state(I know for a fact that my disk is not encrypted on this machine, which is why that is the only value i have if'd currently). Any assistance in getting this code to pull the correct value would be greatly appreciated.
I've tried both the "=" method and the "LIKE" method with no change in output.
using Microsoft.Win32;
using System;
using System.Drawing;
using System.IO;
using System.Management;
using System.Windows.Forms;

    public Form1()
    {
        InitializeComponent();

        // Check for OS Version
        string OSVer = Convert.ToString(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", null));
        OSDialog.Text = OSVer;

        // Check Architecture
        if (Directory.Exists("C:\\Program Files (x86)"))
        {
            ArchitectureDialog.Text = "64 Bit";
        }
        else
        {
            ArchitectureDialog.Text = "32 Bit";
        }

        // Check Encryption
        ManagementObjectSearcher Collect = new ManagementObjectSearcher("SELECT ProtectionStatus FROM Win32_EncryptableVolume WHERE DriveLetter = 'C:'");

        string Encryption = Collect.ToString();

        if (Encryption == "0")
        {
            EncryptionDialog.Text = "Disk is not Encrypted";
            EncryptionDialog.ForeColor = Color.Green;
        }
    }

    private void Cancel_Click(object sender, EventArgs e)
    {
        Close();
    }

A: Getting BitLocker information from WMI requires elevated permissions. Your code has to be running as an admin and you have to ask for elevated privileges. So, I don't use ManagementObjectSearcher to obtain BitLocker info. Instead, I do something similar to the following (modified to your scenario - but not tested as shown):
ManagementObject GetBitLockerManager( string driveLetter )
{
    var path = new ManagementPath( );
    path.Server = string.Empty;
    path.NamespacePath = @"\ROOT\CIMV2\Security\MicrosoftVolumeEncryption";
    path.ClassName = "Win32_EncryptableVolume";

    var options = new ConnectionOptions( );
    options.Impersonation = ImpersonationLevel.Impersonate;
    options.EnablePrivileges = true;
    options.Authentication = AuthenticationLevel.PacketPrivacy;

    var scope = new ManagementScope( path, options );
    var mgmt = new ManagementClass( scope, path, new ObjectGetOptions( ) );

    mgmt.Get( );
    return mgmt
      .GetInstances( )
      .Cast<ManagementObject>( )
      .FirstOrDefault
      ( vol =>
        string.Compare
        (
          vol[ "DriveLetter" ] as string,
          driveLetter,
          true
        ) == 0
      );
}

A: OK so I figured it out, thank you for all of the assistance provided. Code is below.
ManagementObjectSearcher Encryption = new ManagementObjectSearcher(@"root\cimv2\Security\MicrosoftVolumeEncryption", "SELECT * FROM Win32_EncryptableVolume");

        foreach (ManagementObject QueryObj in Encryption.Get())
        {
            string EncryptionStatus = QueryObj.GetPropertyValue("ProtectionStatus").ToString();

            if (EncryptionStatus == "0")
            {
                EncryptionDialog.Text = "Unencrypted";
            }
            else if (EncryptionStatus == "1")
            {
                EncryptionDialog.Text = "Encrypted - SysPrep will not complete";
            }
            else if (EncryptionStatus == "2")
            {
                EncryptionDialog.Text = "Cannot Determine Encryption";
            }
        }


Q: Where i can edit this price element woocommerce? I want to replace the word "De: " of all products, but I do not know where
Link to website

A: You can change the "From" text via the woocommerce_get_price_html_from_text filter.
You would do so, like this:
add_filter( 'woocommerce_get_price_html_from_text', 'so_43054760_price_html_from_text' );
function so_43054760_price_html_from_text( $text ){
    return __( 'whatever', 'your-plugin-textdomain' );
}

Keep in mind this is WooCommerce 3.0-specific code. I'm not sure it is back-compatible with WC 2.6.x.


Q: User Registration setting missing in Joomla This is my first experience in Joomla V3.3.6
I have a requirement where there would be 2 user types.
-> User Type 1
-> User Type 2

1) I am looking out for registration module in Joomla. Searched and looks there are lots of plugins. But also understood that Joomla by default has default Registration module as per the below link:

*

*http://docs.joomla.org/Allowing_user_registration

*http://docs.joomla.org/Setting_user_registration_policy
The issue is, I do not see a place in Global Settings where there is User Settings as defined by the above link. Hence not able to see the registration page.
2) I see in admin dashboard, User Manager, User Groups. I guess, I could use these user groups to define the User Types. Please confirm if this is how it is in Joomla?
Kindly Help! Thanks in advance.

A: From the administrator, go to User Manager
At the top right, you'll see Options
That's where you set the user/registration options


Q: Chart.Js Doughnut not calculating JSON data properly When using static data, the Doughnut chart appear perfectly, example:
$.ajax({
        url: 'includes/stats.php?show',
        dataType: 'json',
        success: function (response)
        {
            console.log(response['CARS']); //I see 2
            console.log(response['MOTORS']); //I see 0
            console.log(response['BOATS']); //I see 0
            var autoData = [
                {
                    value: 2,
                    color: "#4286f4",
                    highlight: "#4d6fa5",
                    label: "Cars"
                },
                {
                    value: 0,
                    color: "#3fe276",
                    highlight: "#51a36d",
                    label: "Motor Homes"
                },
                {
                    value: 0,
                    color: "#bde234",
                    highlight: "#87964e",
                    label: "Boats"
                }
            ];
            var ctx = document.getElementById("onChart").getContext("2d");
            var myNewChart = new Chart(ctx).Doughnut(autoData);
        }
});

I'm doing the JSON call, but on the callback, I'm filling autoData variable with static data [2, 0, 0], this way the chart appears and calculate 100% for "Cars", because it is the only with some value (2), others are 0's...
When I do:
$.ajax({
        url: 'includes/stats.php?show',
        dataType: 'json',
        success: function (response)
        {
            console.log(response['CARS']); //I see 2
            console.log(response['MOTORS']); //I see 0
            console.log(response['BOATS']); //I see 0
            var autoData = [
                {
                    value: response['CARS'],
                    color: "#4286f4",
                    highlight: "#4d6fa5",
                    label: "Cars"
                },
                {
                    value: response['MOTORS'],
                    color: "#3fe276",
                    highlight: "#51a36d",
                    label: "Motor Homes"
                },
                {
                    value: response['BOATS'],
                    color: "#bde234",
                    highlight: "#87964e",
                    label: "Boats"
                }
            ];
            var ctx = document.getElementById("onChart").getContext("2d");
            var myNewChart = new Chart(ctx).Doughnut(autoData);
        }
});

I get just what looks like a 2% slice of the chart filled... What's happening here?

A: I was constructing the JSON from PHP, something like:
    $data = $autoQuery->fetch_array();
    $autoData = array('CARS' => $data['CARS'],
                    'MOTORS' => $data['MOTORS'],
                    'BOATS' => $data['BOATS']);
    echo json_encode($autoData);

This wasn't working. When I put intval() before each $data variable, it worked!


Q: I want to add list view new items (Except old ones) to array I have two list views, list one contains hotel service items that are fixed to a specific room and the other on is optional services, when i click on optional service list view item it will be added into services items. at the end all services will be viewed in list services(fixed + additional), and the price of only optional service will be saved in a db table which is optional service of the specified room
i tried on adding to delete old values and then adding optional services till the size of the added items but it doesn't work, some times it gives an error and other it prints or add only the old services and first one from the optional
`
for(int i=0;i<(lst1Count);i++){
lst1.getItems().remove(i);
    }
for(int i=0;i<(lst1.getItems().size());i++){

       try {
           String queryServicePrice = "select Serviceprice from services where ServiceName ='"+lst1.getItems().get(i)+"'";
           ResultSet rsRoomService = stmt.executeQuery(q`ueryServicePrice);
           rsRoomService.next();
           Serviceprice[i] = rsRoomService.getBigDecimal(

    "Serviceprice");
               System.out.println("price"+i+" : "+Servicepric

e[i]);}

`


Q: Enforce NTP Time Sync on boot - raspberrypi 3 I have a setup a raspberrypi to sync time from a NTP server as it does not have a HW clock on it, however this update does not happen immediately and takes a while (~15 mins). Is there a way I can enforce the NTP Client to sync datetime with the NTP server before starting up other user processes. If anyone has been able to achieve this please let me know. cheers!
Update: The rPi does not have internet connectivity

A: You might want to try this service from the NIST:
NIST Internet Time Service.  They have a list of servers here. and tips on how to engage with their system from Windows, OSX, and Linux.   The response might be quick enough to hold you over until your NTP client can receive its response.


Q: how to get running total column sir i have query that show RUNNING TOTAL but not show me exect Dr_amount and Cr_amount as per transaction how to get Dr_amount and Cr_amount as per single transaction
SELECT
V_DATE,FLAG,V_NUM,V_NARATION,
sum(DR_AMOUNT) AS DEBIT,
sum(CR_AMOUNT) AS CRIDIT,
sum(dr_amount)-sum(cr_amount) as total
FROM VOUCHARDETAIL AS VDTL
INNER JOIN VOUCHARMASTER AS VMST
ON VDTL.DTL_NUM <=VMST.MST_NUM
WHERE (V_DATE BETWEEN '12-03-2017' AND '13-03-2017') AND (FLAG='IV' OR FLAG='BR'
OR FLAG='CP' OR FLAG='CR' OR FLAG='JV') AND (AC_CODE=60030002)
GROUP BY
V_DATE,FLAG,V_NUM,V_NARATION
ORDER BY
V_DATE

Example Image


Q: Running Transient services in background (.NET Core) I am attempting to write a customer order tracker using Blazor Server.
What I'd like to do is launch on the background an order management service for every new order created. The service would keep track of various live information associated with the order, and it should be disposed of when the order is completed.
I am able to do that through registering the service as:
services.AddTransient();
I can then dependency-inject this into a razor component:
@inject OrderManagementService om_service
This creates a new instance for each order, which is good. The problem is that I can't expect the user to keep the page open in order to keep the the Transient service's scope alive.
From my observation, the instance continues to run, but its lifetime is not well-defined. It could terminate indefinitely soon (not long enough to finish the job), or run indefinitely long (thus robbing the server of resources). As I have no reference to it.
How can this problem be solved? If Transient services are not the solution, then what would it be?
Thank you!

A: Check out hosted background services in .NET Core, sounds like it could work for you.
Hosted background services continue running on your server even if the user navigates away from your site. You could have an OrderManager hosted service that guides each order through the process and keeps the order status updated in the database, email the user status updates, or push changes to the front-end.


Q: Auto refresh/reload four iframes in Wordpress I'm pretty NEW
so on the question:
I have 4 iframes on one page in WordPress showing some stats. I want to make them auto refresh (not the whole page) on certain amount of time, like every 3 second.
I've managed to do that for one only but whenever I try to add another one it  doesn't work. I hope there's a simple solution.
Here's the iframe:
<iframe id="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt=">

And the JS I''ve putt in the Header:

PS: That was the only code I found on the internet working as it had to work. I tried with my very basic knowledge to add another 3 iframes to reload but only one refreshed.
Thanks in advance!

A: Try this code

setInterval(function(){ reloadIFrame2(); }, 5000);

function reloadIFrame2() {

 var elements = document.getElementsByClassName("idcw");
 for (var i = 0, len = elements.length; i < len; i++) {
  elements[i].src =  elements[i].src;
 }
}
<iframe class="idcw"  src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt=">

<iframe class="idcw"  src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt=">

<iframe class="idcw"  src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt=">

<iframe class="idcw"  src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt=">

Run this fiddle
http://phpfiddle.org/main/code/asn7-zfvq


Q: Formula to compute partial sums of the Basel problem? Question
What is the taylor expansion of $\Gamma(n+1)$ of the first $4$ terms? Are the results below correct?
I thought of an interesting way to calculate the following quantity:
$$  \prod_{(s-1)^2> m \neq I^2} (s^2 -m) =\frac{(s^2)!}{s ((2s-2)!)^2(2s-1 )}  $$
Where $m$ is an integer which is not a square. Further using this I realised I could calculate partial sums of the Basel problem:
$\epsilon$ is a nil potent matrix such that $\epsilon^4 = 0$. Hence, the expression becomes:
$$ \frac{(\epsilon^2)!}{s ((2\epsilon-2)!)^2(2\epsilon-1 )} \frac{(\epsilon-1)!^2}{(\epsilon-1)^2!} = 1 + O(1)- \epsilon^2 ( \gamma + 2\ln(\epsilon-1)  - B(\epsilon-1) )  $$
Note the $1$ used above is actually the identity. Using this it should be possible to find $B(\epsilon)$'s first two terms.
Background and Motivation
I was pondering about the following:
$$ \frac{(s^2)!}{(s!)^2}  = \frac{s^2\cdot(s^2-1)\cdot(s^2-2)\cdots(s+1)}{s!} $$
Now, we can do some further cancellation using the identity $s^2 - r^2= (s-r)(s+r)$:
$$ \frac{(s^2)!}{(s!)^2}  = {s\cdot(s+1)\cdot(s^2-2)\cdots(s+1)} = s(s+1)^2(s+2)^2\cdots(s^2 -2)(s^2-3)\dots  $$
Hence, we can the above expression properly:
$$  \frac{(s^2)!}{(s!)^2}  =  s (s^2 -(s-1)^2))\prod_{1 \leq k \leq s-2} (s+k)^2 \prod_{(s-1)^2> m \neq I^2 } (s^2 -m)$$
Where $I$ is an arbitrary integer and now re-writing the above expression:
$$ \frac{(s^2)!}{s ((2s-2)!)^2(2s-1 )}  =  \prod_{(s-1)^2> m \neq I^2} (s^2 -m)$$
Now since there are $(s-1)^2 - (s-1) = s^2 -3s +2$ non-square numbers less than $(s-1)^2$:
$$ \frac{(s^2)!}{s ((2s-2)!)^2(2s-1 )}  =  \prod_{i=1}^{s^2 -3s +2} (s^2 -m_i)$$
Where $m_i$ is the $i$'th non-square number. Taking $m_i$ common from the R.H.S using $\prod_{i} m_i = \frac{(s-1)^2!}{(s-1)!^2}$:
$$ \frac{(s^2)!}{s ((2s-2)!)^2(2s-1 )}  =  \frac{(s-1)^2!}{(s-1)!^2}\prod_{i=1}^{s^2 -3s +2} (\frac{s^2}{m_i} - 1) $$
Expanding out the R.H.S from smallest term to largest:
$$ \frac{(s^2)!}{s ((2s-2)!)^2(2s-1 )} \frac{(s-1)!^2}{(s-1)^2!} = 1 - s^2(\sum_{i=1}^{s^2 -3s +2} \frac{1}{m_i}) + \dots + \prod_{i=1}^{s^2 -3s +2} (\frac{s^2}{m_i} ) $$
Now we use the identity:
$$\sum_{i}^{s^2 -3s +2} \frac{1}{m_i} = \sum_r^{(s-1)^2} \frac{1}{r} - \sum_{r=1}^{s-1} \frac{1}{r^2} = \gamma + 2\ln(s-1) +O(\frac{1}{s^2}) - B(s-1)$$
where $B(s-1) = \sum_{r=1}^{s-1} \frac{1}{r^2}$. Now using the above as a substitution:
$$ \frac{(s^2)!}{s ((2s-2)!)^2(2s-1 )} \frac{(s-1)!^2}{(s-1)^2!} = 1 + O(1)- s^2 ( \gamma + 2\ln(s-1)  - B(s-1) ) + \dots $$
Now let us put $s \to \epsilon$ where $\epsilon$ is a nil potent matrix such that $\epsilon^4 = 0$. Hence, the expression becomes:
$$ \frac{(\epsilon^2)!}{s ((2\epsilon-2)!)^2(2\epsilon-1 )} \frac{(\epsilon-1)!^2}{(\epsilon-1)^2!} = 1 + O(1)- \epsilon^2 ( \gamma + 2\ln(\epsilon-1)  - B(\epsilon-1) )  $$
Note the $1$ used above is actually the identity. Using this it should be possible to find $B(\epsilon)$'s first two terms.


Q: Installing Maven and creating a maven project in eclipse I am new to using maven project and i am trying to create a maven project and i followed the instructions to create one in eclipse and i gave the groupId and artifact id to it and clicked Finish, for which it gave me an error stating

"No marketplace entries found to handle
  maven-compiler-plugin:3.1:compile in Eclipse.  Please see Help for
  more information."

For this issue i tried googling and stack overflow and i saw people asking other people to change the installation directory of maven inside

Window-> Preferences -> Maven-> Installation

I tried that and tried to update the maven project but still i have some errors, i am not able to setup my project, Could someone please help?
I am attaching the errors herewith.

A: If  a Maven project is configured to use ecj compiler, the following errors appear when importing the project into eclipse:

*

*No marketplace entries found to handle maven-compiler-plugin:2.3.2:compile in Eclipse.  Please see Help for more information.

*No marketplace entries found to handle maven-compiler-plugin:2.3.2:testCompile in Eclipse.  Please see Help for more information.
A fix should be trivial.
http://git.eclipse.org/c/m2e/m2e-core.git/tree/org.eclipse.m2e.jdt/lifecycle-mapping-metadata.xml reads:
    <parameters>
      <compilerId>javac</compilerId>
    </parameters>

It should read:
    <parameters>
      <compilerId>javac</compilerId>
      <compilerId>eclipse</compilerId>
    </parameters>

Reproducible: Always
Steps to Reproduce:
1. Unpack example zip provided
2. Try to import it to Eclipse: File->Import->Maven->Existing Maven Projects

A: First you can try to install maven globaly. follow the steps.

*

*Download maven from maven download link

*Create or export M2_HOME="MAVEN ROOT LOCATION". Ex. : E:\SoftwareRepo\building tools\apache-maven-3.5.2

*Create  or export MAVEN bin folder location to PATH variable.
For example: E:\SoftwareRepo\building tools\apache-maven-3.5.2\bin

*Open terminal or cmd and run mvn --version to confirm maven is installed or not.
Then go to eclipse. and setup project.follow this steps

*

*Import existing maven project or create a maven project

*Goto project explorer and Right click on your pom.xml

*then select Run As maven install.

*and then what you want.

Hope it will serve your purpose. You can download a sample spring boot project from sample spring boot project
Or you can run a maven project from terminal or cmd. Just goto project root folder and then run a maven task like maven clean install .
Happy Coding :)

A: First install Java and then create the maven project.
Install the stable Java version in the system.
If Java is not installed then these types of errors will be displayed.

No marketplace entries found to handle
maven-compiler-plugin:3.1:compile in Eclipse.

Take a look at Help for more information.


Q: java.lang.ClassCastException: cannot cast class com.ibm.WsnOptimizedNaming._NamingContextStub to interface Created a remote EJB project and deployed in the IBM websphere server as Jar.
Now, i created a EJB Client project in my local and trying to connected as Remote call.
but it is throwing an exception: java.lang.ClassCastException
client Program:
package ejb3.test;

import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

public class TestEJBClient {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Properties props = new Properties();

    props.put(javax.naming.Context.PROVIDER_URL, "iiop://(ip of remote ejb server):2809");

    ITestEJBRemoteInterface loEJB = null;
    Object lobj;

    try {

        InitialContext ctx = new InitialContext(props);
        System.out.println(ctx.getEnvironment());
        lobj = ctx.lookup("ejb3/test/ITestEJBRemoteInterface");// look up of corba
        System.out.println("--------" + lobj);

        loEJB = (ITestEJBRemoteInterface)     PortableRemoteObject.narrow((org.omg.CORBA.Object) lobj, ITestEJBRemoteInterface.class);
        String lsName = "Kevin";
        // Invoke the Method using bean object ;
        System.out.println("Is " + lsName + " present in the list:: " + loEJB.checkNames(lsName));
        System.out.println("EJB run successful");
    }
    catch (NamingException e) {
        e.printStackTrace();
    }

    }
}

exception:
{com.ibm.websphere.naming.hostname.normalizer=com.ibm.ws.naming.util.DefaultHostnameNormalizer, java.naming.factory.initial=com.ibm.websphere.naming.WsnInitialContextFactory, com.ibm.websphere.naming.name.syntax=jndi, com.ibm.websphere.naming.namespace.connection=lazy, com.ibm.ws.naming.ldap.ldapinitctxfactory=com.sun.jndi.ldap.LdapCtxFactory, com.ibm.websphere.naming.jndicache.cacheobject=populated, com.ibm.websphere.naming.namespaceroot=defaultroot, com.ibm.ws.naming.wsn.factory.initial=com.ibm.ws.naming.util.WsnInitCtxFactory, com.ibm.websphere.naming.jndicache.maxcachelife=0, com.ibm.websphere.naming.jndicache.maxentrylife=0, com.ibm.ws.naming.wsn.localonly=false, com.ibm.websphere.naming.jndicache.cachename=providerURL, java.naming.provider.url=iiop://10.176.106.207:2809, java.naming.factory.url.pkgs=com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming}
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
INFO: Client code attempting to load security configuration
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.LoadSCI
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.GettingConfig
Feb 18, 2016 7:39:53 PM null null
WARNING: ssl.default.password.in.use.CWPKI0041W
Feb 18, 2016 7:39:53 PM null null
INFO: ssl.disable.url.hostname.verification.CWPKI0027I
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.AuthTarget
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.ClientCSI
--------com.ibm.WsnOptimizedNaming._NamingContextStub:IOR:00bdbdbd0000003149444c3a636f6d2e69626d2f57736e4f7074696d697a65644e616d696e672f4e616d696e67436f6e746578743a312e3000bdbdbd0000000100000000000000f4000102bd0000000a6c6f63616c686f737400238c0000006b4a4d4249000000124773e3aa37643062633737336533616166633334000000240000004749454a500200f76a838007736572766572311a57736e44697374436f734f626a65637441646170746572574c4d00000016434c45564449434d2d3134334e6f6465303143656c6cbd00000007000000010000001400bdbdbd0501000100000000000101000000000049424d0a0000000800bd00011600000100000026000000020002bdbd49424d04000000050005020102bdbdbd0000001f0000000400bd0003000000200000000400bd0001000000250000000400bd0003
Exception in thread "P=592906:O=0:CT" java.lang.ClassCastException: cannot cast class com.ibm.WsnOptimizedNaming._NamingContextStub to interface ejb3.test.ITestEJBRemoteInterface
    at com.ibm.rmi.javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:396)
    at javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:148)
    at ejb3.test.TestEJBClient.main(TestEJBClient.java:38)

How could i resolve that error?
Can any one please share your thoughts.

A: ClassCastException - if narrowFrom cannot be cast to narrowTo.

Seems that corba.object and itestejbrremoteinterface are not related by inheritance

A: The relevant lines from the dumpNameSpace are:
  168 (top)/nodes/CLEVDICM-143Node01/servers/server1/ejb3.test.ITestEJBRemoteInterface
  168                                                    ejb3.test.ITestEJBRemoteInterface

  192 (top)/nodes/CLEVDICM-143Node01/servers/server1/ejb/TestEJB(1)_jar/TestEJB(1).jar/TestEJB#ejb3.test.ITestEJBRemoteInterface
  192                                                    ejb3.test.ITestEJBRemoteInterface

The root of the server context is (top)/nodes/CLEVDICM-143Node01/servers/server1/, which means you should use one of these strings:

*

*ejb3.test.ITestEJBRemoteInterface

*ejb/TestEJB(1)_jar/TestEJB(1).jar/TestEJB#ejb3.test.ITestEJBRemoteInterface


Q: How to reliably determine the width of a character in C#? I'm writing a C# program and I'm using a fixed-width font to display everything. Under this font, every Unicode character either occupies 1 character width or 2 character width. In the program, there is a feature that needs to determine a particular character occupies 1 character width or 2 character  width. At first I use the regex [^\x00-\xFF] to solve the problem. If a character matches it, it occupies 1 character width, otherwise it's 2 character width. But later I found this is not correct. For example, these characters ┌─┬┐│├┼┤┴┘ don't fall in the range of [^\x00-\xFF] but they all just occupies 1 character width. I want to know in C# how to determine a specific character occupies 1 character width or 2 when using fixed-width font?

A: I'm also searching for the same question's answer... but I haven't found it.
by the way, I finally write a library to get length of character (generate a range information which shows character length use Console.Write() and Console.CursorLeft, and then convert to C# code, when get character length, use binary search for higher speed)
nuget: NullLib.ConsoleEx
Project: https://github.com/SlimeNull/NullLib.ConsoleEx

A: According to .NET documentation, if you know the font used1, you could use the GlyphTypeface API to get the "AdvanceWidths" of each glyph of your font.
You still have to map the character with glyph index in your font. You can use CharacterToGlyphMap to do that.
var character = 'x';

GlyphTypeface glyphTypeface = new GlyphTypeface(new Uri("file:///C:\\WINDOWS\\Fonts\\Kooten.ttf"));

var index = glyphTypeface.CharacterToGlyphMap[character];
var width = glyphTypeface.AdvanceWidths[index];

[1] To get current console's font details I would recommend to read following question: Get current console font info
Related question: How to find exact size for an arbitrary glyph in WPF?


Q: Mule http connector encoding I am posting xml string use mule http connector to my client.
The xml has string "Grubišić". It works fine if I post data to client from anypoint studio. If run on production or testing server, my client received "GrubiÅ¡iÄ" instead of "Grubišić".
I tried to specify content-type = "application/xml;charset=UTF-8" from http request header, payload property.. none of them worked.
<set-payload value="#[flowVars.myXML]" encoding="UTF-8" mimeType="application/xml" doc:name="Set Payload"/>
<http:request config-ref="HTTP_Request_Configuration" path="/api/upload" method="POST" doc:name="HTTP" >
    <http:request-builder>
        <http:header headerName="Content-Type" value="application/xml;charset=UTF-8"/>
    </http:request-builder>
</http:request>

I am using 3.9CE runtime.
Am I missing any config? or it could be a bug in 39CE standalone?
Thanks
-Susan

A: There a lot of context missing in the question to be sure, but setting the encoding in the set-payload operation or in the Content-Type header doesn't actually transform the payload to or from UTF-8. A common mistake is to assume because the configurations, or even the XML declaration says UTF-8, to assume that the data is UTF-8 automatically. It is the data that is in UTF-8 or not. Most probably you are using a payload that is in a local encoding (Windows-1252 or something similar) when you test locally, but your server uses UTF-8 by default so it doesn't appear as you are expecting. "GrubiÅ¡iÄ" looks very similar to how the UTF-8 encoding of "Grubišić" would look.


Q: Does the 'Supporting Files' folder increase launch time/CPU consumption? If I have a lot of images/etc in the Supporting Files folder does that increase CPU consumption and slow the launch time of the app? Does the app have to load all these files on launch.
Thanks in Advance :)

A: No. In general these are copied into the apps bundle at compile time, letting the app access them when it needs them (by finding the files).


Q: how to make chromium/chrome only reloads the modifled files? My site has a lot of img, js, css files. If one file is modified by developer its url will be changed too, otherwise the url will not be changed.
I wish chromium/chrome only reloads the modified files according to the url, but actually it often reloads all files with some unknown rules　without using cache.
How to solve this?

A: It's a vague and broad question, but I guess you use different URLs to prevent retrieving old, cached versions of changed resources (that's one sure way anyway, although not necessarily the best way) and have a problem with Chromium-based browsers not caching resources that are unchanged.
Chromium respects caching directives as per spec, so it seems you're not sending the appropriate caching directives (headers) in the first place or have a problem testing the caching behavior (e.g. testing with caching disabled). Determine which is the problem and fix it.


Q: Update sharepoint user profile property with SPSecurity.RunWithElevatedPrivileges I try to change user profile property with next code
SPSecurity.RunWithElevatedPrivileges(delegate(){
SPSite currentSite = new SPSite(SPContext.Current.Web.Url);

SPServiceContext serviceContext = SPServiceContext.GetContext(currentSite);
UserProfileManager upm = new UserProfileManager(serviceContext);
UserProfile up1 = upm.GetUserProfile("DOMAIN\\User3");
up1["CustomProperty"].Value=10;
up1.Commit();

currentSite.Dispose();
});

And it's all right when i open page with account User1, which have permissions to change all user profiles. But when i open page with User2(with no permissions) - i get 403 error. In debugger up1["CustomProperty"].Value is null.
Why SPSecurity.RunWithElevatedPrivileges have no effect and how can i solve this problem?
Thanks

A: I found description of my problem in next article
Impersonation does not work with UserProfileManager
As a reason you can clear HttpContext each time you get or set user profile properties. For example next code works fin for me.
 SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            HttpContext tempCtx = HttpContext.Current;
            HttpContext.Current = null;

            UserProfile userProfile = GetUserProfile(user);
            userProfile["SomeProperty"].Value = points;
            userProfile.Commit();

            HttpContext.Current = tempCtx;
        });


Q: How to iterate through a list of URLs and make a GET request I am trying to take a list of URLs from Google Sheets and then make an API request for each URL and return data in JSON format.  I currently am able to retrieve the list from Google sheets as well as make a Request for a single URL that I manually enter.
So far everything is working as expected.  I am more or less asking for guidance on what my next steps would be.  I am a novice in Python so not sure what to do next.
Here is an example of the output for the API request of the single URL in JSON:
{"date":"2019-02-07T00:00:00+0000","clicks":7},{"date":"2019-02-06T00:00:00+0000","clicks":7},{"date":"2019-02-05T00:00:00+0000","clicks":5}
# -*- coding: utf-8 -*-
"""
Created on Thu Dec  6 18:47:58 2018

@author: Dylan
"""

import requests
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials

#scope is just telling google what API you want to use because they have so
many
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('Bitly Click
Data-a892fb027ee3.json', scope)
gc = gspread.authorize(credentials)

wks = gc.open("Bit.ly Links & General Links").get_worksheet(0)
values_list = wks.col_values(2)

wks = json.dumps(str(wks))

print(wks.get_all_records())

url = "https://api-ssl.bitly.com/v4/bitlinks/THIS NEEDS TO BE THE URL LIST
HERE/clicks"

payload = ""
headers = {'authorization': 'Bearer ACCESS TOKEN HERE'}

response = requests.request("GET", url, data=payload, headers=headers)

print(response.text)


Q: Два if в тернарном операторе react if else React. Опишу свою проблему на банальном примере. Допустим, есть переменная
let user = 'Ivan'

Могу ли я в jsx создать такой тернарный оператор проверки if else, который будет иметь два if и один else в своей конструкции?
Итак. Что я пытаюсь сделать примерно. Проверяю:
{user == 'ivan' ? 'Пользователя зовут Иван' user == 'Boris' ? 'Пользователя зовут Борис' : 'Не знаю такого пользователя'}

Но такая конструкция не работает. У меня ошибка в синтаксисе? Или подобная конструкция никоим образом не может принять в себя два выражения для положительного ответа?
Не хочу городить здоровенную конструкцию из if или кейсов, потому хочу реализовать это более лаконично и аккуратно.

A: Лучше так:
Вариант 1
const userText = useMemo(() => {
  switch (user) {
    case 'Ivan':
      return 'Пользователя зовут Иван';
    case 'Boris':
      return 'Пользователя зовут Борис';
    default:
      return 'Не знаю такого пользователя';
  }
}, [user]);

return (

{userText}

);

Вариант 2
const userTextMap = {
  'Ivan': 'Пользователя зовут Иван',
  'Boris': 'Пользователя зовут Борис';
};

const MyComponent = ({ user }) => {
  return (

      {userTextMap[user] || 'Не знаю такого пользователя'}

  );
};

A: Можно, конечно, сделать так
{
  user == 'ivan' ? 'Пользователя зовут Иван' :
    user == 'Boris' ? 'Пользователя зовут Борис' : 'Не знаю такого пользователя'
}

Но я бы делал так
let res;
switch (user) {
  case 'Ivan': res = 'Пользователя зовут Иван'; break;
  case 'Boris': res = 'Пользователя зовут Борис'; break;
  default:
    res = 'Не знаю такого пользователя';
}

Так код читается гораздо лучше


Q: Having trouble wrapping my head around how to handle dates I'm working on a scheduling system for music venues.  The basic idea is that there's an "Create new schedule" page, on which there is a DatePicker calendar (using AngularUI Bootstrap).  The user selects a Date, then adds performers into timeslots. The built object looks something like this:
{
  date: 2017-6-22 00:00:00.000-5:00
  venue: VenueID
  performances: [
    {
      performer: performerID,
      time: 2017-06-22 22:00:23.231-5:00
    },{
      perfomer: performer2ID,
      time: 2017-06-22 23:00:42.523-5:00
    }
  ]
}

There's a couple of problems here.  For the original date selection, I set the time (using myDate.setHours(0,0,0,0)) to midnight because the time doesn't really matter, I only care about the actual date.  Likewise for the timeslots, their date doesn't matter (since they belong to the schedule for that day), so I only care about the time. Then in another project, we have a node/mongo app that saves these schedules, and returns them to a page in the angular project that lets you select a schedule for editing/etc.  It selects which ones to return by grabbing all the schedules for a specific venue, and doing "if (schedule.date >= new Date().setHours(0,0,0,0)) { add schedule to return list }"
Anyway, on to the actual problem.  The angular app does all of the date calculations client side.  What I mean is, I'm in CST.  If I select a Date on the calendar and save a schedule for that date, then someone in EST selects the same day on the calendar and saves a schedule, they have different dates in the database.  For example, when I make the schedule, the date in the DB is "2017-06-22 00:00:00.000-5:00".  When the EST friend makes a schedule on the same date, it gets saved as "2017-06-22 00:00:00.000-4:00".
In the "Select a schedule to view/edit" page, I do something like this:
<select ng-model="schedule" ng-options="s.date|date:'fullDate' for s in schedules" ng-show="schedules.length>=1"></select>

Of course this doesn't work because when my EST friend looks at the list, he sees the correct date.  But when I look at one that he created, the date is one day off because "2017-06-22 00:00:00.000-4:00" converted to local timezone is "2017-06-21 23:00:00.000-5:00".
I guess TL;DR is I'm not sure how to handle it since the venue and anyone creating/editing the schedules may not share the same time zone. I want all of the dates/times to show up in the timezone of the venue (which I have the address for.  I guess I could geolocate to find timezone?).  I'm just not sure how to go about it.

A: The DatePicker gives you a date object. Instead of storing the entire value string just grab the day month and year Date(value).getYear() + '-' + Date(value).getMonth()  + '-' + Date(value).getDate(). As for the times do the same as the dates. Store those values in the DB and then when you get them back you will have to convert them back to a date object so that the date picker can understand them.
Ultimately with this solution your just trying to store dates without the timezones. Make sure to state in your app that the times are for those areas.

A: You have to distinguish between the format the date/time is transported, saved vs. how the date will be shown to the user.

*

*For transportation and saving use UTC in a format that is easy computable (eg. ISO8601).

*For visualization to the user convert this value to the timezone and desired user format by using some helper library.


Q: how to poll a resource using jersey service i have a jersey service which generates a response. what i want to do is to poll a resource (in my case, a singleton class instance) for a success value, and as soon as i get the success value, perform some action
@Path("/generate")
class Generation{
    @POST
    @Produces("javax.ws.rs.core.MediaType.TEXT_PLAIN")
    public String generateAndPoll(){
        //Generate response
        /*Polling to start

        */
    return someValue;
    }
}

what may be a good way to accomplish that? Would timer be of any use?

A: As of Jersey 2.3.1, a new feature has been added to support server-sent events. For your use-case, you might want to read more into the Jersey documentation

A: If you don't mind using an external library, I have been using atmosphere for a few years and it is a great server push / comet implementation. It has support for just about ever server and yes it will depend on the server. They support long poll and websockets natively. Almost the entire service can be configured with just a couple of annotations. Here is an example of how to use it on a jersey 2 service.
https://github.com/Atmosphere/atmosphere-samples/blob/master/samples/jersey2-chat/src/main/java/org/atmosphere/samples/chat/jersey/Jersey2Resource.java


Q: Point out location in Google Map I am developing an application in PHP. I have latitude and longitute of few locations in Google Map. I want to point it those locations on google map.
How can i point it?

A: http://code.google.com/apis/maps/index.html take a look at the google api its very easy to work with


Q: Using Weistrass Approximation Theorem to define fourier series convergence. Weistrass Approximation Theorem: Let f be continuous on [-$\pi$,$\pi$] with $f(-\pi)=f(\pi)$. Then for each $\epsilon>0$ there is a trigonometric polynomial T such that $|f(x)-T(x)|<\epsilon$ for all x an element of $[-\pi,\pi]$.
We were also given a theorem saying that if $f(x)$ is square integrable then $\int[f(x)-T(x)]^2dx$ is miniimised when $T(x)$ is equal to the functions fourier series.
Now, we know that this implies convergence of the functions fourier series to the function itself in the $L^2$ sence (Lebesgue norm), but what I dont understand is why this doesn't imply uniform convergence of the functions fourier series to the function itself. I am aware that you do need stronger conditions to make this claim, but I dont see how Weistrass' theorem is not showing uniform convergence, and hence why we can't just use this theorem to say that uniform convergence holds.
Any help would be greatly appreciated, thanks!

A: I don't completely understand your question, let me just state some facts which might be related.
First, Weistrass Approximation Theorem states that if $f$ is continuous on $[-\pi, \pi]$ and $f(-\pi) = f(\pi)$, then for all $\epsilon>0$, there is $T$ so that $|f(x) -T(x) |<\epsilon$. Thus

*

*$T$ depends on $\epsilon$,

*$T$ is not unique given a fixed $\epsilon$.

*$T$ in general is not the fourier series $S_n(f)$ for any $n$.

A: The Weierstrass theorem you quote requires $ f $ continuous and with equal values at the endpoints Neither condition is required to be square integrable.


Q: Why solr RemoveDuplicatesTokenFilterFactory dont work? My schema.xml is splitting product name and then uses RemoveDuplicate to remove duplicated words after split.
    <fieldType name="type_name" class="solr.TextField">
        <analyzer type="index">
            <tokenizer class="solr.PatternTokenizerFactory" pattern="\|| " />
            <filter class="solr.LowerCaseFilterFactory"/>
            <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>

And in query analyzer I see that RemoveDuplicatesTokenFilterFactory did absolutely nothing to duplicated words. Why?

A: If you read Wiki you will see that it only removes duplicates at the same position, which is not the case here.


Q: Deploying angular build utilising the azure event hub js sdk fails to run If I run the project locally with

ng serve -o

everything works as expected
However, once I build it (either dev or prod build) and deploy it to either an Azure web app or a local web server on my machine I get the error of

connectionContext.js:20 Uncaught TypeError: os__WEBPACK_IMPORTED_MODULE_2__.type is not a function - within connectionContext.js (from the azure event hubs SDK)

I performed

npm install

and all modules install but I still get the same error each time.
I am assuming something is added when running locally via the ng server but is not included within a build.
Is there anything to check for that I may have missed?
UPDATE:
I have this running now by removing the functions that were causing the issue, not a fix more a hack to try and get progression. However, if I deploy to a local web server on my machine or to a raspberry pi it runs as expected. But when I deploy it to an azure web app it does not work as expected and states it cannot find 2 files (even though they can be seen via the FTP)

A: You need to create a web.config file in your wwwroot folder and add the MIME config like below to serve the JSON and WOFF files on Azure. You can check this similar thread.
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <system.webServer>
        <staticContent>
            <remove fileExtension=".json" />
            <remove fileExtension=".woff" />
            <remove fileExtension=".woff2" />
            <mimeMap fileExtension=".json" mimeType="application/json" />
            <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
            <mimeMap fileExtension=".woff2" mimeType="application/font-woff" />
        </staticContent>
    </system.webServer>
</configuration>

You can check angular deployment document fore more information,


Q: How to load 1000+ items to a asp:GridView from SQL Server DB with high efficiency I have a function like below that I use to return a gridview (id: dgmenu) to the end users based on their role. Note that I am not allowed to apply pagination to the gridView, all items must be seen in one page.
protected DataTable MenuForUserRole(string userRole) {
  DataTable dtMenus = new DataTable();
  string connectionString = constr;
  try {
    using(SqlConnection cnn = new SqlConnection(connectionString)) {
      cnn.Open();
      string query = @"Select mycolumn1, mycolumn2, mycolumn3, mycolumn4m mycolumn5
                       From mytable
                       Where mykey = (select thekey from anothertable where role = @role)
                       order by myOrderColumn;
                       ";

      SqlCommand oCmd = new SqlCommand(query, cnn);
      oCmd.Parameters.AddWithValue("@role", userRole);

      using(SqlDataAdapter a = new SqlDataAdapter(oCmd)) {
        a.Fill(dtMenus);
      }

      cnn.Close();
    }
  } catch (Exception ex) {
    throw;
  }
  return dtMenus;
}

Usage:
dgMenu.DataSource = MenuForUserRole(ddlUserRoles.SelectedItem.Value.ToString());
dgMenu.DataBind();

My issue is performance-related: some of the GridViews returned has more than 1000 items, so it takes 5-6 seconds to load the complete gridView for those users, which is unacceptable. When I search online, I couldn't find more efficient code to load a gridView from SQL Server Database. Any help or advice that might increase the load speed when there is high amount of data to the gridview would be appreciated.
Used -> Visual Studio 2017 & SQL Server 2017

A: The most efficient way would be to realize that it is a bad idea.
1000 records is too much for any user to deal with. 1-2 Orders of Magnitude to much. There is no human on this planet, that could work with that much data at once. This data needs to be filtered, grouped or paginated way more before it comes in front of a user.
And those are all operations you should not be doing past the query. Those should be done in the query itself. Retrieving data you do not want to do filtering later just adds a tone of network load, adds race conditions, Database locks and is propably slower anyway (DBMS are really good at their job!). Worse, with ASP.Net and it's shared memory it can quickly lead to memory issues.

A: Profile your code. Understand where most of the time is spent. It could be SQL Server, it could be transmission over network, it could be binding the data to the control[s]. If it is SQL Server, we would need to see your schema to tell you how performance could be improved. Like, do you have an index on mykey? BTW, don't call it a key, key is something that uniquely identifies the record, which is obviously not the case here.

A: Use reporting (e.g. Reporting Services) and create a link to export the data into an excel spreadsheet.


Q: mailmerge in word from c# opens multiple instances I'm trying to automate mailmerge using a .net program. There's a one page letter in word document addressed to a particular person with a mailmerge field by name 'Person'. Our database has got multiple persons and each person name has to go into a copy of the letter. We want the one-page letters to be concatenated one after the other. Currently this code tries to use two persons with - name1 & name2. The code below opens a separate instance of word for every person name.
        object oMissing = System.Reflection.Missing.Value;
        //CREATING OBJECTS OF WORD AND DOCUMENT
        Word.Application oWord = new Word.Application();
        Word.Document oWordDoc = new Word.Document("C:\\Test\\AddressTemplate.docx");

        //SETTING THE VISIBILITY TO TRUE
        oWord.Visible = true;
        //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE
        Object oTemplatePath = "C:\\Test\\AddressTemplate.docx";

        oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

        foreach (Microsoft.Office.Interop.Word.Field field in oWordDoc.Fields)
        {
            if (field.Code.Text.Contains("Person"))
            {
                field.Select();
                oWord.Selection.TypeText(name1);
            }
        }

        oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

        foreach (Microsoft.Office.Interop.Word.Field field in oWordDoc.Fields)
        {
            if (field.Code.Text.Contains("Person"))
            {
                field.Select();
                oWord.Selection.TypeText(name2);
            }
        }

Question: How can I change the code to open just one instance of word, fill in the mailmerge field and concatenate one letter at the end of the other?

A: If you call new Word.Application you're creating a new instance, if what you want is to create a new instance if there is none, but reuse one if there is already one open you can do the following:
        Application app;
        try
        {
            app = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
        }
        catch
        {
            app = new Application();
        }

Based on your comment i think you actually only have 1 instance of word open, it just opens both documents in different Windows (but a single application). Windows aren't the same as applications.
If you want it all in a single window you could reuse the previous document or else close it before you open a new one

A: Ronan's code above did the trick for me. I was doing new Application() every time, adding WINWORD instances (I know, should've known better). I speak both C# and VB, but here's the VB version I used in this project:
        ' Use same winword instance if there; if not, create new one
    Dim oApp As Application
    Try
        oApp = DirectCast(Runtime.InteropServices.Marshal.GetActiveObject("Word.Application"), Application)
    Catch ex As Exception
        ' Word not yet open; open new instance
        Try
            ' Ensure we have Word installed
            oApp = New Application()
        Catch eApp As Exception
            Throw New ApplicationException(String.Format("You must have Microsoft Word installed to run the Top Line report"))
        End Try
    End Try
    oApp.Visible = True


Q: How to change html href attribute value with jQuery? I am trying to change html href attribute value ?post=55 to ?post=44 with button click using jQuery, but don't know how.
HTML
<button class="button">button</button>

Post

JAVASCRIPT
$('.button').on('click', function() {

});

This is what I have
Post

This is what I want when clicking button
Post

A: A  Jquery function allows you to change an attribute of a tag. It is written as $("tag").attr('attr','newvalue').
In your case, you can do $("a").attr('href','posts.php?post=44') inside the click function (you should probably give the a tag an id too)

A: "on-click" handler has $(this) that you can use to navigate in the DOM tree if you know that the object you want to alter is relatively placed (from what I see you have  following <button/>.
$('.button').on('click', function() {
    $(this).parent().find('.post-link').attr('href', '#hello-world')
})

JSFiddle
If you want to change a link of the element that is somewhere on the page, I would suggest searching by id value (the id should be unique). Let's say you have ..., then:
$('.button').on('click', function() {
    $('#my-id').attr('href', '#hello-world')
})


Q: brew uninstall does not work cause of no space left on device I have low space left on my device and it was time to made some cleanup...
I removed a lot of things, trash, uninstall unused apps, caches, ... BUT
I installed "League of legends" for Mac a long time ago with brew and the game is huge, so I wanted to delete him like other app I do not use anymore...
$ brew uninstall league-of-legends
==> Uninstalling Cask league-of-legends
Warning: It seems there is already an App at '/usr/local/Caskroom/league-of-legends/latest/League of Legends.app'; overwriting.
==> Removing App '/usr/local/Caskroom/league-of-legends/latest/League of Legends.app'
==> Backing App 'League of Legends.app' up to '/usr/local/Caskroom/league-of-legends/latest/League of Legends.app'
cp: /usr/local/Caskroom/league-of-legends/latest/League of Legends.app/Contents/LoL/Game/DATA/FINAL/Champions/Lillia.wad.client: No space left on device
cp: /usr/local/Caskroom/league-of-legends/latest/League of Legends.app/Contents/LoL/Game/DATA/FINAL/Champions/Neeko.wad.client: No space left on device
cp: /usr/local/Caskroom/league-of-legends/latest/League of Legends.app/Contents/LoL/Game/DATA/FINAL/Champions/Kayn.fr_FR.wad.client: No space left on device
[...] and much more files...

It's like brew made a backup before uninstalling.
I tried to force the uninstall, but I got the same error :
$ brew uninstall league-of-legends --force

Do you guys know how to deal with this ?
thanks

A: Converting my comment on the original question to an answer, since this helped the Op.
I recommended that he delete the app manually from the Applications folder (in Finder or Terminal) and empty the Trash. He went further to also remove the downloaded cask under the homebrew directory and then was able to get “brew uninstall” to work.


Q: Trying to create a new page when horizontal pos. of i extends past right margin I am trying add a page when horizontal or the x position is greater than a counter in order to keep a right side margin. When I run the code I end up in an infinate loop of hundreds of pages all displaying the same first page graphics. Thinking it might have to do with my lack of understanding HasMorePages. I could use some help. Thanks.
    public static class PrintWave
{
    public static void PrintPreWave()
    {

        PrintDocument pd = new PrintDocument();

        if (WaveTools.MySettings == null)
        {
            pd.DefaultPageSettings.Landscape = true;
        }
        else
        {
            pd.DefaultPageSettings = WaveTools.MySettings;
        }
        pd.OriginAtMargins = true;

        pd.PrintPage += new PrintPageEventHandler(OnPrintPage);
        PrintDialog dlg = new PrintDialog();
        PrintPreviewDialog printPreviewDlg = new PrintPreviewDialog();
        printPreviewDlg.Document = pd;

        Form p = (Form)printPreviewDlg;
        p.WindowState = FormWindowState.Maximized;
        printPreviewDlg.ShowDialog();

    }

    private static void OnPrintPage(object sender, PrintPageEventArgs e)
    {
        string MyTag = string.Empty;
        MyTag = WaveActions.ActiveId;
        Wave MyWave = WaveHolder.FindWave(MyTag);
        int MyCount = 0;

        int xOffset = e.MarginBounds.Location.X;

        int yOffset = e.MarginBounds.Location.Y;

        if (MyWave != null)
        {
            Graphics g = e.Graphics;
            g.SetClip(e.PageBounds);

            Pen MyPen = new Pen(WaveTools.WaveColor, WaveTools.PenWidth);

            float dx = (float)e.PageBounds.Width / MyWave.NumSamples;
            float dy = (float)e.PageBounds.Height / 255;

            if (MyWave.Normal == false)
             {
               g.ScaleTransform(dx, dy);

            }

            for (int i = 0; i < MyWave.NumSamples - 1; i++)
            {

                g.DrawLine(MyPen, i, MyWave.Data[i], i + 1, MyWave.Data[i + 1]);
                MyCount = MyCount + 1;

                if (MyCount > e.MarginBounds.Width)
                {

                    e.HasMorePages = true;
                    MyCount = 0;
                    return;
                }
                else
                {

                    e.HasMorePages = false;
                    return;

                }

            }

        }

    }

}

}

A:        for (int i = 0; i < MyWave.NumSamples - 1; i++)

That's the core problem statement, you start at 0 every time PrintPage gets called.  You need to resume where you left off on the previous page.  Make the i variable a field of your class instead of a local variable.  Implement the BeginPrint event to set it to zero.
The else clause inside the loop need to be deleted.


Q: Is there a reward for collecting every ring in SegaSonic the Hedgehog? In the 1993 arcade game SegaSonic the Hedgehog, when you finish a level you are shown a percentage total for how many rings you managed to collect in the level.
According to the Sonic Wiki, you receive extra points if you collect at least half of the rings in a level. However, the wiki doesn't say whether you get additional points for collecting every ring.
Is there an additional bonus if you manage to collect every ring in a level?


Q: Strange behaviour when calling VB6.0 COM-component in C# (in python all is ok) I have some problems when working with COM-component in C#.
I have old (~2001-2003year developed) VB6 COM component, and unfortunately there is no source code for it. The component interacting with a service program (no source too). The main Application is written in VB6, and now I'm rewriting it on .Net.
I have imported (with TblImp) component into C# and calling it:
using System;
using System.Threading;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;

using SrvCommDCG;

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
        {
        System.Console.WriteLine("calling com");
        clsCommDCGService srv = new clsCommDCGService();
        srv.Check();
        System.Console.ReadKey();
        }
    }
}

When I'm running it on Windows 7, nothing happens (the component should show a messagebox when check is finished).
When I'm running it on Windows 8, program crashes without any exception.
I've tried different thread models: MTA, STA (using either [STAThread], or SetApartmentState()), calling DisableComObjectEagerCleanup() -- nothing helped.
After week of no result, I've tried to use my component in Python, and:
import win32com.client
tst = win32com.client.Dispatch("SrvCommDCG.clsCommDCGService")
tst.Check()

All is working, check is ok and MessageBox appeared.
Ofc, it works from VB 6.0 too.
I think, the problem is that python is single-threaded win32 app, and C# is multithreaded managed code. And I'm missing some point to understand what I should add to C# code, to make it work? Unfortunately I need to call it from .Net.
edit #1: I've tried on .Net 4.0 and 4.5, and also on .Net 2.0 frameworks
edit #2: when program crashing on Windows 8 there aren't any useful messages (even if i ran program from VS C# debugger), it's just write "Program occured a problem and will be closed" (have russian Win8, can't tell you the exact message in Windows). The Event log in Win8 says: Process was killed due to unhandled exception c0000005 at address 012E72CC. It's simple Access Violation.
edit#3: While C# program works bad on Win7/8, it works normal on Windows XP. Mysterios things.


Q: Get BoundingBox of ONLY visible area of map in osmdroid I am using osmdroid version 4 and I want to have BoundingBox of visible map. It seems that MapView.getBoundingBox method returns bounding box of all tiles that are visible or partially visible. Take a look at this picture:

Black rectangles are tiles, red rectangle with rounded corners is  device display.
I want to have only diagonal area shown by green line. What should I do?

A: I believe you are mistaken. getBoundingBox() returns the lat/long boundaries of what is visible on the screen. The code will take the pixel x,y value of the two corners and covert that into lat/long and that is what is used. It is not "snapped" to actual map tiles. The result of getBoundingBox() should return the area of the red box.


Q: Opens the map with a certain position of the camera I'm new to java, I installed Google maps in my application, but when you open the card, open a very large scale of the map, a function I need to use for that would map opened at a certain city? And just a second question - please tell me what the name of the function is responsible for determining the location the user

A: This question is rather vague but the API documentation should be able to help you here.
https://developers.google.com/maps/documentation/api-picker
Just pick out which API you need. It should be something like setLocation(Coordinates) in all of them.


Q: How can I eliminate duplicates using MAX function? I have these tables
recommendation_object_id, exhibitor_name, event_edition_id, timestamp
I want to hide/remove the duplicates in recommendation_object_id to make it a primary key.
I successfully removed most of the dups, but a few recommendation id's have a different event edition id so some id's are still duplicating as a result.
A colleague of mine said I could eliminate those further by using max(timestamp) but I could not pull it off :(
My current query is this:
SELECT DISTINCT r.recommended_object_id, ed.exhibitor_name, sd.event_edition_id, r.object_type, max(r.timestamp)
FROM recommendations r
left join show_details sd on r.event_edition_id = sd.event_edition_id
left join exhibitor_details ed on r.recommended_object_id = ed.exhibitor_id
group by r.recommended_object_id, ed.exhibitor_name, sd.event_edition_id, r.object_type
order by r.recommended_object_id

A: If you want one row per recommended_object_id, the one with the most recent timestamp, then use window functions:
select r.*
from (select r.recommended_object_id, ed.exhibitor_name, sd.event_edition_id, r.object_type,
           row_number() over (partition by recommended_object_id order by r.timestamp desc) as seqnum
      from recommendations r left join
           show_details sd
           on r.event_edition_id = sd.event_edition_id left join
           exhibitor_details ed
           on r.recommended_object_id = ed.exhibitor_id
     ) r
where seqnum = 1
order by r.recommended_object_id;


Q: mini.iso doesn't appear in Startup Disk Creator I am interested to make a clean install of Lubuntu Core with the mini.iso from a USB Stick. I am not interested to create a Live USB.
I've done my best to add from "Other" button form the Startup Disk Creator the mini.iso but doesn't appear anything like in here https://help.ubuntu.com/community/In...n/FromUSBStick
I've tried also..
sudo chmod a+r "location"/mini.iso
usb-creator-gtk -i "location"/mini.iso

And when the Startup Disk Creator opens, the mini.iso still not appears.
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.2 LTS
Release:    14.04
Codename:   trusty

apt-cache policy lubuntu-desktop
lubuntu-desktop:
  Installed: 0.55
  Candidate: 0.55
  Version table:
 *** 0.55 0
        500 http://dk.archive.ubuntu.com/ubuntu/ trusty/universe i386 Packages
        100 /var/lib/dpkg/status

I don't think that the old partition is Encrypted, when I installed Lubuntu I remember that I chose not to encrypt it... if this could be important for you. But better if you know exactly how to check it to be sure.
Thank you.

A: according to this site: http://www.maketecheasier.com/install-a-minimal-ubuntu-on-old-laptop/
"You won’t be able to create a USB startup disk with this iso file, so the only way is to burn it into a bootable CD."
BUT IT'S DATED...
EDIT:
Based on quick google search, Unetbootin should work fine:
https://apps.ubuntu.com/cat/applications/unetbootin/
Just select your mini.iso...
I CAN CONFIRM, IT DOES WORK! (15.04)

A: I would like to be clear that with the mini.iso I am interested to make a clean install of Lubuntu Core...
lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 232.9G  0 disk
├─sda1   8:1    0  18.6G  0 part /
├─sda2   8:2    0     1K  0 part
├─sda3   8:3    0 102.5G  0 part /home
├─sda4   8:4    0 108.1G  0 part /windows
└─sda5   8:5    0   3.7G  0 part [SWAP]
sdb      8:16   1   7.2G  0 disk
└─sdb1   8:17   1   7.2G  0 part /media/multix/0AA3-23B8
sr0     11:0    1  1024M  0 rom

I've tried the dd method but still nothing happened...
I've tried like that:
    cd ~/Downloads/
    md5sum 'mini.iso'
a2502844750ecb6477d8fb4ff6b9aaf8  mini.iso

md5sum is ok.
    cd ~/Downloads/
    sudo su
    dd if='mini.iso' of=/dev/sdb bs=4096
7936+0 records in
7936+0 records out
32505856 bytes (33 MB) copied, 2.33314 s, 13.9 MB/s

When I access the USB Stick I can't see any files on it, but when I go to Startup Disk Creator the "Label" of the stick is "Firmware" now and the capacity of it is 6.0 MB and the free space from it is 6.0 MB too...
THis is how it looks after I use dd
lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 232.9G  0 disk
├─sda1   8:1    0  18.6G  0 part /
├─sda2   8:2    0     1K  0 part
├─sda3   8:3    0 102.5G  0 part /home
├─sda4   8:4    0 108.1G  0 part /windows
└─sda5   8:5    0   3.7G  0 part [SWAP]
sdb      8:16   1   7.2G  0 disk
├─sdb1   8:17   1    25M  0 part
└─sdb2   8:18   1     6M  0 part /media/multix/Firmware
sr0     11:0    1  1024M  0 rom
loop1    7:1    0    31M  1 loop /media/iso

It could be possible that the USB stick to be mounted?
Can someone say it from this?
sudo mkdir /media/iso/
sudo mount -o loop /home/multix/Downloads/mini.iso /media/isomount: block device /home/multix/Downloads/mini.iso is write-protected, mounting read-only


Q: How to get img alt text and data-src using Beautifulsoup? HTML snippet :

I want to extract all the alt text and data-src from the img class="profile_photo_img. My code:
ele = soup.find_all('img', class_='profile_photo_img')
    for i in ele:
        print i["data-src"]
        print i["alt"]

But it is printing nothing. How can I get the desired result?

A: Try the following code:
elements = soup.findAll('img', attrs={'class':'profile_photo_img'})
for element in elements:
    print element['data-src']
    print element['alt']

Also make sure that the soup is right parsed from the html by printing it before you are searching for elements


Q: How to get custom headers from axios post response? i'm using nuxt/axios with laravel as my backend. in my responses from laravel i send a custom header named _msg but i cant access it. in my console.log(response) i get only this:

but in my brower network i get the header:

how can i access it?
UPDATED
added this to my laravel middleware:
this is an example if request is from manager and admin
<?php

namespace App\Http\Middleware;

use Closure;
use App\Traits\UtilsTrait;

class ManagerPlus
{
    use UtilsTrait;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//        return $next($request);
        if($this->isMoreManager()){
            $request->panelType = $this->addPanelType();
            $response = $next($request);

            $response->headers->set('Access-Control-Expose-Headers', 'Content-Disposition');
            return $response;
        }
        return $this->permissionDenied();
    }
}

UPDATE AFTER EXPOSE:
i did as told with my laravel/fruitcake setting and middleware and this is my new header that i get from axios. but still not getting my _msg

A: What I think you need to do is:
if you are using the package https://github.com/fruitcake/laravel-cors you will have config/cors.php and there is where you should add
'exposed_headers' => ['_msg'],
and you have to create the middleware as it's explained in the issue https://github.com/fruitcake/laravel-cors/issues/308#issuecomment-490969761
$response->headers->set('Access-Control-Expose-Headers', '_msg');
I hope it works


Q: How to accept an array parameter in a GET request in Flask using Connexion I am using connexion to create a REST API via Flask.  At the moment I am passing a single identifier in.
/read/maa_valid_product_id/{drug_product_id}:
    get:
      operationId: registrations.read_maa_valid_product_id
      tags:
        - Marketing Applications
      summary: Read the entire list of non-passive marketing application registrations for a specified drug_product_id, which have a valid authorisation status
      description: Read the entire list of non-passive marketing application registrations for a specified drug_product_id, which have a valid authorisation status
      parameters:
        - in: path
          name: drug_product_id
          required: true
          schema:
            type: integer
          description: Numeric ID of the user to get
        - in: query
          name: length
          required: false
          schema:
            type: integer
          description: Numeric ID of the user to get
        - in: query
          name: offset
          required: false
          schema:
            type: integer
          description: Numeric ID of the user to get
      responses:
        '200':
          description: Successfully commpleted the list operation for non-passive valid MAAs, for the specified drug_product_id
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/marketing_application'

I need to pass an array of id values in, based on selections in a table.  Is this possible?
If it is possible, how would I access the array, the existing method call is:
def read_maa_valid_product_id(drug_product_id, length=0, offset=0):
    """
    This function responds to a request for /api/products
    with the complete lists of people

    :return:        json string of list of people
    """
    # conn_ariel = pool.acquire()
    conn_ariel = get_connection()
    cursor_ariel = conn_ariel.cursor()

    # Create the list of products from our data
    sql = """
        SELECT A.DRUG_PRODUCT_ID,
               B.PREFERRED_TRADE_NAME,
               B.PRODUCT_LINE,
               B.PRODUCT_TYPE,
               B.FLAG_PASSIVE AS PRODUCT_FLAG_PASSIVE,
               A.REGISTRATION_UID,
               A.COUNTRY_DISPLAY_LABEL,
               A.FLAG_PASSIVE,
               A.AUTHORIZATION_STATUS,
               A.DISTRIBUTION_TYPE AS PROCEDURE_TYPE,
               A.MAH_COMPANY,
               A.DOSSIER_REF_NUMBER AS REGISTRATION_NAME_DETAILS,
               A.APPLICATION_STAGE,
               A.APPLICATION_TYPE,
               A.RENEWAL_NOT_REQUIRED,
               TO_CHAR(A.NEXT_RENEWAL_DATE,'YYYY-MM-DD') AS NEXT_RENEWAL_DATE

               FROM DIM_REGISTRATION_SET A, DIM_DRUG_PRODUCT B, v_rep_az_183_01_reg_includes C
               WHERE A.DRUG_PRODUCT_ID = B.DRUG_PRODUCT_ID AND A.VERSION_SEQ = C.VERSION_SEQ
               AND A.DATA_STATE = 'C'
               AND A.FLAG_PASSIVE = '0'
               AND A.APPLICATION_TYPE = 'Marketing Application'
               AND A.AUTHORIZATION_STATUS LIKE 'Valid%'
               AND A.DRUG_PRODUCT_ID = :id
               ORDER BY B.PREFERRED_TRADE_NAME, A.COUNTRY_DISPLAY_LABEL ASC
        """
    cursor_ariel.execute(sql,{"id":drug_product_id})
    registrations = []
    names = [c[0] for c in cursor_ariel.description]
    cursor_ariel.rowfactory = collections.namedtuple("registrations", names)

    i = 0
    j = 0

    start = None

    if offset == 0:
        start = True
    else:
        start = False

    for row in cursor_ariel.fetchall():
        if start == True:
            registration = {
                "drug_product_id": row.DRUG_PRODUCT_ID,
                "preferred_trade_name": row.PREFERRED_TRADE_NAME,
                "product_line": row.PRODUCT_LINE,
                "product_type": row.PRODUCT_TYPE,
                "product_flag_passive": row.PRODUCT_FLAG_PASSIVE,
                "registration_uid": row.REGISTRATION_UID,
                "country_display_label": row.COUNTRY_DISPLAY_LABEL,
                "flag_passive": row.FLAG_PASSIVE,
                "authorization_status": row.AUTHORIZATION_STATUS,
                "procedure_type": row.PROCEDURE_TYPE,
                "mah_company": row.MAH_COMPANY,
                "registration_name_details": row.REGISTRATION_NAME_DETAILS,
                "application_stage": row.APPLICATION_STAGE,
                "application_type": row.APPLICATION_TYPE,
                "renewal_not_required": row.RENEWAL_NOT_REQUIRED,
                "next_renewal_date": row.NEXT_RENEWAL_DATE
            }
            # logging.info("Adding Registration: %r", registration)
            registrations.append(registration)

            if length > 0:
                if i == length - 1:
                    break
            i += 1
        else:
            if j == offset - 1:
                start = True

        j += 1

    pool.release(conn_ariel)

    return registrations

A: Got there in the end:
yaml config:
/read/products_many/{drug_product_ids}:
    get:
      operationId: products.read_products_many
      tags:
        - Product
      summary: Read multiple drug products for the provided drug_product_ids
      description: Read multiple drug products for the provided drug_product_ids
      parameters:
        - name: drug_product_ids
          in: path
          required: true
          schema:
            type: array
            items:
              type: integer
            minItems: 1
          style: simple
          explode: false
          description: drug_product_ids primary keys of the required products

      responses:
        '200':
          description: Successfully retrieved product
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/product'

Based on:https://swagger.io/docs/specification/serialization/#uri-templates
Then in my method, I see a list coming in as a parameter, so I am converting to string and then creating the SQL using string formatting.
def read_products_many(drug_product_ids):

    conn_ariel = get_connection()
    cursor_ariel = conn_ariel.cursor()

    print(drug_product_ids)          # --> [4670, 4671]
    print(type(drug_product_ids))    #  --> List

    # convert to string for use in IN clause in SQL
    drug_product_ids = [str(x) for x in drug_product_ids]

    print("read_many product, id", drug_product_ids)
    # Create the list of products from our data
    sql = """
        SELECT DRUG_PRODUCT_ID, PREFERRED_TRADE_NAME, PRODUCT_LINE, PRODUCT_TYPE, FLAG_PASSIVE , PRODUCT_NUMBER
        FROM DIM_DRUG_PRODUCT
        WHERE DRUG_PRODUCT_ID in ({0})
        AND PREFERRED_TRADE_NAME NOT LIKE '%DO NOT USE%'
        AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%DELETE%'
        AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%TEST%'
        """.format(",".join(drug_product_ids))

    print("SQL")
    print(sql)
    cursor_ariel.execute(sql)

    product = None
    products = []

    for row in cursor_ariel.fetchall():
        r = reg(cursor_ariel, row, False)

        product = {
            "drug_product_id"           :   r.DRUG_PRODUCT_ID,
            "preferred_trade_name"      :   r.PREFERRED_TRADE_NAME,
            "product_line"              :   r.PRODUCT_LINE,
            "product_type"              :   r.PRODUCT_TYPE,
            "flag_passive"              :   r.FLAG_PASSIVE,
            "product_number"            : r.PRODUCT_NUMBER

        }
        products.append(product)

    pool.release(conn_ariel)
    return products

SQL being returned when I enter this URL:
localhost:5000/api/read/products_many/4671,4670

is correct as:
SELECT DRUG_PRODUCT_ID, PREFERRED_TRADE_NAME, PRODUCT_LINE, PRODUCT_TYPE, FLAG_PASSIVE , PRODUCT_NUMBER
        FROM DIM_DRUG_PRODUCT
        WHERE DRUG_PRODUCT_ID in (4671,4670)
        AND PREFERRED_TRADE_NAME NOT LIKE '%DO NOT USE%'
        AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%DELETE%'
        AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%TEST%'


Q: Mounted Volumes for IBM Bluemix CF Apps IBM Containers on Bluemix has the support for mounting volumes and use across containers. Is there any way we can have a similar shared volumes kind w.r.t Bluemix CF Apps?

A: Cloud Foundry applications on IBM Bluemix can use Bluemix's Object Storage service for shared storage between applications.
Cloud Foundry does not support sharing volumes across instances and discourages users from writing the the filesystem as storage.
Using Object Storage, you have an API to access and share files between applications.


Q: SGEN amplitude measurement doesn't match oscilloscope I don't understand the measurements regarding the voltage of the oscilloscope of the JDS6600 signal generator I recently bought.
Being the SGEN specified amplitude 5V I'd expect the Vpp on the oscilloscope to be 10v. Instead, I get 5.76V. Even if the amplitude in the SGEN actually refers to its  Vpp, it still doesn't match the one reported by the oscilloscope.


Q: How do I disable rails form_with update functionality I have the following form to add somebody to a waiting list.
<%= form_with(model: waitinglist, url: '/join', local: true) do |form| %>

    <%= form.text_field :email %>

    <%= form.submit %>

<% end %>

This works fine and it will post and add somebody to the waiting list. However when the page reloads the form goes into some sort of automatic resource mode that where the submit button magically changes to update and then the form submit magically changes to the HTTP Patch method.
I'm trying to understand what is doing this and I can't find anything in the docs.
How do I create a regular form that just posts to an end point but still validates the model? (and removes this update functionality).
edit added controller
class WaitinglistsController < ApplicationController
  before_action :set_waitinglist, only: [:show, :edit, :update, :destroy]

  # GET /waitinglists/new
  def new
    @waitinglist = Waitinglist.new
  end

  # POST /waitinglists
  # POST /waitinglists.json
  def create
    @waitinglist = Waitinglist.new(waitinglist_params)

    if @waitinglist.save
      flash[:notice] = "You have been added to the waiting list"
      render :new
    else
      render :new
    end
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_waitinglist
    @waitinglist = Waitinglist.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def waitinglist_params
    params.require(:waitinglist).permit(:email)
  end
end

A: You are keeping a copy of your persisted waitinglist variable around between page loads. When your new page is rendered for the second time, since the waiting list has already been persisted, it is doing all the magical default Rails behaviours, which include updating labels for the submit button (create vs update), and the form's method (post vs patch).
You will want to create a new waitinglist if you are going to re-render the new page:
  def create
    @waitinglist = Waitinglist.new(waitinglist_params)

    if @waitinglist.save
      @waitinglist = Waitinglist.new #
      flash[:notice] = "You have been added to the waiting list"
      render :new
    else
      render :new
    end
  end

A: I think what u should do is if the waiting list is saved, redirect to new instead of render new. When u redirect to action it will call the action so a new object will be created. When u do render it render the view and I will have your persisted object, that’s why it is trying to update.


Q: Cretate multiple shared secrets in a (selfmade) public/privavte key infrastructure I just try to understand cryptography, please be concern. Its not meant to be secure or professional. I create 3 numbers for each party. a public key, a secret key and a modulus. The first party (A) creates his keys
let pri = 133
let mod = 256
let pub = mod - pri

and shares "mod" and "pub" to other partys (B, C). When B want to encrypt a string he takes A's public key and modulus and do
// B encrypts
let enc = ( input + pubA ) % modA

A on his side is doing
// B decrypts
let dec = ( enc + priA) % modA

to decrypt it. My problem is, i can create multiple keypairs but only 1 associated public key to each secret key because i have to share the modulus of each pair for en/decryption.
Is it possible (in this situation) to create multiple publics numbers for a single private number? And if so, how can i do it?
Thank you (and sorry if this is a poor question)
EDIT Even if its not "good" to create your own cipher i want to do so..
I recognized that i missed the secret exponent d so that phi divides (e * expo)-1.
/* Pseude code */

p = q = primes()
n = p * q
phi = (p-1) * (q-1)

e = 3
d = ? // <-- have to find my own secret exponent!

if( gcd(e, p-1) != gcd(e, q-1) ) exit(0)

expo = 0
for(expo < 100000)
    if( (e * expo)-1 == phi ) ) d = expo

And therefore i could have
public(n,e)
private(n,d)

so i can share (n,e). Is that correct?


Q: Is there a way for users to collaborate on a post? There are times when multiple users wish to jointly prepare a question or answer, and not release it for general viewing before it is done.

*

*If it is of more than trivial length, that isn't practical to do in chat (can't really edit, and it needs to be in chunks of a few hundred characters).

*If it is desired to finalize it before others see it, that can't be done by just writing the post normally and both editing it.

*If both are high-rep users on the site, one could draft the post and delete it.  Then both could see it and edit it while it was deleted.  Only high-rep users who stumbled upon the thread would see the work in progress, so not perfect but maybe a workable solution for those users.  Best case, that's limited to at least one of the users being high-rep, and the low-rep user starting it (even if it's just a stub).  This wouldn't work for two low-rep users.

Do we have any provision to support this kind of collaborative effort?

A: Some SE sites, such as Math, have at least one "sandbox" type post on their site's meta (e.g., Sandbox for drafts of long, complex posts for Math), with them normally being used for users creating drafts of long posts, checking on formatting, etc., before posting on the main site. This is not quite what you're asking about, but I believe using one of the answer slots on a post like that would work fairly well for what you're describing. In particular, with it being updating a current "answer" on the post, relatively few people would notice it being updated plus, with it being a "sandbox" post, those people will often just ignore it anyway. Also, as fixer1234's comment indicates, if the score is low enough (i.e., -8 as Laurel's comment states, with this being used in the Physics' meta sandbox post), then edits won't bump the post to the main page. Nonetheless, the post would not be completely hidden, so people could still view the incomplete post. Regardless, if something like was used, I suggest adding a prefix text to indicate this is what's happening so people are aware of it and nobody else would try to edit that answer in the meantime.
If the site's meta doesn't already have a "sandbox" type post that you may reasonably use for your purpose, then this may provide a relatively good reason (among possibly several other reasons) to create one. Note that, as Laurel's comment indicates, there's a list of sandbox posts, with this including that sandbox type posts may be used for various purposes, and there even may be more than one on a particular site (e.g., Math and Meta), with each one being used only for specific purposes. Alternatively, you can create a new post on the site's meta to be used just for doing what you're describing, although it may be best to first check on the site's meta to confirm this is acceptable.


Q: WebDeploy with MSdeploy.exe fails to sync GAC Assembly because dll(s) locked by another process I'm having this problem using msdeploy to sync GAC assembly to many Application Servers.
When I run this command
msdeploy -verb:sync -source:gacAssembly="'MyAssembly'" -dest:gacAssembly,computername=DESTINATIONSERVER

I obtain this error:
*Microsoft.Web.Deployment.DeploymentException:
(28/09/2010 16.46.37) An error occurred when the request was processed on the remote computer.
---> Microsoft.Web.Deployment.DeploymentClientServerException: An error was encountered when processing 'INPS.DNA.dll'.
---> Microsoft.Web.Deployment.DeploymentException: The error code was 0x80070020.
---> System.IO.IOException: The process cannot access 'C:\Windows\assembly\GAC_MSIL\MYASSEMBLY\1.0.0.0__a31fe99d2f98435c\MYASSEMBLY.dll' because it is being used by another process.
   at Microsoft.Web.Deployment.Win32Native.RaiseIOExceptionFromErrorCode(Win32ErrorCode errorCode, String maybeFullPath)
   at Microsoft.Web.Deployment.FileStreamEx.CreateInstance(String path, FileMode fileMode, FileAccess fileAccess)
   at Microsoft.Web.Deployment.FilePathProvider.Add(DeploymentObject source, Boolean whatIf)
   --- End of inner exception stack trace ---
   --- End of inner exception stack trace ---
   at Microsoft.Web.Deployment.DeploymentObject.Update(DeploymentObject source,DeploymentSyncContext syncContext)
   at Microsoft.Web.Deployment.DeploymentSyncContext.HandleUpdate(DeploymentObject destObject, DeploymentObject sourceObject)
   at Microsoft.Web.Deployment.DeploymentSyncContext.SyncDirPathChildren(DeploymentObject destRoot, DeploymentObject sourceRoot)
   at Microsoft.Web.Deployment.DeploymentSyncContext.SyncChildrenNoOrder(DeploymentObject dest, DeploymentObject source)
   at Microsoft.Web.Deployment.DeploymentSyncContext.SyncChildrenOrder(DeploymentObject dest, DeploymentObject source)
   at Microsoft.Web.Deployment.DeploymentSyncContext.ProcessSync(DeploymentObject destinationObject, DeploymentObject sourceObject)
   at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject
destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, Conten
tRootTable contentRootTable)
   at Microsoft.Web.Deployment.DeploymentAgent.HandleSync(DeploymentAgentWorkerR
equest workerRequest)
   --- End of inner exception stack trace ---
   at Microsoft.Web.Deployment.StatusThreadHandler.CheckForException()
   at Microsoft.Web.Deployment.AgentClientProvider.RemoteDestSync(DeploymentObje
ct sourceObject, DeploymentSyncContext syncContext)
   at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject
destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, Conten
tRootTable contentRootTable)
   at Microsoft.Web.Deployment.DeploymentObject.SyncTo(DeploymentProviderOptions
 providerOptions, DeploymentBaseOptions baseOptions, DeploymentSyncOptions syncO
ptions)
   at MSDeploy.MSDeploy.ExecuteWorker()
Error count: 1.*
If I execute IISRESET on DESTINATIONSERVER the error doesn't occur!
My question is:
It's possible to unlock DLL without perform an IISRESET command?
I think I can avoid to restart entire Web Server.
Can you help me'
Thanks a lot!
Best regards.

A: What about using the recyleApp provider to stop and start the app pool?
msdeploy.exe -verb:sync -source:recycleApp -dest:recycleApp="Default Web Site",recycleMode="StopAppPool",computerName=remote-computer
... do your real deployment ...
msdeploy.exe -verb:sync -source:recycleApp -dest:recycleApp="Default Web Site",recycleMode="StartAppPool",computerName=remote-computer


Q: How to reduce the time of curl call? For some reason my curl call is very slow. Here is the code I used.
            $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTPHEADER,array('Expect:','Accept: application/xml'));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //curl_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //curl_setopt($ch, CURLOPT_NOBODY, !($options['return_body']));
        curl_setopt($ch, CURLOPT_SSLVERSION, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
        curl_setopt($ch,CURLOPT_TIMEOUT_MS,0);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
        $result = curl_exec($ch);

        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);

        curl_close($ch);

we have 9000 records to fetch
its taking 56 mins
To check execution time for each record I use curl_getinfo() function;
and each record take ~0.46 seconds!!
I want to reduce this seconds.
any luck it can reduce to 15 mins?

A: Try to set one more cURL option.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

Also try to use curl_multi_exec.

A: Use file_get_contents($url)
example with User Agent
<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>


Q: Realm from JSON in async in background I'd like to work to write Realm from JSON in async in background, but I can't understand why my code isn't work as must.
override func viewDidLoad() {
    super.viewDidLoad()

    myFunc()

}

and myFunc():
func myFunc() {

        let realm = try! Realm()

        // get file JSON from local device and write data from it to RealmDB
        if realm.isEmpty {

            //local file JSON
            let file = Bundle.main.path(forResource: "file", ofType: "json")!
            let url = URL(fileURLWithPath: file)
            let jsonData = NSData(contentsOf: url)!

            //Serialization JSON
            let json = try! JSONSerialization.jsonObject(with: jsonData as Data, options: [])

            DispatchQueue.main.async {

            realm.beginWrite()

            //Create data from JSON to our objects
            realm.create(DataRoot.self, value: json, update: true)

            try! realm.commitWrite()

            }
        }
    }

DB is creating, but next step (as I see) is in error:
  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return (transport.filter("id == 1").first?.routes.count)!
    }

So, I'd like to wait full writing DB in background (show progress view, for example) and go next step.

A: You have to check for optional in numberOfRows Method and do it like this
    func myFunc() {
        let queue1 = DispatchQueue(label: "com.appname.queue")
        queue1.async {
            let realm = try! Realm()
            // get file JSON from local device and write data from it to RealmDB
            if realm.isEmpty {

                //local file JSON
                let file = Bundle.main.path(forResource: "file", ofType: "json")!
                let url = URL(fileURLWithPath: file)
                let jsonData = NSData(contentsOf: url)!

                //Serialization JSON
                let json = try! JSONSerialization.jsonObject(with: jsonData as Data, options: [])
                realm.beginWrite()

                //Create data from JSON to our objects
                realm.create(DataRoot.self, value: json, update: true)

                try! realm.commitWrite()

                DispatchQueue.main.async {

                    self.tableview.reloadData()

                }

            }
        }
    }

    override func tableView(_ tableView: UITableView,     numberOfRowsInSection section: Int) -> Int {
        if let routes = transport.filter("id == 1").first?.routes {
            return routes.count
        }
            return 0
    }

A: To generally answer your question: the high level Realm feature you want to be using here is notifications.
You should be architecting your app in such a way that the data you want to use to back a view controller can be represented in a Realm query or notification, so that when the underlying data for a view or controller changes, you can perform the relevant view update actions.
There are some other problems with your code, such as potentially accessing a Realm instance from a different thread than the one on which it was created. I suggest you read more about this in Realm's Threading documentation.


Q: Meaning of $\log$ If you write $\log{x}$ rather than ${\log_a{x}}$ for some base $a$, does it have a particular meaning? Sometimes I see people leave off the base by mistake when posting questions and it seems from the comments they get that it doesn't simply mean "log of $x$ to some base but I haven't said which yet".  For example, does it indicate the complex logarithm?

A: In mathematics, this usually means log in base $e$.
In computer science, this sometimes means log in base $2$.
In natural sciences (such as chemistry) and high school, this usually means log in base $10$.
Finally, when it appears in big-O notation (such as $O(\log x)$), the base doesn't matter, since the difference is a multiplicative constant.
Edit (answering your edit): The complex logarithm is a different matter than bases. The complex logarithm is always taken in base $e$ (it doesn't make much sense otherwise), and the principal branch is usually denoted $\text{Log}$ with a capital L. Usually it is pretty clear from the context whether a complex logarithm is being discussed, since it must be handled with care, with its branch cut or with its special domain as a multi-valued function.

A: In many contexts the base doesn't make much, or any, relevant difference and thus can safely be omitted. When it does make a difference, context can determine the base (e.g., when talking about bit complexity, base $2$ makes most sense). In most mathematical contexts, the base, if omitted, is assumed to be $e$.


Q: How do I change the Created By for my crossrider plugin? When users install my browser it shows the plugin created by the name listed under my crossrider dev account.  I'd like to change that to my company name but the site won't let me change the name.  How can I change it to show my company name vs my first and last name?  Thanks

A: Email support@crossrider.com from the email address currently associated with the account. In the email, provide:

*

*Current Account Name: the name currently associated with the account

*Extension ID(s): One or more IDs of extensions in the account

*New Account Name: the desired name for the account

[Disclosure: I am a Crossrider employee]


Q: How to get device ID in angular js? I need to find the device ID on which my app is running. I am using angular js and ionic. Is there any way to obtain the device ID?

A: Option 1: Use AngularJS run
// Calling the rootScope to handle the  ondevice ready
angular.module('myApp').run(['$rootScope', function($rootScope) {
  document.addEventListener('deviceready', function() {
      $rootScope.$apply(function() {
          $rootScope.myVariable = "variable value";
          try {
            $rootScope.uuid = device.uuid; //always use device object after deviceready.**
            alert($rootScope.uuid);
            //onapploginx(uuid);
          } catch (e) {
            alert(e);
          }
          // Register the event listener
          document.addEventListener("backbutton", onBackKeyDown, false);
      });
  });
}]);

Option 2: Use JS only
define the onLoad in the body
<body id="main_body" ng-app='myApp' ng-controller='DemoController' onload="onLoad()">

call addEventListener for device ready and then call the function of onDeviceReady
function onLoad() {
  console.log("i am onload");
  document.addEventListener("deviceready", onDeviceReady, false);
}

// device APIs are available
//
function onDeviceReady() {
  try {
    var uuid = device.uuid; //always use device object after deviceready.**
    alert("uuidx:",uuid);
  } catch (e) {
    alert(e);
  }
}


Q: HttpWebResponses: How efficient is MemoryStream.CopyTo vs chunking? I'm running into a problem with downloading large JSON objects from an API. Usually, this documents are small in size, but occasionally they are quite large (100k+). This puts the large object heap into play and there are some performance concerns.
Here is the guts of the downloader method that returns the response bytes.
using (var httpWebResponse = (HttpWebResponse)request.GetResponse())
{
    byte[] responseBytes;
    using (var responseStream = httpWebResponse.GetResponseStream())
    {
        using (var memoryStream = new MemoryStream())
        {
            if (responseStream != null)
            {
               responseStream.CopyTo(memoryStream);
            }
            responseBytes = memoryStream.ToArray();
        }
     }
     return responseBytes;
 }

If the end goal is to get the contents of the webresponse into a byte array, is this the most efficient way to do this? In the past I would just read the stream in chunks. I've been told that this is less efficient than CopyTo for the 90% of the time (when the JSON response is sub-85k), but better for the other 10%.
I cannot seem to find a general consensus on this. Any input would be appreciated.


Q: python-shell problem with sync inside javascript I'm using python-shell to run a Python code that return some messages inside a JavaScript environment, but the messages come out of sync. The first message returns at the right moment, but then all other messages comes out together at the end, not one by one.
When I run the test.py alone the messages come in the right way, which possibly means that is not a problem with my python code. Despite all other messages is logged together, the time when they are executed inside the python code is right, what can be seeing by the time: inside each message.
But what happens in my browser environment is the message <2>FIRST TEST logged first, and then <3>TEST and <4>MORE TEST are logged together after 10 seconds.

This is my python code test.py:
import sys
import time
import threading

def test():
    start = time.time()
    end1 = time.time()
    print("<2>FIRST TEST time: {}".format(end1 - start))

    time.sleep(5)
    end2 = time.time()
    print("<3>TEST time: {}".format(end2 - start))

    time.sleep(5)
    end3 = time.time()
    print("<4>MORE TEST time: {}".format(end3 - start))

x = threading.Thread(target=test)
x.start()
sys.stdout.flush()

This is my JavaScript code execPyShell.ts:
const exec: () => void = () => {
    console.log('Start')
    let pyshell = new PythonShell('./engine/test.py');
    let newLogs: string[] = [];

    pyshell.on('message', function(message: string) {
        console.log(message);
    })

    pyshell.end(function (err: any) {
    if (err){
        throw err;
    };
        console.log('Finished');
    });
}

A: Solved! I forgot that I had to add
sys.stdout.flush()

After every print() called to force it to flush the buffer.