text:
Q: How to connect multiple On-Premise sites to Azure and connect Virtual Networks? I would like to be able to setup multiple Azure Virtual Networks, connect them together and also allow multiple On-Premises VPN routers to connect in to those Virtual Networks. Below is how I plan on setting up the networks.
Datacenter Virtual Network:
172.16.250.0/24 address space
172.16.250.0/25 subnet-1
172.16.250.128/29 gateway
-> Point-to-Site Connectivity: 10.0.253.0/24
-> Site-to-Site Connectivity: Datacenter Local Network: 10.0.250.0/24
Headquarters Virtual Network:
172.16.0.0/24 address space
172.16.0.0/25 subnet-1
172.16.0.128/29 gateway
-> Site-to-Site Connectivity: Headquarters Local Network: 10.0.0.0/24
Region1 Virtual Network:
172.16.1.0/24 address space
172.16.1.0/25 subnet-1
172.16.1.128/29 gateway
-> Site-to-Site Connectivity: Region1 Local Network: 10.0.1.0/24
So with this I want the Datacenter, Headquarters and Regional Virtual Networks to be connected. I then need for on-premise VPN routers to connect to the Headquarters and Regional Virtual Networks. How can I 1) get the VN's to talk to each other and 2) I have Cisco 881 routers and I'm using the following configs from Azure.
! Microsoft Corporation
! Windows Azure Virtual Network

! This configuration template applies to Cisco ISR 2900 Series Integrated Services Routers running IOS 15.1.
! It configures an IPSec VPN tunnel connecting your on-premise VPN device with the Azure gateway.

! ---------------------------------------------------------------------------------------------------------------------
! ACL rules
!
! Proper ACL rules are needed for permitting cross-premise network traffic.
! You should also allow inbound UDP/ESP traffic for the interface which will be used for the IPSec tunnel.
access-list 101 permit ip 10.0.0.0 0.0.0.255 172.16.0.0 0.0.0.255

! ---------------------------------------------------------------------------------------------------------------------
! Internet Key Exchange (IKE) configuration
!
! This section specifies the authentication, encryption, hashing, and Diffie-Hellman group parameters for the Phase
! 1 negotiation and the main mode security association.
crypto ikev2 proposal azure-proposal
  encryption aes-cbc-256 aes-cbc-128 3des
  integrity sha1
  group 2
  exit

crypto ikev2 policy azure-policy
  proposal azure-proposal
  exit

crypto ikev2 keyring azure-keyring
  peer 104.215.95.202
    address 104.215.95.202
    pre-shared-key
    exit
  exit

crypto ikev2 profile azure-profile
  match address local interface
  match identity remote address 104.215.95.202 255.255.255.255
  authentication remote pre-share
  authentication local pre-share
  keyring azure-keyring
  exit

! ---------------------------------------------------------------------------------------------------------------------
! IPSec configuration
!
! This section specifies encryption, authentication, tunnel mode properties for the Phase 2 negotiation
crypto ipsec transform-set azure-ipsec-proposal-set esp-aes 256 esp-sha-hmac
 mode tunnel
 exit

! ---------------------------------------------------------------------------------------------------------------------
! Crypto map configuration
!
! This section defines a crypto profile that binds the cross-premise network traffic to the IPSec transform
! set and remote peer.  We also bind the IPSec policy to the virtual tunnel interface, through which
! cross-premise traffic will be transmitted.  We have picked an arbitrary tunnel id "1" as an example. If
! that happens to conflict with an existing virtual tunnel interface, you may choose to use a different id.
crypto ipsec profile vti
  set transform-set azure-ipsec-proposal-set
  set ikev2-profile azure-profile
  exit

int tunnel 1
  ip address 169.254.0.1 255.255.255.0
  ip tcp adjust-mss 1350
  tunnel source
  tunnel mode ipsec ipv4
  tunnel destination 104.215.95.202
  tunnel protection ipsec profile vti
  exit

ip route 172.16.0.0 255.255.255.0 tunnel 1

Are there any configurations that need to be added or removed from this template to get the On-Premises VPN working?
Thanks for your help!

A: How can I get the VN's to talk to each other
You will need to create VNet-to-VNet VPN tunnels, this can be done by doing the following:

*

*In the Azure portal, create all the VNets you want, add the subnets to the VNets and the corresponding local networks in your LAN.

*Create Gateways for the VNets using Dynamic Routing VPN, Static Routing VPN will not work.

*Connect the VPN gateways to each other first, and then connect you LAN to ease the troubleshooting process if needed.

This is all very well documented here:
Configure a VNet-to-VNet connection in the Azure Portal and here too
VNet-to-VNet: Connecting Virtual Networks in Azure across Different Regions
Are there any configurations that need to be added or removed from this template to get the On-Premises VPN working?
You're in luck, you're device is supported with the Azure site-to-site VPN using dynamic routing, to insure that you can successfully connect your LAN to Azure, I would recommend going over the details in this page: About VPN devices for site-to-site virtual network connections
Unfortunately, I'm not an expert when it comes to Cisco routers, I will be unable to review the configuration you posted, but I can help you by providing the general guidelines to connect Azure to you VPN device:

*

*Once you setup the VNets using the steps above, Azure will be smart enough to create a script that you can download and use to setup your local VPN device.

*Read the manuals of you creating a VPN Dynamic tunnel from Cisco: http://www.cisco.com/c/en/us/support/docs/security-vpn/ipsec-negotiation-ike-protocols/46242-lan-to-lan-vpn-client.html

*Take a look at the Azure VPN samples for Cisco: https://msdn.microsoft.com/library/azure/dn133800.aspx?f=255&MSPPError=-2147217396#BKMK_ISRDynamic
I hope those are enough to help you, if not, I'm sure someone else with more experience in Cisco will be able to help you figure this out.

A: Okay, so I've made some progress.  I've gotten my on-premises equipment to connect up to Azure, I also have my virtual networks in Azure connecting to each other, but if I put a VM in one VNet and another in a different VNet I can not ping across the VNets.  Also I can't ping anything in the Azure VNets from the on-premises device.
So here's how it's all currently setup.
Virtual Networks
VNet-DataCenter: 172.16.250.0/24

*

*Local Networks: LNet-to-Headquarters (10.0.0.0/24), LNet-to-Region1 (10.0.1.0/24)

VNet-Headquarters: 172.16.0.0/24

*

*Local Networks: LNet-Headquarters (10.0.0.0/24), LNet-int-Headquarters (10.0.250.0/24, 10.0.1.0/24)

VNet-Region1: 172.16.1.0/24

*

*Local Networks: LNet-Region1 (10.0.1.0/24), LNet-int-Region1 (10.0.250.0/24, 10.0.0.0/24)

I have a VM in VNet-Headquarters and one in VNet-DataCenter, but I can't ping either machine.
I used the following article as a reference.  How to configure routing between Azure virtual networks?
Any help is appreciated!

A: Okay, I've rebuilt the entire network and again placed two VMs within two of the VNs, but still they can't ping anything, not even their local gateways.  So here's the setup.
I have three VNs created:

*

*VNet 1 - 10.0.250.0/24

*VNet 2 - 10.0.0.0/24

*VNet 3 - 10.0.1.0/24

I have four LNs created:

*

*LNet 1 - 10.0.0.0/24

*LNet 2 - 10.0.1.0/24

*LNet 3 - 10.0.250.0/24, 10.0.1.0/24

*LNet 4 - 10.0.250.0/24, 10.0.0.0/24

VNet 1 has two LNs attached to it, LNet 1 and LNet 2
VNet 2 has one LN attached to it, LNet 3
VNet 3 has one LN attached to it, LNet 4
VNet 1 has a VM in it with the IP 10.0.250.4.
VNet 2 has a VM in it with the IP 10.0.0.4.
I can not ping either VM from the other VM, so 10.0.0.4 can not ping 10.0.250.4 and visa versa.
Thanks!!

A: Pinging VMs in Azure is blocked at the Windows Firewall level, ensure you turn off the firewall on each VM during testing, once successful you can configure them to allow ICMP. Alternatively, check for connectivity using RDP instead (assuming it is enabled)


text:
Q: Oppo Phone removing Device Admin Permission In my application I am using Device admin permission, It is working fine in all devices but In Latest Oppo Phones F9, F7, F5 whenever user unlocks phone it askes to remove Admin permission Or Shows a dialogue to remove admin permissions of all applications,
My App is not working without admin permissions,
I am stuck here, looking for a solution.
Thanks

A: Disclaimer: I do not own an Oppo phone, though my older Xiaomi Redmi Note 4 had similar issues so this should be it.
Go to Settings/Security Center on your Oppo phone and disable "Permission Monitor." This should be what is causing the popups.
Source: Credit to Ameer Hamza Khan.

A: As I have found that, this is device issue, Oppo has added this security purpose
In this case for oppo f7 user has to ignore popup of permission.

redpajama_set_name: RedPajamaStackExchange


text:
Q: why won't run my react-native android app in my custom phone emulator it's worked but suddenly without any reason stop working
my error in cmd is this:
com.android.ddmlib.InstallException: Failed to establish session


text:
Q: php.ini does not exist in my apache/bin folder, but I'm getting an error? I've been trying to figure out how to resolve this error with all the new pages I create:
Server error!

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.

If you think this is a server error, please contact the webmaster.

Error 500

localhost
2011/11/28 13:36:56
Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1

Well, it all started when I increased the security on MySQL by setting some more passwords, I think.  I figured I'd get a better error report if I turned error reporting on in php.ini, but it's not in my /apache/bin folder.
Alright, so I have no idea what to do.  I've also got this line in xampp: MySQL database   DEACTIVATED.
Any idea what might be happening?  Also, please let me know if this should go to superuser.

A: If you're on Linux, try a "find", like this:
find / -name php.ini print

Another approach is to create a "phpinfo.php" in your Apache DocumentRoot folder, and let PHP tell you where you should put your php.ini:
<?php
  // Create this file in your Apache root,
  // then browse to http://localhost/phpinfo.php
  // Look for "Configuration File (php.ini) Path" in the resulting output
  phpinfo ();
 ?>

A: Use the find feature in Linux, as specified by paulsm4 to find php.ini.
Use ctrl+f in Windows and search for files and folders -> php.ini to find it in Windows.  I recommend you do this from your web server's root directory rather than from some other location; otherwise, it may fail.
If you're experiencing a 500 error, you should check your Apache log files.  They can be found in the /apache/logs folder in the file error.log, I believe.  I emptied the file and then caused the error to isolate it.  The information lead me to the answer.
In my case, the reason I was getting a 500 error was because my .htaccess file was referencing a .htpasswrd file that did not exist.  I changed the line of code in the .htaccess file that was targeting the .htpasswrd file to target an existing .htpasswrd file that I wanted to use.  I could have just as soon copied a properly formatted .htpasswrd file or made one from scratch, though.
I've read at multiple sources that 500 errors have many causes.  So, none of these steps are guaranteed to work for you.  If they do not, I wish you luck, and I hope that you will post a reply telling me how you fixed your 500 error, too--or, a link to a resolved question about a 500 error.


text:
Q: Deriving law of motion for Brownian motion I have a continuum of objects, all affected by Brownian motion with drift $\mu$ and variance $\sigma^2$. I want to find the mass of those that are moving upwards, which I will make more precise in the discrete-time approximation that follows.

Discretize a grid over a with step size $\Delta_a = \bar a - \underline a$. Time period is $\Delta_t = (\Delta a/\sigma)^2$. In the interior, $a$ increases with probability $1/2 (1 + \mu \Delta_a/\sigma^2)$, and decreases with probability $1/2 (1 - \mu \Delta_a/\sigma^2)$. This yields an expected value of $\mu \Delta_t$ with second moment $\sigma^2 \Delta_t$.

Now, what I am interested in, in discrete time, is separating the "upward-movers" from the "downward-movers", and compute the "speed" ($\Delta_a/\Delta_t$) for each of these.
For upward-movers, we have how much you move upwards X prob of moving upwards per unit of time:
$$\Delta_a \cdot \left[\frac{1}{2}(1 + \frac{\mu\Delta_a}{\sigma^2}) \right]/\Delta_t\\
= \frac{1}{2}\left[\sigma^2\frac{\Delta_t}{\Delta_a}  + \frac{\mu\Delta_a^2}{\sigma^2})\right]/\Delta_t\\
= \frac{1}{2}\left[\sigma^2\frac{\Delta_t}{\Delta_a} + \mu\Delta_t\right]/\Delta_t\\
= \frac{1}{2}\left[ \sigma^2\frac{1}{\Delta_a} + \mu\right]  $$
Now, when $\Delta_t \to 0$, we have $\Delta_a \to 0$, so the first term explodes. What am I missing?


text:
Q: What's the difference between volatile and UNSAFE.putIntVolatile() private static final long SEGSHIFT_OFFSET;
SEGSHIFT_OFFSET = UNSAFE.objectFieldOffset(
            ConcurrentHashMap.class.getDeclaredField("segmentShift"));
UNSAFE.putIntVolatile(this, SEGSHIFT_OFFSET, 32);

the code adove can be replaced code as follows?
private static volatile long SEGSHIFT_OFFSET = 0L;
SEGSHIFT_OFFSET = 32;

or can be replaced as follows?
private static synchronized long SEFSHIFT_OFFSET = 0L;
SEGSHIFT_OFFSET = 32;

A: I assume this code you have in some class which subclasses the ConcurrentHashMap class.
No, it cannot be replaced as you suggest. This code does very dangerous thing: it updates the package-private final field segmentShift of ConcurrentHashMap with the new value. SEGSHIFT_OFFSET is used to determine the offset of the segmentShift field within the class (number of bytes between this field location and the beginning of the object) in the memory. As this offset assumed to be the constant during JVM lifecycle, it's stored in the final field.
Your suggested replacements do completely different thing: just declare the field and change its value. This way you cannot change the value of inaccessible final segmentShift field. It's updated using the volatile semantic to put memory barrier after update, so other threads will see the updated value (though I still doubt whether it's a robust way to do this).
If you want to replace this code, you can try to use reflection, though this would not impose volatile semantics which is probably necessary in this case.
Note that this unsafe code will not work completely in JDK8, as the internal structure of ConcurrentHashMap is changed significantly and it has no segmentShift field anymore. If you want to upgrade to JDK8, then reflection will not help you either.
By the way there's an ongoing discussion about removing the Unsafe completely.


text:
Q: How to get image picker with jsonschema in reactjs Can anyone please tell a simple solution to get image picker in UI form using json schema. code snippet would be wonderful.
It would be really helpful.


text:
Q: how to make datagridview column as linktype I am fetching data and storing in datatable to display it in datatgridview ,How do I make 2nd column visitdate of datatable as of link type?
something like this
DataGridViewLinkColumn linkcol = new DataGridViewLinkColumn();
this.dataGridViewVisits.Columns[1].DefaultCellStyle = linkcol;

below is my code for displaying data in datagridview
cmd1 = new OleDbCommand("Select VisitNo,VisitDate,remark from Patient_Visit_Details WHERE Patient_ID=" + pid, con);
            dt = new DataTable();
            adp1 = new OleDbDataAdapter(cmd1);
            adp1.Fill(dt);
            this.dataGridViewVisits.DataSource = dt;
            DataGridViewLinkColumn linkcol = new DataGridViewLinkColumn();

A: Add this code after you have set the DataTable(dt) as your DataGridView's datasource.
foreach (DataGridViewRow row in dataGridViewVisits.Rows)
            {
                DataGridViewLinkCell linkCell = new DataGridViewLinkCell();
                linkCell.Value = row.Cells[1].Value;
                row.Cells[1] = linkCell;
            }

It'll surely work.. :)

A: Handle the DataBindingComplete event of datagridView like the following.
  private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                r.Cells[1] = new DataGridViewLinkCell();
            }
        }

A: for Vb.Net geeks...
For Each typeCell As DataGridViewRow In FlxInvTransaction.Rows
    Dim linkCell As New DataGridViewLinkCell
    linkCell.Value = typeCell.Cells(2).Value
    typeCell.Cells(2) = linkCell
Next

A: Hi,
You just need to create HyperLink column in GridView control using smart navigation and set values as like below...

 <asp:HyperLinkField DataNavigateUrlFields="VisitDate"
 DataTextField="VisitDate"
 DataNavigateUrlFormatString="Default3.aspx?VisitNo={0}&visitDt={1}" />

Thank you,
Vishal Patel


text:
Q: Incorporating PYQT GUI significantly increases loop time I have been working on converting a program which took a CSV file as inputs for a modelling application that iterated over several thousant timesteps and and did calculations on each. In this format, the program took 1-2min max to complete. During the calculation I utilized a simple TKinter progress bar to indicate simulation progress.
With the completed UI using PyQT5, the calculation time slows down significantly. It now takes 30+ minutes to calculate.
Things I have tried:
QT threading: I pushed the calculation to a separate worker thread as outline here: https://realpython.com/python-pyqt-qthread/
class Simulator(QObject):
    def __init__(self,inputs):
        super(Simulator, self).__init__()
        self.inputs = inputs

    finished = pyqtSignal()
    progress = pyqtSignal(int)

    def run_task(self):
        print(self.inputs)
        simEVs(self.inputs)
        self.finished.emit()

Hiding QWidgets & Blocking signals: for another project I found that updating a QTable widget, slowed down the program due to a multitude of signals being sent, so blocking signals for the widget increased performance there. Here I tried blocking signals and hiding all child elements of my UI during the simulation to no effect.
def sleep_ui(self):
    children = self.findChildren(QWidget)
    for child in children:  #ignore the double indent here
            child.blockSignals(True)
            child.setUpdatesEnabled(False)
            child.hide()
def wake_ui(self):
    children = self.findChildren(QWidget)
    for child in children:
        child.blockSignals(True)
        child.setUpdatesEnabled(True)
        child.show()

In other code implementations, I've deleted the ui window and recreated it once the calculation has completed, but I'm trying to avoid that here.
here is an example of what I am talking about:
longsim() takes 0.0029883 secs with the UI and 0.0009970 secs without, an almost 300% increase in computation time.
longsim.py:
import pyqtgraph as pg
import numpy as np
import matplotlib
matplotlib.use('Qt5Agg')
import time
pg.mkQApp()

def longsim():
    t = time.time()
    # do stuff
    tmax = 365*24*4
    timev = np.linspace(0,tmax)

    for i in timev:
        for i in timev: # an example loop with some placeholder calculations
            output = i*100

    elapsed = time.time() - t
    print(elapsed)

stackexchange.py:
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import os
import matplotlib

from PyQt5 import QtWidgets, QtGui

from longloop import longsim
matplotlib.use('Qt5Agg')

pg.mkQApp()

path = os.path.dirname(os.path.abspath(__file__))
uiFile = os.path.join(path, 'Example.ui')
WindowTemplate, TemplateBaseClass = pg.Qt.loadUiType(uiFile)

class MainWindow(TemplateBaseClass):
    def __init__(self):
        TemplateBaseClass.__init__(self)
        self.setWindowTitle('window')

        # Create the main window
        self.ui = WindowTemplate()
        self.ui.setupUi(self)

        self.ui.buttonBox.clicked.connect(self.clicked)
        self.show()

    def clicked(self):
        longsim()

win = MainWindow()

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

here is the UI file:
example.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>640</width>
    <height>480</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <widget class="QDialogButtonBox" name="buttonBox">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>440</y>
     <width>621</width>
     <height>32</height>
    </rect>
   </property>
   <property name="orientation">
    <enum>Qt::Horizontal</enum>
   </property>
   <property name="standardButtons">
    <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>buttonBox</sender>
   <signal>accepted()</signal>
   <receiver>Dialog</receiver>
   <slot>accept()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>248</x>
     <y>254</y>
    </hint>
    <hint type="destinationlabel">
     <x>157</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>buttonBox</sender>
   <signal>rejected()</signal>
   <receiver>Dialog</receiver>
   <slot>reject()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>316</x>
     <y>260</y>
    </hint>
    <hint type="destinationlabel">
     <x>286</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>

A: Thank you all for the suggestions, As is usually the case for things like this the bug was elsewhere. After fixing a value that should have been a percentage (0-1 instead of 0-100) the loop runs as it should. no issues with increased loop times as of yet.


text:
Q: Why is std::unique_ptr much slower than standard pointer... before optimizations? Lesson learned, always use optimizations when doing benchmarks...

I decided to look at std::unique_ptr as an alternative for my program. The reasons as to why are not important.
After using compiler optimizations, they seems to take equivalent amounts of time.
How I tested:
time_t current_time;
time(&current_time);
srand((int)current_time);
//int* p0 = new int[NUM_TESTS];
//int* p1 = new int[NUM_TESTS];
std::unique_ptr<int[]> u_p0{ new int[NUM_TESTS] };
std::unique_ptr<int[]> u_p1{ new int[NUM_TESTS] };
for (unsigned i = 0; i < NUM_TESTS; ++i){
    u_p0[i] = rand(); // Use p0 and p1 for the standard ptr test
    u_p1[i] = rand();
}
int result;
auto start = std::chrono::steady_clock::now();
for (unsigned index = 0; index < NUM_TESTS; ++index){
    result = u_p0[index] + u_p1[index]; // Use p0 and p1 for standard ptr test
}
auto end = std::chrono::steady_clock::now();
double duration = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();
printf("time: %f\n", duration);

My environment:

*

*Windows 8.1 64 bit

*MSVC compiler in Visual Studio 2013. Using Release.

*Intel 4790k (standard clock)

*1600 MHz RAM

My results (using optimized compilation):
// NUM_TESTS = 1,000,000

/*
STD:
    0.001005
    0.001001
    0.001000
    0.001000
    0.001015
*/
/*
unique_ptr:
    0.001000
    0.001000
    0.000997
    0.001000
    0.001017
*/

A: Because "standard compiler flags" means you're compiling without optimizations enabled.
std::unique_ptr is a thin wrapper around a raw pointer. As such, when dereferencing it, it goes through a very simple forwarding function, which the compiler is able to optimize away. But it only does that if optimizations are enabled. If they are, then it can eliminate the overhead of going through the wrapper, so performance will be the same as if you'd just used a raw pointer.
But if you don't ask the compiler to optimize your code, then every time you access the pointer, it has to go through the small wrapper function to get to the actual internal pointer.
Always, always enable optimization when benchmarking code.


text:
Q: How to get FireWire details with WMI? I have to get the firewire details from user PC before installing the application, I'm able to get the Win32_1394Controller Object using WMI query, so I get most of the details.
But my main objective is to get the what firewire connector user installed on their machine. Like is it a 4,6 or 9 pin connector?
Is there any possibility I can get these details?

A: I don't think so. I hand-built my machine; how would WMI guess what ports exist? The difference between 4 and 6 pin connectors is a pair of power pins.


text:
Q: Automatic Drag and Drop I need help with mouse drag and drop. I would like to make something like mouse macro. You specify the XY coordinates of cursor and then drag something to another XY coordinates automatically. Is it possible?
I know how to simulate Mouse Click and Mouse Movement, but I am not sure with the Mouse Dragging.

A: WM_MOUSEDOWN, WM_MOUSEMOVE, WM_MOUSEUP -- use Spy++ to view windows messages


text:
Q: how do I get a list of all the members of a group using VBA? I found some code on the internet and tinkered with it to list all the members of a group in Active Directory.
my final result must be similar to this:
E.g.
Group 1, User 1
Group 1, User 2
Group 2, User 1
Group 3, User 3

Etc
Function GetGroupUsers(ByVal strGroupName As String) As String

    Dim objGroup, objDomain, objMember
    Dim strMemberlist As String, strDomain As String
    Set objDomain = GetObject("LDAP://rootDse")
    strDomain = objDomain.Get("dnsHostName")

    Debug.Print strGroupName
    Debug.Print strDomain

    Set objGroup = GetObject("WinNT://" & strDomain & "/" & strGroupName & ",group")
    Debug.Print objGroup

    Dim i
    i = 0

    For Each objMember In objGroup.Members
        strMemberlist = strMemberlist & "," & objMember.Name
        Debug.Print strMemberlist
        i = i + 1
        Debug.Print i
    Next objMember
    ' strip off the leading comma
    GetGroupUsers = Mid$(strMemberlist, 2)

End Function

A: Each member can have couple of groups
try look around this
Sub testLookup()
    PrintMemberOf Environ("USERNAME")
End Sub

Public Sub PrintMemberOf(samAccountName As String)
    Dim sDomain     As String
    Dim groups      As Variant
    Dim x           As Long
    'Get the Domain from the Current logged on user
    Set dd = CreateObject("ADSystemInfo")
    With CreateObject("ADSystemInfo")
        sDomain = .DomainShortName
    End With
    'Assign the groups to an array
    groups = GetMembers(GetDN(samAccountName, sDomain))
        'Print each group
        For x = LBound(groups) To UBound(groups)
            Debug.Print groups(x)
        Next x
End Sub

Public Function GetMembers(strDN As String) As Variant
'Function to return the memberof property
    With GetObject("LDAP://" & strDN)
        GetMembers = .memberOf
    End With
End Function

Function GetDN(ByVal samAccountName, ByVal sDomain)
'Function to return the DN from a given samAccountName and Domain
    With CreateObject("NameTranslate")
        .Init 1, sDomain
        .Set 3, sDomain & "\" & samAccountName
        GetDN = .Get(1)
    End With
End Function

Function getADAll()
    UserName = Environ("USERNAME")

    Set RootDSE = GetObject("LDAP://RootDSE")
    Base = "<LDAP://" & RootDSE.Get("defaultNamingContext") & ">"
    'filter on user objects with the given account name
    '"samAccountName,givenName,sn,displayName,mail,userPrincipalName,l,c,mobile,facsimileTelephoneNumber,info,title,department,company,manager"
    attr = "samAccountName,givenName,sn,displayName,mail,userPrincipalName,l,c,mobile,facsimileTelephoneNumber,info,title,department,company,manager"
    fltr = "(&(objectClass=*)(objectCategory=Person))"

            '"(sAMAccountName=" & UserName & "))"

    scope = "subtree"

    Set conn = CreateObject("ADODB.Connection")
    conn.Provider = "ADsDSOObject"
    conn.Open "Active Directory Provider"

    Set cmd = CreateObject("ADODB.Command")
    Set cmd.activeconnection = conn
    cmd.CommandText = Base & ";" & fltr & ";" & attr & ";" & scope

    Set rs = cmd.Execute
    strArr = Split(attr, ",")
    ThisWorkbook.Worksheets("Data").[A1].Resize(1, UBound(strArr)) = strArr
    y = 2
    Do Until rs.EOF

        For i = 0 To rs.Fields.Count - 1
            ThisWorkbook.Worksheets("Data").Cells(y, i + 1).Value = rs.Fields(i).Value
        Next i
        y = y + 1
      rs.movenext
    Loop
    rs.Close

    conn.Close
End Function


text:
Q: boost filesystem canonical path is not valid after conversion to const char * I am trying to transform a relative path and convert it to absolute to pass to SQLite using boost filesystem. This is supposed to work correctly for windows and linux
    boost::filesystem::path path("../../data/dominion");
    boost::filesystem::path file("dominion.db");
    boost::filesystem::path canonical = boost::filesystem::canonical(dataPath / file);

canonical returns
   m_pathname=L"D:/Users\\me\\Documents\\tonkatsu\\data\\dominion\\dominion.db"

As you can see the beginning of the path "D:/" is not correct. I also tried to call normalize() on it without success
Is there a way to remedy to this ?

A: Despite not being standard practice, forward slashes are also accepted on Windows, that's why boost isn't forcing the conversion.
However, some libraries won't accept forward slashes. boost::filesystem::path::make_preferred()[1] is meant to solve such situations, by converting the path to the system's preferred representation (i.e. using backslashes on Windows).
[1] This older reference makes that behaviour more obvious
As discused below, while (most of) the Windows API accepts forward slashes, and even a mixture of forward and backslashes, some user interfaces even on applications included in Windows don't.


text:
Q: Neo4j doesn't obey my database location setting When open up the Neo4j Community Edition program, it gives me an option to choose my database location.

I chose the path D:\Program Files (x86)\Neo4j.
When I look at the database information in the browser, I find that this is not where the database is actually located.

It seems to ignore my choice and always put the database in C:\Users\Peter\Documents\Neo4j\default.graphdb. Is there a way I can actually change the database location?

A: I just tested it and it worked for me.
I chose the new directory directly after install though. But also after choosing a different directory it honored my selection.
Did you have an old installation or a fresh install?


text:
Q: Software watchdog timer in Windows I'd like to create a simple watchdog timer in Windows, which will invoke a callback if certain time elapses since the last timer reset.
I thought of using a timer queue timer, but it seems that I need to call DeleteTimerQueueTimer each time I want to "postpone" the timer:
// This is called whenever data is received from a device.
// If not called within a certain period, timerCallbackFn will
// be invoked on a separate thread.
void resetWatchdog(void)
{
    if (_timer->handle != NULL)
    {
        // cancel previous timer
        DeleteTimerQueueTimer(NULL, (HANDLE)_timer->handle, NULL);
        _timer->handle = NULL;
    }

    // create new "one shot" timer
    CreateTimerQueueTimer(&_timer->handle,
        NULL,
        timerCallbackFn,
        _timer,
        _timer->intervalMs,   // fire once, after the specified interval
        0,                    // not periodic
        0);
}

Is this the correct approach? Do I need to use delete/create each time? Or is this the wrong timer for the job altogether?


text:
Q: ASP.NET Using slash in alert() I would like to prompt the path of the excel file to the user. But I cannot include slashes in the alert function. Here goes my code that works:
Dim sb As New System.Text.StringBuilder()
sb.Append("<script type ='text/javascript'>window.onload=function(){alert('C:')};</script>")

However, because I need to alert user regarding the path, I need to put e.g. C:\Program Files\New Folder. But when I insert the slash '\' the alert() will not work. Please guide me. Thanks in advance!

A: You need to escape the slash, like this:
'C:\\\\'

This is because slashes in strings are - in most languages - used to escape special characters, such as, for example, in a newline:
\n

So, if you need the slash to be written out verbatim, you need to escape the slash itself. You need to do this twice - once for C# to escape it and write out 'C:\\' which will then be escaped by Javascript, producing C:\ in your alert.
Alternatively, you can escape it once and use the "verbatim" modifier, which will treat the escape character as a literal backslash instead:
sb.Append(@"<script type ='text/javascript'>window.onload=function(){alert('C:\\')};</script>")


text:
Q: Does inside "if" statement change running time of algorithm? I have written the running time based on my calculation in red color on the picture. But I don't know what would be for that IF statement as well as it's body's running time. Will that IF condition's running time would be n x n ? Because each time in the inner loop, it would be evaluated. Isn't it? What about it's body's?

A: You need to take into account two different parameters, m and n. The outermost loop executes m times, and the inner loop executes n times. The complexity, therefore, is θ(mn).
Note that the if-statement and its body are executed in constant time.


text:
Q: How To Profile Stored Procedures I am using SQL Server 2012 and was wondering how to profile stored procedures
For instance can profiler capture each individual SQL statement in a stored procedure, what it is, and how long it takes to run etc?
I am trying to diagnose merge replication stored procedures, and this must be captured a part of a full run of the merge agent. It doesn't seem possible to grab the stored procedure with performance issues and run it again because at that point it is not slow.

A: Kevin's answer describes what events to capture in SQL Trace/SQL Profiler. To expand on that answer a bit - SP:StmtCompleted will show you each statement within a stored procedure being completed, as it sounds.
Also if you are on a busy system and trying to diagnose a performance issue you should be careful with SQL Profiler. SQL Profiler is much slower than tracing to a file or using Extended Events. This blog post by Jonathan Kehayias shows about a 90% overhead on a system's performance from using SQL Profiler and about a 10% overhead from tracing to file. Less for Extended Events. That is why it is typically recommended to not run SQL Profiler itself whil
While this information is available through Extended Events, I would suggest still using SQL Trace (the technology behind SQL Profiler) but tracing to a file instead (if you wanted to invest in learning and using Extended Events this would be the way to go, in a future version of SQL Server SQL Trace will be gone and all we'll have is Extended Events) . I would also suggest you filter through the Column Filters button out as much background noise as possible to make sure you are only capturing what is necessary. You can setup your trace with the Profiler tool using the steps Kevin describes in his good answer and then add a filter from that same GUI. Then you can export the trace as a script and run that script on SQL Server tracing to a file on a folder that doesn't contain database or transaction log files. To export, you would simply setup your trace, run it for a few seconds to just make sure you are capturing what you want, stop it and then go to the menu bar and File -> Export -> Script Trace Definition and save the file. Then open that file in a new query window on the server you intend to trace. You can see more about the options and definitions of this script you created by looking at the help articles for the various stored procedures used in that script you just created by starting here.
If you have time and want to learn, you can also read some articles on Extended Events and see how to capture the information as well. Jonathan Kehayias is a great resource for blog posts when you are ready to start there.

A: You can capture the individual statements in a stored procedure through SQL Server Profiler.  To do this, in your Events Selection tab, click the "Show all events" checkbox.  Then, scroll down to the Stored Procedures category and check the box next to SP:StmtCompleted.  If you also have the SQL:BatchStarted and SQL:BatchCompleted events selected, you can get a beginning-to-end picture of a stored procedure run, tying it all together by SPID.
It might also help to look at the plan cache to see if you can get a query plan for your slowly-performing procedure.  You could start with something like this:
SELECT
    OBJECT_NAME(st.objectid,st.dbid) AS ObjectName,
    cp.usecounts AS ExecutionCount,
    st.TEXT AS QueryText,
    qp.query_plan AS QueryPlan
FROM
    sys.dm_exec_cached_plans AS cp
    CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
    CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) AS st
WHERE
    cp.objtype = 'Proc'
    AND OBJECT_NAME(st.objectid,st.dbid) = 'YourStoredProcedure';


text:
Q: Why wrap an IO result in IO Monad In Haskell we have a function readFile :: FilePath -> IO String. My question while understanding monad is why wrap it in IO? Couldn't we just have written function like these:
(lines.readFile) path

Rather than
(readFile >>= lines) path

What benefit does the IO wrapper provide?

A: Haskell expressions are referentially transparent. This means that if readFile would really have a type of FilePath -> String, then expression readFile "a.txt" would always yield the same result. Even if you read the file, then change it, and then read again, you will get the contents in its first state.
Thus, we need to distingush between values and actions, and this is what IO is for. It doesn't let you use the result readFile "a.exe" in other expressions until you perform an action associated with it. As a consequence, after changing your file you have to perform the reading action again, to get file contents, and because of that you will able to see the changes.

A: We write functions that create computer programs
It should be noted that Haskell is a functional programming language. Functions, in the mathematical sense, always produce the same values for the same inputs.
Now this requirement to always produce the same result constrains things quite a bit, since a function to read a file would somehow have to produce the same result every time, even if the file was later changed. That's obviously not what we really want.
There is, however, a way to make a functional programming language that can handle reading a changing file. What you do is to write a function that produces some action the computer should perform. So you might perform an action composed of the following steps:
Read the file
Break it into lines
Change the even-numbered lines to uppercase
Output the lines to the screen

These four actions aren't performed yet. They're just a sequence of actions that we might perform. A function can return that exact same sequence of potential actions every time it's called, which makes it a proper mathematical function.
The main :: IO a function in Haskell returns the action that the program should perform. It always returns the same action, making it a proper mathematical function. When the program is run, the computer evaluates the main function, producing the action the computer should perform, and the computer then executes the action.
Do notation
Do notation takes the strangeness out of the process, giving you the feel of a much more standard programming language. You have three options:

*

*Perform an action and do nothing with its results

*Perform an action and store its results

*Process data using only functions (no actions)

These are done in the following ways, respectively:

*

*action args

*result <- action args

*let result = f . g . h . whateverCalculation $ value
This is similar to an imperative language like C where you do, respectively:

*

*action(args);

*result = action(args);

*result = f(g(h(whateverCalculation(value))));

A: For (lines.readFile) path to work, the type of readFile would need to be FilePath -> String. That, however, doesn't make sense in Haskell. A Haskell function is supposed to always produce the same results when given the same arguments. If the result type readFile was String, however, that would not happen, as readFile "foo.txt" would have to, for any useful implementation of such a readFile, produce different strings depending on the contents of the foo.txt file.
The Haskell solution to this issue is giving readFile the type FilePath -> IO String. An IO String is not a string, but a program that can be executed by the computer and that, when executed, somehow materialises a String into memory. While the String thus produced might be different each time the program is executed, the program itself remains the same, and therefore readFile always returns the same results when given the same arguments (and so, for instance, readFile "foo.txt" is always the same program).
This trick of manipulating a program that produces an I/O-dependent result instead of the result itself only works if the I/O-dependent result is kept opaque; that is, if there is no way of directly extracting it. In other words, there cannot be, for instance, an IO String -> String function -- for one, it would allow us to implement a readFile with the inappropriate type FilePath -> String that we have discussed above. There are, however, indirect ways of using the I/O-dependent result that do not lead to trouble. One of them is using it to create a second program, whose I/O-dependent result is just as opaque as the first one was. The Monad interface allows us to express this usage pattern:
(>>=) :: Monad m => m a -> (a -> m b) -> m b

Specialising (>>=) to IO, we get:
(>>=) @IO :: IO a -> (a -> IO b) -> IO b

The first program has type IO a, and the function that produces the second program using the I/O-dependent result of the first one has type a -> IO b. The result of (>>=) is a program which executes the first program and the second, newly generated, one in sequence. For instance...
readFile "foo.txt" >>= putStrLn

... is a program which reads the contents of foo.txt and then displays these contents.

P.S.: With respect to your example involving lines, it is worth noting that both (readFile >>= lines) path, as you have written it,  and (\p -> readFile p >>= lines) path are rejected by the type checker. Something that does work is:
(fmap lines . readFile) path

In it, we are making indirect use of the file contents in a different way. If we have a program which produces an I/O-dependent result, we can turn it into a program which produces a modified version of this result. That is done through fmap, from the Functor class:
fmap :: Functor f => (a -> b) -> f a -> f b

Or, specialising to IO:
fmap @IO :: (a -> b) -> IO a -> IO b


text:
Q: Invalid postback or callback argument error when using webservice to populate Dropdownlist I have a drop down list on my page. The onchange event of this dropdownlist calls a web service using javascript/jquery. The webservice returns data that populates ANOTHER drop down list. When I do this and try to submit my form I get an invalid postback or callback error.
I know why it is occurring but cannot figure out how to stop this error. I found a few solutions about putting <pages enableEventValidation="false"/> in the web config. that is unfortunately not an option. Company doesn't allow it.
What may make it even trickier to solve is that these drop downs are all located in a control. Not it's own specific aspx page. Does anyone have any idea how to solve this?
Another thing that could make it trickier is that I have no idea what the ID of the control is. We use a framework here at work that gives the control added to the page some weird whacky ID when it gets added. Is this error even possible to avoid given all these constraints?
Thanks!

A: I had this issue as well and tried all the different solutions mentioned across multiple sites but nothing worked.
In the end I tracked down the control, a dropdown list that was causing the issue. The problem was to do with the data being used to populate it. I was reading rows from a database and the issue was that one of the rows on the table had a carraige return. Once I deleted that it resolved my problem.
Hope this helps someone.

A: Have you considered making your second DropDownList that is filled dynamically a basic HTML select list instead of using a asp:DropDownList?  You could then check the posted value server side manually although you would have to handle any PostBack refreshes.
To address your other point about the control, that is not really a problem if you are using a asp:DropDownList.  You can just embed the ClientID in the javascript with:
$('#<%= yourDDL.ClientID %>')

Or you could assign it a unique class and use the class selector in JQuery:
$('.yourUniqueClassForTheDDL')

Hope that helps.  If not, just leave a comment :)


text:
Q: tensorboard "No scalar data was found." This is my first time using the tensorboard.
I've followed many tutorials, but the result that comes back to me is the same as the attached image below.

This is the code I wrote using the tensorboard.
self.writer = SummaryWriter('SimCLR_Code/SimCLR/runs')

...

def train(self, train_loader):
        scaler = GradScaler(enabled=self.args.fp16_precision)

        sess = tf.Session()
        self.writer = tf.summary.FileWriter('./runs/graphs', sess.graph)
        #saver = tf.train.Saver(tf.global_variables())
        #ckpt = tf.train.get

        # save config file
        save_config_file(self.writer.log_dir, self.args)

        n_iter = 0  #global optimization step
        logging.info(f"Start SimCLR training for {self.args.epochs} epochs.")
        logging.info(f"Training with gpu: {self.args.disable_cuda}.")

        for epoch_counter in range(self.args.epochs):
            for images, _ in tqdm(train_loader):
                images = torch.cat(images, dim=0)

                images = images.to(self.args.device)

                with autocast(enabled=self.args.fp16_precision):
                    features = self.model(images)
                    logits, labels = self.info_nce_loss(features)
                    loss = self.criterion(logits, labels)

                self.optimizer.zero_grad()
                scaler.scale(loss).backward()

                scaler.step(self.optimizer)
                scaler.update()

                if n_iter % self.args.log_every_n_steps == 0:
                    top1, top5 = accuracy(logits, labels, topk=(1, 5))
                    self.writer.add_scalar('loss', loss, global_step=n_iter)
                    self.writer.add_scalar('acc/top1', top1[0], global_step=n_iter)
                    self.writer.add_scalar('acc/top5', top5[0], global_step=n_iter)
                    self.writer.add_scalar('learning_rate', self.scheduler.get_lr()[0], global_step=n_iter)

                n_iter += 1

                # warmup for the first 10 epochs
                if epoch_counter >= 10:
                    try:
                        self.scheduler.step()
                    except ZeroDivisionError:
                        print("ZeroDivision")
                logging.debug(f"Epoch: {epoch_counter}\tLoss: {loss}\tTop1 accuracy: {top1[0]}")  #훈련과정 출력

        logging.info("Training has finished.")
        # save model checkpoints
        checkpoint_name = 'checkpoint_{:04d}.pth.tar'.format(self.args.epochs)
        save_checkpoint({
            'epoch': self.args.epochs,
            'arch': self.args.arch,
            'state_dict': self.model.state_dict(),
            'optimizer': self.optimizer.state_dict(),
        }, is_best=False, filename=os.path.join(self.writer.log_dir, checkpoint_name))
        logging.info(f"Model checkpoint and metadata has been saved at {self.writer.log_dir}.")

        # merged = tf.summary.merge_all()
        # writer = tf.summary.FileWriter

        self.writer.flush()
        self.writer.close()

And here is my file routes

I've been thinking about it for several days, but there's no progress.
Please give me a lot of advice.


text:
Q: Can't use many2many field in attrs? I got problem while using many2many in attrs, it's fine with domain but got error while using in attrs. Do we have any solution or workaround for this issue?
<field name="visible_fields" widget="many2many_tags"/>
<field name="create_uid" attrs="{'invisible': [('id','not in', visible_fields or False)]}"/>

A: I don't think the 'or operation' inside the right branch can be parsed. I would try something like this:
<field name="create_uid" attrs="{'invisible': ['|',('id','not in', visible_fields), ('id','=',False)]}"/>


text:
Q: Desigine a NFA but not working I designed this NFA - where I input a string, and the output is Accepted if this NFA accept it else Not accepted.

My code is here -
#include <stdio.h>
#include <stdlib.h>

int accepted = 1;

struct node
{
    char first, second;
    struct node *left, *right;
};

int main()
{
    struct node *stage, *start, *temp;
    char A[50000], data;
    printf("String: ");
    gets(A);
    int i;
    for(i=0; i<strlen(A); i++)
    {
        if(i==0)
        {
            stage=(struct node*)malloc(sizeof(struct node));
            if(A[i] == '0')
            {
                stage->first = 'B';
                stage->second = 'A';
            }
            else if(A[i] == '1')
            {
                stage->first = 'A';
                stage->second = '\0';
            }
            stage->left = '\0';
            start = stage;
            temp = stage;
            stage->right = '\0';
        }
        else
        {
            stage=(struct node*)malloc(sizeof(struct node));
            temp->right = stage;
            stage->left = temp;
            if(A[i] == '0')
            {
                if(temp->first = 'A')
                {
                    stage->first = 'B';
                    stage->second = 'A';
                }
                else if(temp->first = 'B')
                {
                    stage->first = '\0';
                    stage->second = '\0';
                }
                else if(temp->first = 'C')
                {
                    stage->first = '\0';
                    stage->second = '\0';
                }
                else if(temp->first = '\0')
                {
                    while(1)
                    {
                        stage = stage->left;
                        temp = stage->left;
                        stage->right = '\0';
                        i--;
                        if(i == 0)
                        {
                            accepted = 0;
                            break;
                        }
                        if(stage->second != '\0')
                        {
                            stage->first = stage->second;
                            stage->second = '\0';
                            break;
                        }
                    }
                }
            }
            else if(A[i] == '1')
            {
                if(temp->first = 'A')
                {
                    stage->first = 'A';
                    stage->second = '\0';
                }
                else if(temp->first = 'B')
                {
                    stage->first = 'C';
                    stage->second = '\0';
                }
                else if(temp->first = 'C')
                {
                    stage->first = 'C';
                    stage->second = '\0';
                }
                else if(temp->first = '\0')
                {
                    while(1)
                    {
                        stage = stage->left;
                        temp = stage->left;
                        stage->right = '\0';
                        i--;
                        if(i == 0)
                        {
                            accepted = 0;
                            break;
                        }
                        if(stage->second != '\0')
                        {
                            stage->first = stage->second;
                            stage->second = '\0';
                            break;
                        }
                    }
                }
            }
            temp = stage;
            stage->right = '\0';
        }
    }
    temp = start;
    printf("\n");
    while(1)
    {
        printf("%c => ", temp->first);
        temp = temp->right;
        if(temp->right == '\0')
        {
            data = temp->first;
            break;
        }
    }
    if(accepted && data == 'C') printf("\n\nAccepted.\n");
    else printf("\n\nNot accepted.\n");
    return 0;
}

Please help me to find, what's wrong there.


text:
Q: An arithmetic sequence "The sum of the first $13$ terms of an arithmetic sequence is $-234$ and the sum of the first $41$ terms is $-780$. Find the $27^\text{th}$ term of the sequence."
The $S_n=\frac n2(2a+(n-1)d)$ formula ($S_n$ represents the sum of the first to $n^\text{th}$ terms) only gives me fractional values for $a$ (which is the first term) and $d$, which is the common difference. Are there other viable methods?

A: Yes, $a$ and $d$ are not integers. To be precise,$$a=-\frac{720}{41}\text{ and }d=-\frac3{41}.$$
What exactly is your question? You already know that they are fractions. Do you expect to get a different answer if you use another method?

A: Method$\#1:$
HINT:
If we put $n=13,41$ we get two simultaneous equations in $a,d$
Solve for them.
Do you how to calculate the $26$th term?
Method$\#2:$
$$S_m=\dfrac m2\{2a+(m-1)d\}$$
$$S_n=\dfrac n2\{2a+(n-1)d\}$$
$$\dfrac12\left(\dfrac{S_m}m+\dfrac{S_n}n\right)=a+\dfrac{(m+n-2)d}2$$
Now the $r$ term $$T_{r+1}=a+rd$$
$\implies 2r=m+n-2$
Here $m=13,n=41\implies r=?$

A: $a_1$ and $d$ are unknown, but we know:
$\frac{13}{2}(a_1 + a_{13}) = -234 \implies a_1 + a_{13} = - \frac{234\times 2}{13} = -36$
and also $\frac{41}{2}(a_1 + a_{41}) = -780 \implies a_1 + a_{41} = -38\frac{2}{41}$
and also $a_{13}= a_1 + 12d$
and $a_{41} = a_1 + 40d$.
So we get two linear equations in two variables, by  substiting the last two into the first two. There is no problem with fractions, or even arbitrary reals being used as $a_1$ or $d$. That some sums of fractions are integers is OK, it doesn't mean all solutions are integers.


text:
Q: How do I determine if a unit has been compiled into a Delphi program? I want to be able to determine if a particular unit has been compiled into a Delphi program, e.g. the unit SomeUnitName is part of some of my programs but not of others. I would like to have a function
function IsSomeUnitNameInProgram: boolean;

(which is of course not declared in SomeUnitName because in that case it would always be included) that at runtime returns true, if the unit has been compiled into the program, and false, if not.
My thoughts so far have gone along the lines of using the jcl debug information (compiled from a detailed map file) which I basically add to all my programs to determine this information, but I would prefer it, if jcl were not required.
Adding code to SomeUnitName is not an option.
This is currently for Delphi 2007 but preferably should also work for Delphi XE2.
Any thoughts?
some background on this since @DavidHeffernan asked:
This is not only for one program but for more than 100 different ones. Most of them are used internally but some also get delivered to customers. Since we use quite a few libraries, some bought others under various open source licenses, I wanted to be able to add a "credits" tab to the about box which displays only those libraries actually compiled into the program rather than all of them. Thanks to the answer from TOndrej this works now exactly as I wanted it to:
The code checks for a unit which is always linked if a library is used by the program and if it is there, it adds the library name, the copyright and a link to it to the about box.

A: This function will return the list of unit names included in an application. Works in Delphi 2010. Not verified for other compilers.
function UnitNames: TStrings;
var
  Lib: PLibModule;
  DeDupedLibs: TList<cardinal>;
  TypeInfo: PPackageTypeInfo;
  PInfo: GetPackageInfoTable;
  LibInst: Cardinal;
  u: Integer;
  s: string;
  s8: UTF8String;
  len: Integer;
  P: PByte;
begin
result := TStringList.Create;
DeDupedLibs := TList<cardinal>.Create;
Lib := LibModuleList;
try
  while assigned( Lib) do
    begin
    LibInst := Lib^.Instance;
    Typeinfo := Lib^.TypeInfo;
    if not assigned( TypeInfo) then
      begin
      PInfo := GetProcAddress( LibInst, '@GetPackageInfoTable');
      if assigned( PInfo) then
        TypeInfo := @PInfo^.TypeInfo;
      end;
    if (not assigned( TypeInfo)) or (DeDupedLibs.IndexOf( LibInst) <> -1) then continue;
    DeDupedLibs.Add( LibInst);
    P := Pointer( TypeInfo^.UnitNames);
    for u := 0 to TypeInfo^.UnitCount - 1 do
      begin
      len := P^;
      SetLength( s8, len);
      if len = 0 then Break;
      Inc( P, 1);
      Move( P^, s8[1], len);
      Inc( P, len);
      s := UTF8ToString( s8);
      if Result.IndexOf( s) = -1 then
        Result.Add( s)
      end
    end
finally
  DeDupedLibs.Free
  end
end;

Example to use in the was suggested in the question...
function IsSomeUnitNameInProgram: boolean;
var
  UnitNamesStrs: TStrings;
begin
UnitNamesStrs := UnitNames;
result := UnitNamesStrs.IndexOf('MyUnitName') <> -1;
UnitNamesStrs.Free
end;

A: Unit names are compiled into the 'PACKAGEINFO' resource where you can look it up:
uses
  SysUtils;

type
  PUnitInfo = ^TUnitInfo;
  TUnitInfo = record
    UnitName: string;
    Found: PBoolean;
  end;

procedure HasUnitProc(const Name: string; NameType: TNameType; Flags: Byte; Param: Pointer);
begin
  case NameType of
    ntContainsUnit:
      with PUnitInfo(Param)^ do
        if SameText(Name, UnitName) then
          Found^ := True;
  end;
end;

function IsUnitCompiledIn(Module: HMODULE; const UnitName: string): Boolean;
var
  Info: TUnitInfo;
  Flags: Integer;
begin
  Result := False;
  Info.UnitName := UnitName;
  Info.Found := @Result;
  GetPackageInfo(Module, @Info, Flags, HasUnitProc);
end;

To do this for the current executable pass it HInstance:
HasActiveX := IsUnitCompiledIn(HInstance, 'ActiveX');

(GetPackageInfo enumerates all units which may be inefficient for executables with many units, in that case you can dissect the implementation in SysUtils and write your own version which stops enumerating when the unit is found.)


text:
Q: Spring application.yaml doesn't work I'm trying to config some JPA and Hibernate properties in yaml file, but the problem arises when I use @Value("${$hibernate.show_sql}") in my JpaConfig.
The error message:

org.springframework.beans.factory.BeanCreationException: Could not
  autowire field: private java.lang.Boolean
  com.movieGo.JpaConfig.showSql; nested exception is
  org.springframework.beans.TypeMismatchException: Failed to convert
  value of type [java.lang.String] to required type [java.lang.Boolean];
  nested exception is java.lang.IllegalArgumentException: Invalid
  boolean value [${spring.hibernate.show_sql}]

I write my application.yml like this:
spring:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1/hello
    username: root
    password:

  hibernate:
    dialect: org.hibernate.dialect.MySQLDialect
    hbm2ddl.auto: update
    show_sql: false

I use @Value like this:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = HelloApplication.class)

class JpaConfig implements TransactionManagementConfigurer {

@Value("${spring.dataSource.driverClassName}")
private String driver;
@Value("${spring.dataSource.url}")
private String url;
@Value("${spring.dataSource.username}")
private String username;
@Value("${spring.dataSource.password}")
private String password;
@Value("${spring.hibernate.dialect}")
private String dialect;
@Value("${spring.hibernate.hbm2ddl.auto}")
private String hbm2ddlAuto;
@Value("${spring.hibernate.show_sql}")
private Boolean showSql;
...
}

It seems Spring regards show_sql as a String type, but
How can I specify a Boolean type in .yml ?
New to Spring mvc, eager seeking help.


text:
Q: Data Recovery on a Repartitioned SSD Is data recovery possible from an SSD where the partitions were deleted, and new partitions were created, then formatted?  The file system is NTFS.
I understand data recovery is generally not possible on SSDs with TRIM when files are deleted, but I'm not sure if TRIM applies to deleted partitions.  Also, it was deleted in the Preinstallation Environment, and I'm not sure if TRIM functions there.

A: If you only did quick format of the partitions, recovery might be possible
by using a product that scans the disk.
Deleting a partition only changes the partition table and does not TRIM
the partition data.
The disk tables are not of much help, since someone did a good job of
destroying them, so the recovery of files whose sectors are not contiguous
on the disk is doubtful or only partially possible.
Some recovery products you may try are :
Recuva,
TestDisk,
PhotoRec.

A: There are two types of formatting:
Quick formatting and full formatting. If you have done quick formatting then you can recover your data back, but if you have full formatting of data then the chances of recovery are very less.
Quick-format helps you remove/delete data from the hard drive. When you quick format a hard drive, only the file pointers get deleted, and the drive space becomes available for new data storage. However, data becomes inaccessible but remains available.
There are various data recovery software that can help you to recover data from deleted partitions, you can try that.


text:
Q: Why does fetching Attributes work differently when using PropertyDescriptor & PropertyInfo? I understand that calling GetCustomAttribute returns a new generated attribute, but why can't I get the attribute using the Attribute property?
I've attached this example:
Definitions:
    public class MyTestAttribute : Attribute
    {
       public int Test { get; set; }
    }

    public class TestClass
    {
       [MyTest]
       public int Property { get; set; }
    }

Code:
    // PropertyInfo
    var prop = typeof(TestClass).GetProperty("Property");
    var attr1 = prop.GetCustomAttribute(typeof(MyTestAttribute), false) as MyTestAttribute;
    attr1.Test = 12;

    var attr2 = prop.GetCustomAttribute(typeof(MyTestAttribute), false) as MyTestAttribute;
    // attr2.Test == 0 since GetCustomAttribute creates a new attribute.
    var attr3 = prop.Attributes; //attr3 = None

    // PropertyDescriptor
    var tProp = TypeDescriptor.GetProperties(typeof(TestClass)).Cast<PropertyDescriptor>().First(p => p.Name == "Property");
    var tAttr1 = tProp.Attributes.Cast<Attribute>().OfType<MyTestAttribute>().First();
    tAttr1.Test = 12;

    var tProp2 = TypeDescriptor.GetProperties(typeof(TestClass)).Cast<PropertyDescriptor>().First(p => p.Name == "Property");
    var tAttr2 = tProp2.Attributes.Cast<Attribute>().OfType<MyTestAttribute>().First();
    // tAttr2.Test == 12


text:
Q: Pass by value/reference/rvalue with a std::move(str) arg I have the following code:
//void func(const std::string &&i){
//void func(const std::string &i){
void func(const std::string i){
  std::string val{i};
}

int main()
{
  std::string d = "asdf";
  func(std::move(d));
  std::cout << d << std::endl;
}

When i is pass-by-value, d becomes empty, but d retains its form if we're passing by reference or by r-value reference. Could someone explain what is going on?
I understand that std::move doesn't actually move anything, but rather makes the variable it takes in moveable by casting it to an xvalue.
As an aside why does the code in the current state compile if d is cast to an x-value? func is currently set to take in pass by value arguments, and not by rvalue reference.

A:
When i is pass-by-value, d becomes empty,

To be accurate, d will be in some valid state not specified in the C++ standard. Empty is one possibility.
std::move itself never causes the move constructor to be called directly. Neither does binding an rvalue reference to an object cause move constructor to be called directly.
Only initialising an object with a non-const rvalue will cause the argument to be moved from. In the example, std::string i is initialised with a non-const rvalue and the move constructor will be called.

As an aside why does the code in the current state compile if d is cast to an x-value?

Because the type has a (non-deleted) move constructor. Therefore the argument can be initialised from an rvalues.

I had thought if we had std::string i, a copy of the rvalue reference is made.

std::string i is not a reference. It is a variable of type std::string and as such there is an object of type std::string associated with the variable. That object is initialised with the expression that is passed into the function as argument.

Also, if I observe that the output of d is still the same as prior to applying std::move, what does this mean in this case?

If you call the uncommented version of the function with an rvalue, then the argument will be moved from. If the value is same as it was, then it simply means that the value is the same. You cannot assume that the value will be the same nor that it won't be the same.

Does it mean that d is still occupying the space it originally occupied?

Assuming that by "space" you mean the storage where the variable is, then of course it is still occupying the same storage. The address of an object never changes through the lifetime of the object.

A: void func(const std::string &&i)

This signature will not move anything, because the reference is to a const object. Remove the const, and it'll work. But only if you std::move the parameter i again inside the function. This is because anything that has a name is an lvalue, whether the parameter was declared as & or &&. See this answer.
void func(const std::string &i)

This will copy, as you probably already know. However, it behaves similarly to the ptevious one in that if you drop the const and do std::move( i ) inside the function, it'll actually move. This is because, as you noted, move is a cast and the compiler will listen to you and do exactly what you say when you cast, regardless of what you intended.
void func(const std::string i)

This moves in your example because here, i is an entirely new string. The outside string d gets moved into i. However, you still have to drop the const and use std::move( i ) if you want to move i into val.


text:
Q: Limiting Distribution of Average of iid Gamma Variables It can be shown that if
$X \sim Gamma(\alpha, \theta)$,
then
$\overline{X_{n}} \sim Gamma(\alpha n, \theta/n)$.
where $X_{1}, X_{2} \dots X_{n}$ are all iid and follow the distribution of $X$.
The proof of this argues that the MGF of $X$ is $M_{X}(t) = \frac{1}{(1-\theta t)^{\alpha}}$ and the MGF of an average is just $M_{X}(\frac{t}{n})^{n}$.
I was playing around and wondered that if we took the limit of $M_{\overline{X_{n}}}(t)$, then we would have
$$lim_{n \to \infty} \frac{1}{(1 - \frac{\theta t}{n})^{\alpha n}}$$
which can be show to $ = e^{\theta \alpha t}$.
By a theorem in probability theory:
$M_{X_{n}}(t) \rightarrow M_{X}(t) \implies X_{n} \rightarrow X$ in distribution.
Thus, $\overline{X_{n}}$ converges to the constant random variable, $Q = \alpha \theta$.
What does this mean? That, in the limit, the average of $n$ trials of a gamma distribution will have at least $\alpha n \approx \infty$ occurences with waiting time $\theta/n \approx 0$?

A: TLDR: in this case $\bar{X}$ is always a gamma random variable of a certain form. But when $n$ is large, this particular type of gamma random variable "is close to" a (degenerate) normal random variable.
The expectation of a $\text{Gamma}(\alpha n, \theta /n)$ random variable, the way you have it parametrized, is $\frac{\alpha n \theta}{n} = \alpha \theta$. The variance will be $\alpha n \theta^2n^{-2}$. This is the distribution of $\bar{X}$ for any integer $n$, small or large. So, to answer your question, $E[\bar{X}] = \alpha \theta$ even for small $n$.
You don't need a large sample to get results about the mean and distribution. But if you do have a large sample, it's approximately normal. That's because the MGF looks different now after you take the limit. It's the MGF of a normal (see here) with mean $\alpha \theta$ and variance $0$. Or in other words, $P(\bar{X} \in A) \to \delta_{\alpha\theta}(A)$.
This agrees with intuition because, in the case of the normal, the parameters represent the mean and variance, and you get these numbers when you take the limit of the gamma rv's mean and variance in the above paragraph.

A: Since you mention waiting times.
Assume that $\alpha$ is an integer, and that $X_1$ is the time of occurrence of (equivalently, the waiting time for) the $\alpha$-th arrival after $t = 0$ in a
Poisson process of rate $\lambda = \theta^{-1}$. Recall that
in a Poisson process of rate $\lambda$, there are (on average)
$\lambda$ arrivals in any time interval of unit length, and
the average spacing between arrivals (average waiting time)
is $\lambda^{-1} = \theta$.
Furthermore, $X_1$ is a Gamma random variable with parameters
$(\text{order}, \text{scale}) = (\alpha,\theta)$ and so
its mean $E[X_1] = \alpha\theta$ is the average time of occurrence of the
$\alpha$-th arrival. Next, define $X_2$ the time elapsed between the occurrence of the $\alpha$-th arrival and the $(2\alpha)$-th
arrival, and more generally, $X_k$ as the  time elapsed between the occurrence of the $((k-1)\alpha)$-th arrival and the $(k\alpha)$-th
arrival. Then the $X_i$ are independent $Gamma$ random variables
with parameters $(\text{order}, \text{scale}) = (\alpha,\theta)$.
OK, with that as prologue, consider that
$$Y_n = X_1 + X_2 + \cdots + X_n$$
is the waiting time for the $(n\alpha)$-th arrival after $t=0$.
Over this long period of time, a total of
$(n\alpha)$ arrivals have occurred, and so
$$Z_n = \frac{Y_n}{n} = \frac{X_1 + X_2 + \cdots + X_n}{n}$$
is an estimate of the waiting time for $\alpha$ arrivals
to occur, obtained by taking $n$ measurements over a long
period of time and averaging the results; a method dear to
the heart of every statistician. What you have determined is
that as $n\to\infty$, the distribution of $Z_n$ converges to a
degenerate
random variable (called a constant by statistically illiterate
folks) that takes on value $\alpha\theta$ with probability
$1$.  What this result is saying is that when $n$ is very
large, $Y_n$, the waiting time for the occurrence of the
$(n\alpha)$-th arrival will be approximately $n\alpha\theta$
while $Z_n$ will be very very close to $\alpha\theta$.
Note the difference in wording here. $Y_n$ can have substantial
deviations e.g. $O(\sqrt n)$) from the nominal value $n\alpha\theta$ which itself is increasing without bound as $n\to\infty$,
but $Z_n$ will deviate from its nominal value only very slightly
with the deviation being $O(\frac{1}{\sqrt{n}})$ which is getting
smaller as $n \to \infty$.


text:
Q: Stop the page to refresh after the form button is clicked and error is shown I have seen other questions too but i want to stop my page from refreshing after signup form is filled and with validation from php it shows an error in a span. or not refreshing the form data or not clearing the form data will also work. I just want the form data to be exact as it is but the error to be shown. please find the code
  <form action="signup.php" id="form" method="POST" onsubmit="">

Mero Notes

Register Your Account

  <?php
      echo '
'.$message.'
';
       ?>

        <input placeholder="Full Name" type="text" required="required" name="fullName" value=""/>
        <input placeholder="Email" type="text" required="required" name="email" />
        <input placeholder="Password" type="password" name="password" required="required" id="id_password" minlength="8" onkeyup="passValidation();"/>
        <input placeholder="Confirm Password" type="password" name="conPassword" required="required" id="id_conPassword" onkeyup="passValidation();"/>
        <input placeholder="Contact" type="number" required="required" name="contactNum" />
        <button type="submit" class="regButton" type="submit" value="Sign Up" id="regBtn" onclick="return passValidationAlert()">SignUp </button>

      Already Have an Account ?
      Login here

  </form>

The php code looks like this
if(mysqli_num_rows($result)>0){
  $_SESSION['error']=true;
    $message='The Entered Email is Already Taken';
      }
        elseif($password!=$confirmPassword){
           $message='Password did not match';
      }
      {
           $epassword=password_hash($password,PASSWORD_BCRYPT);
            $sql = "INSERT INTO signupdatabasemn (fullName, email, password, phoneNumber)
              VALUES ( '$fullName', '$email', '$epassword', $phoneNumber) ";
                $result2= mysqli_query($conn, $sql);

 if ($result2>0) {
    header('Location: /demosite3fnl/index.php');
  } else {
  }

}
?>

A: The simplest solution would be to put the post data in the input value so that when page get refreshed, it stays where it should be. In example:
<input placeholder="Email" type="text" required="required" name="email" value="<?= $_POST['email'] ?>"/>

Updated. Just seen your updated code. Looks like form is sending request to different php file. In this case, try return posted data using get. See more here


text:
Q: Cannot create dataproc cluster When creating DataProc cluster using Web Console or gcloud, getting the same error:
gcloud dataproc --region us-west1 clusters create cluster-02eb --subnet default --zone us-west1-a --master-machine-type n1-standard-4 --master-boot-disk-size 500 --num-workers 2 --worker-machine-type n1-standard-4 --worker-boot-disk-size 500 --image-version 1.2 --scopes 'https://www.googleapis.com/auth/cloud-platform' --project projectxyz123 --initialization-actions 'gs://dataproc-initialization-actions/jupyter/jupyter.sh'

Waiting on operation [projects/projectxyz123/regions/us-west1/operations/53badbbc-41cc-4241-aedb-490981864bf9].
Waiting for cluster creation operation...done.
ERROR: (gcloud.dataproc.clusters.create) Operation [projects/projectxyz123/regions/us-west1/operations/53badbbc-41cc-4241-aedb-490981864bf9] failed: com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found
Not Found.

What does this error means ?

A: This is currently a known issue for zone us-west1-a. Using an alternative zone should work (e.g. us-west1-b).


text:
Q: Jquery rails 3, move item from one div class to another div when it is checked i have two div id=left and div id=right. now, there are multiple checkboxes with item listed in left div. when i select one check box then that item should remove from left div and added to right div and do it same for move selected item from div id=right to div id=left. and when i click one check box its status also updated in database. so tell me how to perform this task with jquery-ajax in rails 3.
Script :

rails code:

      <% @activity.each do |p| %>
        <% p.task.each do |t| %>

                <%= check_box_tag 'activity_status', task.id, :class => 'checkbox'%>
              <%= link_to task.title, mytask_path(@task), :title => "is responsible.                                 , Total my task : " %>

                 <%= link_to "Edit", task(@activity) %> |
                 <%= link_to "delete", @task, :method => :delete %>

                <%= task.due_date %>

        <% end %>
      <% end %>


text:
Q: Laravel 5.0 - Using Request in function I am building an application that uses the repository pattern. Now what I have done is reuse functionality but I have hit a bit of a hiccup. I have one view that shows several different models on it. These models are related through a one-to-one relationship (MovieBasic to MovieDetail) and one-to-many relationship (MovieBasic to MoviePersonnel). The issue I am having is that I have two different request to validate my forms. They are MovieBasicRequest, which validates my movie's basic information (Title, synopsis) and MovieDetailRequest, which validates my movie's detail information (price, screen type, runtime, etc). So to distinguish between which request to use I have added a parameter to my url as follows:
movie_basic.blade.php
<?php $params = ['id' => $movie->id, 'type' => 'movie_basic']; ?>

Movie Baiscs Edit

      {{ $movie->movie_title}}

      {{ $movie->movie_synopsis }}

I know that using the <?php ?> tags is not best practice but I will clean that up later. So because of my $params the URL will look like so
www.moviesite.dev/1/edit?movie_basic

Which will call the edit function in the controller like so
MovieController.php
/**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $movie = $this->movieBasic->find($id);

        return view('cms.edit', compact('movie', 'type'));
    }

In this case the type does not really play a role because of the relationship between MovieBasic and MovieDetail models. However it does play a role in my update function below:
MovieController.php
/**
     * Update the specified resource in storage.
     *
     * @param  int  $id, MovieBasicRequest $request
     * @return Response
     */
    public function update($id)
    {
        if(strcmp($_GET['type'], 'movie_basic') == 0)
        {
            $movie = $this->movieBasic->find($id);
            $this->request = new MovieBasicRequest;
            $this->movieBasic->update($id, $this->request);
        }
        elseif(strcmp($_GET['type'], 'movie_detail') == 0)
        {
            $movie = $this->movieBasic->find($id);
            $this->request = new MovieDetailRequest;
            $this->movieDetail->update($id, $this->request);
        }

        return redirect()->action('MovieController@show', compact('movie'));
    }

Essentially what this function does is determine what is being passed in and from there call the correct request. However the way I have it now it just creates an empty array and thus validates nothing. Is there any way to uses these requests to validate information passed in? Or to validate input before I pass it to the update function of the repository?
PS. I have also tried this:
$this->movieBasic->update($id, MovieBasicRequest $request);

but I get an "Undefined variable $request" error.

A: You should better combine them. And you can use sometimes on your form validation for handling both where you will only validate present fields. So that your MovieRequest can be like below
class MovieRequest extends Request
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'movie_title' => 'sometimes|required|min:3',
            'price' => 'sometimes|required|integer'
            // and so on
        ];
    }

}

So you can update your controller as below and use for the both pages. For instance, if the price is not set within the request, then it will skip validating it, but if it's present and empty, then it will throw an error message as it's required.
public function update($id, MovieRequest $request)
{
    $movie = $this->Movie->find($id);
    $movie->fill($request->all());
    $movie->save();
    return redirect()->action('MovieController@show', compact('movie'));
}


text:
Q: How to find the largest number in a list that is not X number? Let's say I have two lists:
x = [6,5,5,4]
z = [5,5,4,3]

I want to find the largest number in each list that is not 5.
So the max of x is 6 and the max of z is 4.
My ideas:

*

*Remove all 5 from both lists then find the max.
OR

*If 5 is the max, then return the second-highest number. If 5 is not the max, return the max.

Would you solve this another way?

A: Check this.
x = [6,5,5,4]
z = [5,5,4,3]
print(max(e for e in x if e!=5))
print(max(f for f in z if f!=5))

A: #!/usr/bin/env python

def max_excluding(it, num):
    try:
        return max(filter(lambda x: x != num, it))
    except ValueError:
        return

for x in [[6,5,5,4], [5,5,4,3], [5], [1]]:
    print(max_excluding(x, 5))

Output:
6
4
None
1

I find filters over iterators easier to reason about than list comprehensions where the key part of the code is tucked away near the end of the line.
I am, however, surprised to find that it results in code that takes almost 25%-30% longer:
import timeit

cases = {
    'comprehension': {
        'setup': "\n".join([
            'import random',
            'X = [int(random.randint(0, 10)) for _ in range(1000000)]',
        ]),
        'stmt': 'max([x for x in X if x != 5])',
    },
    'filter': {
        'setup': "\n".join([
            'import random',
            'X = [int(random.randint(0, 10)) for _ in range(1000000)]',
        ]),
        'stmt': 'max(filter(lambda x: x != 5, X))',
    },
}

for case, code in cases.items():
    print(case)
    print(timeit.timeit(**code, number=100))

Sample timing output:
comprehension
11.6845581
filter
14.393007899999999


text:
Q: Using $("#select-id").prop("selectedIndex") In A Select Statement OK, so I've been made to understand that using this
$("#select-id").prop("selectedIndex")

in conjunction with this
$("#select-id").prop("selectedIndex", 1)

Would help obtain the results I'm looking for in getting certain elements passed back to a select statement, but I cannot find any examples of usage for this.
Lets say I have 6 elements in the select, and I have them being compared against something in another field. What would be the recommended way to set this up? I understand use a for loop, and then an if statement to iterate through the values, but I don't quite get how to use the aforementioned .prop statements.
Any help would be appreciated.
function compareAmts($FIELDSwitchText, $FIELDSwitchPull)
{
var SwitchAdv = 0;
temp = $("#FIELD_SwitchPull").val();
var SwitchComm = parseInt(temp.replace(/\,/g,''));

if($("#FIELD_SwitchText").val()!=""){
    SwitchAdv = parseInt($("#FIELD_SwitchText").val());

Basically this collects the information, I then need to use the 2 lines above in a For Loop to Get and Set the SelectedIndex, and thus the Select DropDown

A: If you are trying to select a specific option in the select by its value, use val(). For example:
$('#select-id').val('foo');

Would select the following option:
<select id="select-id">
    <option value="">Please select</option>
    <option value="foo">Foo</option> <!-- jQuery code selects this one -->
    <option value="bar">Bar</option>
</select>

Update
If you have a specific item index you want to select, you can use eq() to get the specific option. Given the above HTML, the following would also select the foo option:
$('#select-id option').eq(1).prop('selected', true);

A: var $select = $("#select-id");
var value = $('textarea').val(); // Or whatever

$select.find('option').each(function (index) {
    if ( $(this).text() == value ) { // Or whatever other criteria you have...
        $select.prop('selectedIndex', index);
        return false;
    }
});


text:
Q: find character array length in Android to get length of string
String str=strLenData.toString();
int ipLen= str.length();
return ipLen;

whatever be the value of strLenData, value of str= [C@40523f80. As a result, for every char[] I input, the length is shown as 11.
I have to use the length as a limit to a loop. Many a times the actual length of char [] would be less than 11. In those cases, the application crashes with the java.lang.ArrayIndexOutOfBoundsException.
Is there any other method to find the length of array. In C++ we might look for '\x0' to mark the end of string. But I guess that is not valid case in Android.

A: May be other code from the same line (may be strCharData[i+j]) goes out of bound

A: The problem might be because of this,
strCharData[i+j]

Consider the length of strCharData to be 5.
Now if you can see, you have used "i+j". Consider the result of i+j to be greater than 5.
This will lead to a situation where you are referring to an index which is greater than the length of strCharData(say 5).
Or even this replaceLen value might be bigger than the total array size. Check it out

A: Java throws an out of bounds exception when you access an array outside its limits. In Java an array goes from 0 to length - 1.
In your case I would guess it is because replaceLen is too big, but could you please post the entire method so we can see?

A: Why are you using char arrays to do replacement? It's likely that you're better off using String.replaceAll, which accepts a regex. The regex can handle the 'match' part of your code and the replacement string doesn't have to be the same length as long as it matches the regex.
As Andro mentioned, the problem is almost definitely due to the i+j exceeding the bounds of the array and you're better off not using arrays at all.

A: String str=strLenData.toString();
int ipLen= str.length();

I assume strLenData is a char[]:
This code calls toString() on a char[], which returns garbage (I think it's something like a 2 char indicator of the data type + the hashcode of the array but that's not important). You then take the length of that String which is 11.
if strLenData is a char[] then you get the length with strLenData.length. It's a field not a method so there is no ().


text:
Q: Managing MySQL SET datatype in PHP I have a column 'Ambience' of the following datatype in a MySQL database:
set('Funny', 'Sad', 'Scary')

I am querying the data through PHP with:
$result = mysqli_query($con,"SELECT * FROM Films");

I am wondering how to deal with this data type on the client-side. For example, I want to find a film that is scary and print it. Should I treat the whole SET datatype as a string?

A: If you want a film that is scary:
SELECT * FROM Films WHERE FIND_IN_SET('Scary', Ambience) > 0;

A: This is bad design as you need to search for specific values of Ambience filed. You can use FIND_IN_SET, but your query will be slow. Turn to atomic values for Ambience


text:
Q: Calloc'd struct members changing without me doing it - intermittent only I am trying to implement a shunting yard algorithm and then a RPN calculator in C, however I am getting an intermittent fault, which doesn't ever happen when I step through the code line by line! I'm at my wits end!
I have each item stored in a struct, where is_operator is true when the character encountered is a * / - + symbol.
struct operator{
    char symbol;
    associativity assoc;
    uint8_t prec;
    float value;
    bool is_operator, is_number;
};

This is only ever assigned in line 53 of my code - in the 'assign_operator' function.
operator* assign_operator(char symbol, associativity ass, int prec){

    //check the precedence is in limits
    assert(prec <= 6);

    //get memory for the struct
    operator *op= calloc(1, sizeof(op));
    mem_check(op);

    //assign the struct
    op->symbol = symbol;
    op->assoc = ass;
    op->prec = prec;
    op->is_operator = true;
    op->is_number = false;

    return op;
}

Show how though it ends up becoming false, I suspect in the print_array function but I have no clue how!
void print_array(operator ** array, int size){

    fflush(stdout);

    for (int i = 0; array[i]; i++) {

        if (array[i]->is_number) {
            printf("%f ", array[i]->value);

        }

        else{
            printf("%c ", array[i]->symbol);

        }
    }

    printf("\n");
}

Any finally my shunting yard function which does the 'meat':
void infix_rpn(operator** output, const char* equation){

const char symbols[] = { '/', '*', '+', '-' };
unsigned int number_of_operators = num_elems(symbols), q_len = (int)strlen(equation)-1, out_pos = 0;
char input_symbol;
int in_int, i, z = 0;

//get memory for array of operators and set them up
operator **opers = setup_operators(symbols, number_of_operators);

/*
 the FILO 'stack' area, where 0 is the bottom, so the thing to pop is the highest index occupied
 */
operator **stack = calloc(q_len, sizeof(operator));
mem_check(stack);

//iterate through the letter in the equation string
while(equation[z]){

    //test for blank and skip over until it's not blank
    while(isblank(equation[z])){
        z++;
    }

    //is it's a character then set in_int to 0 and put the character in 'input'
    if(!isdigit(equation[z])){
        in_int = 0;
        input_symbol = equation[z++];
    }

    //must be a number entered
    else{
        in_int = atoi(&equation[z++]);
    }

    //if the number is a 0 it must have been a character
    if (!in_int) {

        //loop though the symbols to find a match
        for (i = 0; i < number_of_operators; ++i) {
            if (opers[i]->symbol == input_symbol) {

                int j = 0;
                //find next empy element in queue
                while(stack[j] != NULL && j < q_len){
                    j++;
                }

                /*
                 cant have a + on top of a / so check the precedence
                 a + has a higher precedence than a / therefore
                 if the number is higher, the precedence is less!
                 inverse precedence
                 */
                if (j == 0) {
                    stack[j] = assign_operator(symbols[i], left, i + 3);
                }

                //if the top thing in the queue has a lower precedence than the new operator's
                else {

                    //get the precedence numbers
                    int queue_prec = stack[j - 1]->prec;
                    int new_prec = opers[i]->prec;

                    //if the + is coming down on top of the * they need switching
                    if (queue_prec < new_prec){

                        //pop to output and point to next available element
                        output[out_pos] = stack[j - 1];
                        out_pos += 1;

                        //put new one in the queue in it's place
                        stack[j - 1] = assign_operator(symbols[i], left, new_prec);

                    }

                    //if the things are the same or it's a * on toof a + can just be put on the queue
                    else{
                        //put it on the queue
                        stack[j] = assign_operator(symbols[i], left, new_prec);
                    }
                }
            }
        }
    }

    //add number to the output queue, then increment the index of the queue
    else{
        output[out_pos] = assign_value(in_int);
        out_pos += 1;
    }

}

//find last thing in the queue
i = 0;
while(stack[i+1]){
    i++;
}

//add the queue to te output stack
while(i >= 0){
    output[out_pos++] = stack[i];
    //needs to be 'popd' here so that the queue no long has any contents
    stack[i--] = NULL;
}

//free_ops(queue, q_len);
free(stack);

free_ops(opers, number_of_operators);
free(opers);

}

Any tips as to why this could possibly happen would be appreciated!
Thank you,


text: Q: Number of bins for discretization How do I decide on the right number of bins to discretize my continuous data? Are there are tests/techniques to do the same? Could someone give me some idea into existing approaches?


text:
Q: devops pipeline fails, artifact not found I have an azure devops pipeline that publishes output,
pool:
vmImage: 'windows-latest'
steps:
- script: |
    dotnet restore
    dotnet build --configuration Release
- task: DotNetCoreCLI@2
  inputs:
    command: publish
    arguments: '--configuration Release --output publish_output'
    projects: 'MyProject/*.csproj'
    publishWebProjects: false
    modifyOutputPath: false
    zipAfterPublish: false
- task: ArchiveFiles@2
  displayName: "Archive files"
  inputs:
    rootFolderOrFile: "$(System.DefaultWorkingDirectory)/publish_output"
    includeRootFolder: false
    archiveFile: "$(System.DefaultWorkingDirectory)/myapp.zip"
- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(System.DefaultWorkingDirectory)/myapp.zip'
    artifactName: 'myapp'

and this works.
Another release pipeline should use the artifact generated by build,
trigger:
- main

variables:
  azureSubscription: MySubscription
  appName: myAppName
  vmImageName: 'ubuntu-latest'

steps:

- task: DownloadBuildArtifacts@1
  inputs:
    buildType: 'current'
    downloadType: 'single'
    artifactName: 'myapp'
    downloadPath: '$(Build.ArtifactsDirectory)'
- task: AzureFunctionApp@1 # Add this at the end of your file
  inputs:
    azureSubscription:  $(azureSubscription)
    appType: functionApp # default is functionApp
    appName: $(appName)
    package: $(Build.ArtifactsDirectory)/**/*.zip

but this fails already in the DownloadBuildArtifacts task with error:
##[error]Artifact myapp was not found for build xy.

I can see in the log that the artifact is placed in some folder,
Upload 'D:\a\1\s\myapp.zip' to file container: '#/29596927/myapp'

but there is no info in which location the DownloadBuildArtifacts task is searching for the artifact (at least I did not find it even with analytics enabled in the pipeline run). Should I replace 'Build.ArtifactsDirectory' or is something wrong at another place?

A: You have to define your resources to that other build pipeline before or after the variables:
resources:
  pipelines:
    - pipeline: referenceNameOfBuildPipeline
      source: BuildPipelineName

  # similarly, referencing another repo source
  repositories:
    - repository: referenceNameOfRepo
      type: git
      name: RepoName

Then you can use the reference name in a download or checkout step:
steps
  - checkout: self
  - checkout: referenceNameOfRepo

  - download: referenceNameOfBuildPipeline
    artifact: 'myApp'
    displayName: 'Downloading myApp'

  - task: ExtractFiles@1
    displayName: "Extracting Build Artifacts"
    inputs:
      archiveFilePatterns: "$(Pipeline.Workspace)/**/myapp.zip"
      destinationFolder: '$(Build.BinariesDirectory)'

A:
##[error]Artifact myapp was not found for build xy.

From your YAML sample, the cause of the issue is that you need to download the artifacts from Build Pipeline, but in release pipeline, you add the  DownloadBuildArtifacts task to download the current release pipeline artifacts.

buildType: 'current'

Since the build artifacts doesn't exist in release pipeline, it will cause the issue.
To solve this issue, you need to modify the DownloadBuildArtifacts task definition to download the build pipeline artifacts.
For example:
steps:
- task: DownloadBuildArtifacts@1
  displayName: 'Download Build Artifacts'
  inputs:
    buildType: specific
    project: 'projectname'
    pipeline: 'Pipelinename or PipelineID'
    artifactName: 'myapp'
    downloadPath: '$(Build.ArtifactsDirectory)'

In this case, it will download the artifacts of Build Pipeline.
For more detailed info, you can refer to the doc: DownloadBuildArtifacts@1


text:
Q: Using external programs inside azure-functions I'm actually developing a POC on Azure Functions.
I actually need to renders PDF from LaTex and the best way to do that is to use some external program usually.
So far what I understood is that I need to use a custom Dockerfile where I can install any external programs and then use them from my Azure Functions, is that the correct way?
By doing this way, when I try to create a Function App in the Azure Portal, I select "Docker container"

and then I cannot select the "Consumption" Plan, I must go for the "App Service" / "Premium"

Well, I can still select the Free plan, so it's still fine.
But then it's NOT creating a "Function App" but a simple "App Service".
How I can then deploy on it?

A: It's correct. You'll need to use the Azure Function image and deploy it to Containers Running on Web App:
https://hub.docker.com/_/microsoft-azure-functions-base


text:
Q: Sharepoint - Custom ItemStyle in a new file how can I customize the presentation of a Content Query Web Part by modyfing the xsl it uses without touching ItemStyle.xsl but using a brand new .xsl file?
I'm using MOSS 2007.
Thanks

A: Export the content query web part (should download as a .webpart file), open it in your favourite text editor, and set the URL to your custom xsl in the XslLink field.
When you're done, rename it and either upload it to the web part gallery then import into a web part page, or directly import it into a web part page.


text:
Q: How to get array of row values from JDBC result set I have a sql statement that brings back the following rows:

I would like to obtain these values from a JDBC result set as two objects.  One for the customer with customerNo 1 and the other for customer 2.  I would like the two objects to have another array value with the related Titles with the object values.
The structure would ultimately look like this (in JSON):
{customerNo : 1, ["Object 1", "Object 2", "Object 3"]}, {customerNo : 2, ["Object 4", "Object 5"]}
How can I accomplish this with JDBC?

A: You can use a Map to initially collect the results in the format you want.
Map<Integer, Set<String>> customerTitles = new HashMap<Integer, Set<String>>();
while(resultSet.next()) {
    Integer custId = resultSet.getInt(1);
    Set<String> titles = customerTitles.containsKey(custId) ?
            customerTitles.get(custId) : new HashSet<String>();
    titles.add(resultSet.getString(2));
    customerTitles.put(custId, titles);
}

Once you have it collected this way, you can iterate over the Map and in turn the Sets within and convert them to JSON
// Convert to Json array here using your JSON library
for(Integer custId :  customerTitles.keySet()) {
    for(String title : customerTitles.get(custId)) {

    }
}

A: Two ways that I can think of.

*

*Get the CustomerNo first with a SELECT DISTINCT query and keep it in a COLLECTION.
Then for every (using a loop) CustomerNo in the COLLECTION perform a SELECT Title from table WHERE CustomerNo = <collectionValue> and create a new JSON Object for each CustomerNo.

*Fetch the RESULTSET with a SELECT CustomerNo, Title FROM tablename ORDER BY CustomerNo.
In the fetching code (inside the loop) of the RESULTSET assign a variable to the CustomerNo you are getting from the RESULTSET and check for the next row. If you encounter a new CustomerNo then create a new JSON Object.