text:
Q: Python - calculate the distance with different data types in python I have a data with the 11 attributes. I want to calculate the distance on each of these attributes. for example its attribute (x1, x2, ..., x11) and for x1 & x2 has a nominal type, x3, x4, ... x10 has ordinal type, then x11 has binary type. how can I read the attributes using python? and how to differentiate these attributes in python and how to differentiate these attributes in python so I can calculate the distance? can someone tell me what should I do? thank you
sample data: x1 (forestry,plantation,other,forestry) x2 (plantation, plantation, shrubs, forest) x3 (high, high, medium, low) x4 (low, medium, high, high) x5 (high, low, medium, high) x6 (medium, low, high, medium) x7 (3, 1, 0, 4) x8 (low, low, high, medium) x9 (297, 298, 299, 297) x10 (1, 2, 0, 4) x11 (t, t, t, f)

A: You can do something like this:
def distance(x,y):
    p = len(x)
    m = sum(map(lambda (a,b): 1 if a == b else 0, zip(x,y)))
    return float(p-m)/p

Example:
x1 = ("forestry", "plantation", "high", "low", "high", "medium", 3, "low", 297, 1, True)
x2 = ("plantation", "plantation", "high", "medium", "low", "low", 1, "low", 298, 2, True)

print distance(x1,x2) # result: 0.636363636364 = (11-4)/7

A: I've rewritten this as follows:
First I create a Nominal type factory:
class BaseNominalType:
    name_values = {}   # <= subclass must override this

    def __init__(self, name):
        self.name = name
        self.value = self.name_values[name]

    def __str__(self):
        return self.name

    def __sub__(self, other):
        assert type(self) == type(other), "Incompatible types, subtraction is undefined"
        return self.value - other.value

# class factory function
def make_nominal_type(name_values):
    try:
        nv = dict(name_values)
    except ValueError:
        nv = {item:i for i,item in enumerate(name_values)}

    # make custom type
    class MyNominalType(BaseNominalType):
        name_values = nv
    return MyNominalType

Now I can define your nominal types,
Forest = make_nominal_type(["shrubs", "plantation", "forestry", "other"])
Level  = make_nominal_type(["low", "medium", "high"])
Bool   = make_nominal_type({"f":False, "t":True})

Then I make a MixedVector type factory:
# base class
class BaseMixedVectorType:
    types = []          # <= subclass must
    distance_fn = None  # <=   override these

    def __init__(self, values):
        self.values = [type_(value) for type_,value in zip(self.types, values)]

    def dist(self, other):
        return self.distance_fn([abs(s - o) for s,o in zip(self.values, other.values)])

# class factory function
def make_mixed_vector_type(types, distance_fn):
    tl = list(types)
    df = distance_fn

    class MyVectorType(BaseMixedVectorType):
        types = tl
        distance_fn = df
    return MyVectorType

then create your data type,
# your mixed-vector type
DataItem = make_mixed_vector_type(
    [Forest, Forest, Level, Level, Level, Level, int, Level, int, int, Bool],
    ??? # have to define an appropriate distance function!
)

... but wait, we haven't defined a distance function! I wrote the class to allow you to plug in whatever distance function you like, in the form:
def manhattan_dist(_, vector):
    return sum(vector)

def euclidean_dist(_, vector):
    return sum(v*v for v in vector) ** 0.5

# the distance function per your description:
def fractional_match_distance(_, vector):
    return float(sum(not v for v in vector)) / len(vector)

so we finish creating
# your mixed-vector type
DataItem = make_mixed_vector_type(
    [Forest, Forest, Level, Level, Level, Level, int, Level, int, int, Bool],
    fractional_match_distance
)

and test it as
def main():
    raw_data = [
        ('forestry', 'plantation', 'high', 'low', 'high', 'medium', 3, 'low', 297, 1, 't'),
        ('plantation', 'plantation', 'high', 'medium', 'low', 'low', 1, 'low', 298, 2, 't'),
        ('other', 'shrubs', 'medium', 'high', 'medium', 'high', 0, 'high', 299, 0, 't'),
        ('forestry', 'forestry', 'low', 'high', 'high', 'medium', 4, 'medium', 297, 4, 'f')
    ]

    a, b, c, d = [DataItem(d) for d in raw_data]

    print("a to b, dist = {}".format(a.dist(b)))
    print("b to c, dist = {}".format(b.dist(c)))
    print("c to d, dist = {}".format(c.dist(d)))

if __name__=="__main__":
    main()

which gives us
a to b, dist = 0.363636363636
b to c, dist = 0.0909090909091
c to d, dist = 0.0909090909091


text:
Q: Excel: Min/Max sum amount per person within unique dates I have an Excel table with 3 columns (please see picture attached below): Date, Name (Initials) and Amount Spent
I'd like to return the value of the minimum and maximum summed amounts (separately) spent for each person per date (B31:C33).
I thought of a formula looking like so:
{=MIN(SUMIFS(C2:C26,B2:B26=A31, A2:A26))}
Or like so:
{=SUMPRODUCT(--(C2:C26,B2:B26=A31,?))}

Unfortunately, I am unable to return the correct value. I would be grateful to receive your help.
I'll be looking forward to some responses.

A: Your question can be answered with a PivotTable:

Assuming you want the absolute minimum and the absolute maximum for all the dates

*

*In 'Rows' you add the initials, since you will want a minimum and a maximum by person, throughout all the dates.

*In 'Values' you want the Amount Spent, but not the Sum (which is the default value shown)... You can change the Values so that one shows the Min, and the other shows the Max.

Follow the following steps:
Start
You should start by selecting your table (A1:C26) and then go to Insert... PivotTable. I created a dummy spreadsheet with only a few values, so in my case I selected (A1:C10):

Step 1
After you create your PivotTable, it will be empty. Click on the large icon that appears and a menu with PivotTable Fields will appear on the right. Here, drag Name (Initials) to Rows and Amount Spent to Values, twice. It will then look like this:

Step 2
The PivotTable is showing the sum of the amounts, but you want the minimum and maximum. These can be changed by clicking on the info button to the right and then selecting your intended calculation (e.g. minimum):

Step 3
Repeat Step 2 and change to the maximum.
End Result
The end result will be this:

I removed the Grand Totals, since they were meaningless, in Design... Grand Totals... Off for rows and columns. This menu appears only if you click the PivotTable.

Assuming you want to do this for each date

Easy! On top of what you already did, just drag Date to the Columns and it will show one minimum and one maximum per unique date.
[EDIT] Getting the Date to the Columns doesn't answer the question, but based on the comment, what if you add it to Rows? You will get something like this:

Which can be summarised into a table like this, which seems to be what you want:

A: Firstly, sorry for the delay answering this. I had a rather urgent flurry of bug fixes to attend to at work.
This is an array formula, array formulas must be confirmed by pressing Ctrl+Shift+Enter
MIN -
=SMALL(IF(SUMIFS($C$2:$C$26,$A$2:$A$26,IF($B$2:$B$26=$A30,$A$2:$A$26),$B$2:$B$26,$A30),SUMIFS($C$2:$C$26,$A$2:$A$26,IF($B$2:$B$26=$A30,$A$2:$A$26),$B$2:$B$26,$A30)),1)
MAX - =LARGE(IF(SUMIFS($C$2:$C$26,$A$2:$A$26,IF($B$2:$B$26=$A30,$A$2:$A$26),$B$2:$B$26,$A30),SUMIFS($C$2:$C$26,$A$2:$A$26,IF($B$2:$B$26=$A30,$A$2:$A$26),$B$2:$B$26,$A30)),1)
It looks fairly big so let's talk you through it:
You may have noticed that the only thing that has changed in this formula is SMALL() to LARGE(), this is because the SUMIFS() array is handling the total for each day for that "Person Initials".
SUMIFS([amounts to sum],[dates],
We break off here to produce an array of dates for criteria 1 of SUMIFS():
IF([name initials]=[person initials],[dates])
As this is an array, we end up with a list of matching dates or FALSE like so: {43252;FALSE;FALSE;FALSE;FALSE;FALSE;FALSE;43301;43301;FALSE;43301;FALSE;FALSE;FALSE;FALSE;43342;43342;FALSE;FALSE;FALSE;FALSE;FALSE;43317;43317;43317}
That's the first criteria nailed and the second criteria is simply the "Name (Initials)"
,[name initials],[person initials])
What we now have though, is an array of 0 for where the criteria has not matched and the amounts that we would like to assess.
To make the data useful to us, we make use of the binary nature of Excel in that a 0 will be read as a FALSE result for an IF() statement:
IF([result from formula],[result from formula])
This translates the SUMIFS() result back to either FALSE or our totals.
We are now free to use MIN([formula]) or SMALL([formula],1) to get our smallest value.
As 0 will not be returned fro the maximum providing you have any matched values, you don't need to actually perform the binary trick for MAX([formula]) or LARGE([formula],1):
=MAX(IF(SUMIFS($C$2:$C$26,$A$2:$A$26,IF($B$2:$B$26=$A30,$A$2:$A$26),$B$2:$B$26,$A30))
Again, sorry for the delay and I appreciate that it's a lot to take in so feel free to ask any questions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Receiving comment deprecated error when attempting to loop through the results of a MySQL query I am trying to loop through the results of a MySQL query via PHP. My code is below.
$list = mysql_fetch_array(mysql_query("SELECT * FROM proxies"));

for($i = 0; $i < 2000; $i++) {

  echo $list['address'];

}

This results in: "PHP Deprecated:  Comments starting with '#' are deprecated in /etc/php5/cli/conf.d/ming.ini on line 1 in Unknown on line 0". However, when I try this...
$list = mysql_fetch_array(mysql_query("SELECT * FROM proxies"));

for($i = 0; $i < 2000; $i++) {

  echo $list['id'];

}

it works. So something must be wrong with the database column? Also, I went in /etc/php5/cli/conf.d/ming.ini and changed the # comment to // and retried running my script. It showed no results and gave no errors.

A: Found this...
http://www.howtoforge.com/debian-squeeze-apache2-php5-php-deprecated-comments-starting-with-are-deprecated-in-etc-php5-apache2-conf.d-ming.ini-on
and this....
http://pravams.com/2011/08/18/php-deprecated-comments-starting-with-are-deprecated/
try removing comments.

A: Change all comments starting with # from this:
# comment here

to //:
// comment here

A: Quick Note:Your code is deprecated with the mysql* codes.
You need to go into /etc/php5/cli/conf.d/ming.ini and change those # to ; An article I just read said this.

A: Comment issue is not in your code issue in in php.ini or ming.ini use ; instead of #


text:
Q: A normal space that is not completely normal and has countable pseudo-character I am looking for a $T_4$ space (normal + $T_1$) that is not $T_5$ (completely normal +$T_1$), but such that every singleton is the countable intersection of open sets. Or, alternatively, a proof that none exists.
Some background:
A $G_{\delta}$ normal space, i.e. a normal space where every closed set is the countable intersection of open sets, is perfectly normal and therefore is also completely normal.
What about a normal space where every singleton is the countable intersection of open sets? i.e. a normal space with a countable pseudo-character (if I understand correctly the term "pseudo-character"). Does such space have to be completely normal?

A: To re-use an example I used recently for another problem, use $X:=A \times A$ (in the product topology) where $A$ is Aleksandrov's double arrow space (see here e.g. or here) which is compact, $T_5$, hereditarily Lindelöf, hereditarily separable but not metrisable and contains the Sorgenfrey line $\Bbb S$ as a subspace.
$X$ is compact Hausdorff, as the square of a compact Hausdorff space, so certainly $T_4$. It's not $T_5$ because the subspace $\Bbb S \times \Bbb S$ is not normal.
$A$ is first countable and hence so is $X$, so all points are $G_\delta$ sets, but e.g. $\Delta = \{(x,x): x \in A\}$ is an example of a compact and closed subset that is not a $G_\delta$ set, e.g. So $A$ is an example of a $T_6$ space whose product is not $T_6$ as well.


text:
Q: Restricting swap usage for a systemd service in Ubuntu 18.04 I am trying to restrict the swap usage of a process using MemorySwapMax as mentioned in the doc with Ubuntu 18.04.
Environment
ubuntu@vrni-platform:/usr/lib/systemd/system$ uname -a
Linux vrni-platform 4.15.0-143-generic #147-Ubuntu SMP Wed Apr 14 16:10:11 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

ubuntu@vrni-platform:/usr/lib/systemd/system$ systemctl --version
systemd 237
+PAM +AUDIT +SELINUX +IMA +APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD -IDN2 +IDN -PCRE2 default-hierarchy=hybrid

My systemd unit file looks like below
[Unit]
Description=My service
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=support
MemoryMax=2000M
KillMode=process
MemoryAccounting=true
OOMScoreAdjust=1000
MemorySwapMax=0
ExecStart=/usr/bin/java -cp /home/support -XX:NativeMemoryTracking=summary -Xmx10000m MemoryConsumer 100 200 1

I tried to disable swap for this process by specifying 0 for MemorySwapMax. But it seems there was some issue in systemd which is fixed in systemd 239.
So I also tried setting MemorySwapMax=1M. But that also seems to be not restricting the swap memory usage for this systemd service.
The documentation for MemorySwapMax states this
This setting is supported only if the unified control group hierarchy is used and disables MemoryLimit=.

Can someone let me know how can I know if systemd is using unified control group hierarchy is being used in my setup or what else could be the problem which is not allowing MemorySwapMax to take effect?
EDIT
As mentioned in this answer I can see cgroup2 enabled
ubuntu@vrni-platform:/tmp/debraj$ sudo mount -t cgroup2 none /tmp/debraj
ubuntu@vrni-platform:/tmp/debraj$ ls -l /tmp/debraj/
total 0
-r--r--r--  1 root root 0 Jul  2 17:13 cgroup.controllers
-rw-r--r--  1 root root 0 Jul  2 17:13 cgroup.max.depth
-rw-r--r--  1 root root 0 Jul  2 17:13 cgroup.max.descendants
-rw-r--r--  1 root root 0 Jun 30 14:42 cgroup.procs
-r--r--r--  1 root root 0 Jul  2 17:13 cgroup.stat
-rw-r--r--  1 root root 0 Jul  2 17:13 cgroup.subtree_control
-rw-r--r--  1 root root 0 Jul  2 17:13 cgroup.threads
drwxr-xr-x  2 root root 0 Jun 30 14:42 init.scope
drwxr-xr-x 87 root root 0 Jul  2 15:05 system.slice
drwxr-xr-x  7 root root 0 Jun 30 15:22 user.slice
ubuntu@vrni-platform:/tmp/debraj$ sudo umount /tmp/debraj

A: This has been answered in systemd mailing list.
Link1
Re-posting relevant parts.

Looks like your Ubuntu version is using the "hybrid" cgroup mode by
default. Cgroup v2 is indeed enabled in your kernel, but not
necessarily
in use – in the hybrid mode, systemd still mounts all resource controllers (cpu, memory, etc.) in v1 mode and only sets up its own
process tracking in the v2 tree. See findmnt.
You could boot with the systemd.unified_cgroup_hierarchy=1 kernel
option to switch everything to cgroups v2, but if you're using
container software (docker, podman) make sure those are cgroups
v2-compatible.

Link2

Hello Debraj.
On Thu, Jul 08, 2021 at 05:10:44PM +0530, Debraj Manna wrote:

Linux vrni-platform 4.15.0-143-generic #147-Ubuntu SMP Wed Apr 14 16:10:11 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
[...]
GRUB_CMDLINE_LINUX="audit=1 rootdelay=180 nousb net.ifnames=0 biosdevname=0
fsck.mode=force fsck.repair=yes ipv6.disable=1
systemd.unified_cgroup_hierarchy=1"

Even after making these changes MemorySwapMax not taking into effect.

You need to add also swapaccount=1, swap accounting is enabled by
default only since kernel v5.8.


text:
Q: TypeError: Data type not understood, numpy.zeros I am getting an error while running my code.  The error I receive is:
Traceback (most recent call last):
File "/Users/penguin/PycharmProjects/Greatness/venv/Recipes.py", line
153, in <module>
newRatios = np.zeros(count,count)
TypeError: data type not understood

Process finished with exit code 1

My code is:
count1 = 0
count2 = 0
newRatios = np.zeros(count,count)
print(newRatios)
for ep in XDF['EmailPrefix']:
   for ep2 in XDF['EmailPrefix']:
       if count1 != count2:
           newRatios[count1,count2] = fuzz.token_sort_ratio(ep,ep2)
       else:
           newRatios[count1,count2] = None
       count2 += 1
   count1 += 1
   if(count1 == 2500):
       print('Halfway')

print(newRatios)

The variable count represents a integer value of about 5000.  I apologize I can only give code snippets instead of the entire file, but I am not allowed to disclose the full file.
Not really sure why I'm getting this error, I have tried a few different methods of setting up numpy zeros array and setting up a 2D matrix.  Please note that I import numpy as np so thats why its called np.  I am using python3, if you have any other suggestions for setting up a 2D array and accessing it better than I am here that would be appreciated as well.

A: You need to pass in a tuple. Try np.zeros((count, count)).
Further documentation on this method available here:  https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

A: Use a sequence of ints:
newRatios = np.zeros((count,count))

Shape parameter of zeros accepts int or sequence of ints. Refer docs.

A: np.zeros accepts an iterable as the shape argument. You need to pass your arguments as np.zeros((count,count)). Notice the extra parenthesis. What you're currently doing is passing in count as the shape and then passing in count again as a datatype. It doesn't recognize the datatype that count represents, hence the error.


text:
Q: Cloud formation configuration depending on the region being created Which is the best approach for having a cloud formation template (CFT) use different values for configuration in the mappings depending on the region it's being created?
For example, let's assume I have a service deployed in 2 different regions (Europe and America). Each instance of the service writes to its own DynamoDB (DDB) table, lets call it Data. In order to create the DDB I use a CFT. Since the traffic is not the same in both regions I would like to set different capacity units for the table.
For the above, I could add a parameter to the CFT to state if the template is for Europe or America, create a mapping with the desired valued keyed by the parameter value, and depending on it get one or the other.
Like:
AWSTemplateFormatVersion: 2010-09-09
Resources:
  DdbData:
    Type: 'AWS::DynamoDB::Table'
    Properties:
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      TableName: 'Data'
      BillingMode: PROVISIONED
      ProvisionedThroughput:
        ReadCapacityUnits: !FindInMap
          - DdbDataCapacityUnits
          - 'Read'
          - !Ref Continent
        WriteCapacityUnits: !FindInMap
          - DdbDataCapacityUnits
          - 'Write'
          - !Ref Continent
Mappings:
  DdbDataCapacityUnits:
    Read:
        Europe: '10'
        America: '5'
    Write:
        Europe: '5'
        America: '10'
Parameters:
  Continent:
    Description: The continent in which the stack is being created, either Europe or America
    Type: String
    AllowedValues:
      - Europe
      - America
    Default: Europe

However, since I'm managing multiple regions with the same CFT I would like to use StacksSets to update both of them as one. The stacks for the stack set all have the same parameters, is just that the creation its done in multiple regions.
My approach was to use the pseudoparameter AWS::Region as the key in the configuration mapping like:
AWSTemplateFormatVersion: 2010-09-09
Resources:
  DdbData:
    Type: 'AWS::DynamoDB::Table'
    Properties:
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      TableName: 'Data'
      BillingMode: PROVISIONED
      ProvisionedThroughput:
        ReadCapacityUnits: !FindInMap
          - DdbDataCapacityUnits
          - 'Read'
          - !Ref AWS::Region
        WriteCapacityUnits: !FindInMap
          - DdbDataCapacityUnits
          - 'Write'
          - !Ref AWS::Region
Mappings:
  DdbDataCapacityUnits:
    Read:
      'eu-west-1': '10'
      'us-east-1': '5'
    Write:
      'eu-west-1': '5'
      'us-east-1': '10'

But this approach doesn't work as I get on error when creating the stack: Template validation error: Template format error: Mappings attribute name 'eu-west-1' must contain only alphanumeric characters.
Is there any approach in which I can achieve this?

A: You can swap the region and the Read/Write attribute.
For example, here is a mapping for finding AMIs:
Mappings:
  AmazonLinuxEcsAMI:
    us-east-1:
      AMI: ami-07eb698ce660402d2
    us-east-2:
      AMI: ami-0a0c6574ce16ce87a
    us-west-1:
      AMI: ami-04c22ba97a0c063c4
    us-west-2:
      AMI: ami-09568291a9d6c804c

It can then be used with:
ImageId: !FindInMap [AmazonLinuxEcsAMI, !Ref 'AWS::Region', AMI]

So, try putting the region as the first level instead of Read, then putting Read and Write as the next level.


text:
Q: Will OpenXML ever split a single word into multiple xml elements within a .docx file? I've noticed while parsing .docx using OpenXML that sentences will be broken up by a ton of run elements, formatting, proofing and other elements. E.g. "Hello world" will look like:
Hello</w:t></w:r><w:r><w:rPr><w:rFonts w:ascii=\"Arial\" w:hAnsi=\"Arial\" w:cs=\"Arial\"/><w:noProof/><w:sz w:val=\"20\"/></w:rPr> World"
This makes it very tough to do string replacements.
My question is - will OpenXML every split a single word into multiple elements? E.g.
He</w:t></w:r><w:r><w:rPr><w:rFonts w:ascii=\"Arial\" w:hAnsi=\"Arial\" w:cs=\"Arial\"/><w:noProof/><w:sz w:val=\"20\"/></w:rPr>llo"


text:
Q: Filtering file types with CMFCShellTreeCtrl I'm using a CMFCShellTreeCtrl derived class called CShellTreeCtrl in an CMFCOutlookBar object to display files and I'd like to filter file types and later be able to drag and drop files from it.
I've managed to display files as well as folders, but struggling to understand how to use IEnumIDList to achieve the file type filtering.
int CBar::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMFCOutlookBar::OnCreate(lpCreateStruct) == -1)
    return -1;

CMFCOutlookBarTabCtrl* pOutlookBar = (CMFCOutlookBarTabCtrl*)GetUnderlyingWindow();

if (pOutlookBar != NULL)
{
    pOutlookBar->SetImageList(IDB_PAGES_HC, 24);
    pOutlookBar->SetToolbarImageList(IDB_PAGES_SMALL_HC, 16);
    pOutlookBar->EnableInPlaceEdit(FALSE);
    RecalcLayout();
}

RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE);

// can float, can autohide, can resize, CAN NOT CLOSE
DWORD dwStyle = AFX_CBRS_AUTOHIDE | AFX_CBRS_RESIZE;

CRect rectDummy(0, 0, 0, 0);
const DWORD dwTreeStyle = WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_INFOTIP;
m_pDirList = new CShellTreeCtrl;
m_pDirList->Create(dwTreeStyle, rectDummy, this, ID_SHELLDRILL);
m_pDirList->SetFlags(m_pDirList->GetFlags() | SHCONTF_NONFOLDERS);
pOutlookBar->AddControl(m_pDirList, _T("Folders"), 2, FALSE, dwStyle);
}

A: Got it working with the following code adapted from this similar question
HRESULT EnumObjects(HTREEITEM hParentItem, LPSHELLFOLDER pParentFolder, LPITEMIDLIST pidlParent)
{
    ASSERT_VALID(this);
    ASSERT_VALID(afxShellManager);

    LPENUMIDLIST pEnum = NULL;

    HRESULT hr = pParentFolder->EnumObjects(NULL, m_dwFlags, &pEnum);
    if (FAILED(hr) || pEnum == NULL)
    {
        return hr;
    }

    LPITEMIDLIST pidlTemp;
    DWORD dwFetched = 1;

    // Enumerate the item's PIDLs:
    while (SUCCEEDED(pEnum->Next(1, &pidlTemp, &dwFetched)) && dwFetched)
    {
        TVITEM tvItem;
        ZeroMemory(&tvItem, sizeof(tvItem));

        // Fill in the TV_ITEM structure for this item:
        tvItem.mask = TVIF_PARAM | TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_CHILDREN;

        // AddRef the parent folder so it's pointer stays valid:
        pParentFolder->AddRef();

        // Put the private information in the lParam:
        LPAFX_SHELLITEMINFO pItem = (LPAFX_SHELLITEMINFO)GlobalAlloc(GPTR, sizeof(AFX_SHELLITEMINFO));
        ENSURE(pItem != NULL);

        pItem->pidlRel = pidlTemp;
        pItem->pidlFQ = afxShellManager->ConcatenateItem(pidlParent, pidlTemp);

        pItem->pParentFolder = pParentFolder;
        tvItem.lParam = (LPARAM)pItem;

        CString strItem = OnGetItemText(pItem);
        tvItem.pszText = strItem.GetBuffer(strItem.GetLength());
        tvItem.iImage = OnGetItemIcon(pItem, FALSE);
        tvItem.iSelectedImage = OnGetItemIcon(pItem, TRUE);

        // Determine if the item has children:
        DWORD dwAttribs = SFGAO_HASSUBFOLDER | SFGAO_FOLDER | SFGAO_DISPLAYATTRMASK | SFGAO_CANRENAME | SFGAO_FILESYSANCESTOR;

        pParentFolder->GetAttributesOf(1, (LPCITEMIDLIST*)&pidlTemp, &dwAttribs);
        tvItem.cChildren = (dwAttribs & (SFGAO_HASSUBFOLDER | SFGAO_FILESYSANCESTOR));

        // Determine if the item is shared:
        if (dwAttribs & SFGAO_SHARE)
        {
            tvItem.mask |= TVIF_STATE;
            tvItem.stateMask |= TVIS_OVERLAYMASK;
            tvItem.state |= INDEXTOOVERLAYMASK(1); //1 is the index for the shared overlay image
        }

        // Fill in the TV_INSERTSTRUCT structure for this item:
        TVINSERTSTRUCT tvInsert;

        tvInsert.item = tvItem;
        tvInsert.hInsertAfter = TVI_LAST;
        tvInsert.hParent = hParentItem;

        string str = strItem;

        if (tvItem.cChildren & SFGAO_HASSUBFOLDER)
        {
            InsertItem(&tvInsert);
        }
        else
        {
            if ((str.substr(str.find_last_of(".") + 1) == "pdf"))
            {
                InsertItem(&tvInsert);
            }
        }
        dwFetched = 0;
    }

    pEnum->Release();
    return S_OK;
}


text:
Q: Отправка формы в AngleSharp Пробую выполнять действия на сайте с помощью библиотеки AngleSharp. Остановился на эмуляции нажатия кнопки.
Часть html кода отвечающий за авторизацию на сайте.

<form action="login.php?do=login" method="post" onsubmit="md5hash(vb_login_password, vb_login_md5password, vb_login_md5password_utf, )">

  <input type="hidden" name="do" value="login" />
  <input type="hidden" name="url" value="/log-in.php" />
  <input type="hidden" name="vb_login_md5password" />
  <input type="hidden" name="vb_login_md5password_utf" />
  <input type="hidden" name="s" value="" />
  <input type="hidden" name="securitytoken" value="guest" />

      Email
<input type="text" class="bginput" name="vb_login_username" size="50" accesskey="u" tabindex="1" />

      Pass
<input type="password" class="bginput" name="vb_login_password" size="50" tabindex="1" />

        <input type="submit" class="button" value="Вход" accesskey="s" tabindex="1" />
        <input type="reset" class="button" value="Сброс" accesskey="r" tabindex="1" />

</form>

Начал с проверки нажатия кнопки "Сброс". Для этого заполнил поля ввода логина и пароля, и проверил заполнились ли они, да они заполнились.
Затем выполнил эмуляцию нажатия кнопки, но похоже она не сработала. Т.к потом еще раз прошелся по циклом по странице, но введенные значения логина и пароля остались, то есть нажатие на кнопку не сработало.
Что я делаю не так?
 foreach (IElement element in document.Body.QuerySelectorAll("div.panel > div > form > table > tbody > tr > td > input"))
        {
            if (element.GetAttribute("type") == "text")
            {
                element.SetAttribute("value", email);
                Console.WriteLine(element.GetAttribute("value")); // проверка, изменился ли атрибут value
            }
            else if (element.GetAttribute("type") == "password")
            {
                element.SetAttribute("value", pass);
                Console.WriteLine(element.GetAttribute("value"));
            }
            else if (element.GetAttribute("type") == "reset")
            {
                IHtmlElement div = (IHtmlElement)element;
                div.DoClick();
            }
        }

A: Потому что нужно делать submit form (отправку формы). Что-то в духе:
var document = browsingContext.Active.QuerySelector<IHtmlFormElement>("form#login").SubmitAsync(new
{
    do = "login",
    url = "/log-in.php",
}).Result;

Не очень удобно, что у вас форма не имеет id или класса - так что подбирайте селектор.
И проверить ваш пример не могу, так как не приведён пример сайта, а создавать код - долго, но у меня подобный код является вполне рабочим.


text:
Q: Can "without abandonment" mean "with abandon"? An author I'm currently reading often uses language in a slightly irregular fashion. I've been trying to decide if it's playful and intentional, which would be intriguing. If it's not intentional, then it's either an error on the author's part (fine) or on the editor's (less fine).
The current book includes the following (presumably wrong) phrase, in a scene where two people try to elude others.
"Without abandonment, she grabbed my hand and pulled me down the pavement"
Given the nature of the scene, I think it's supposed to mean "with abandon" but that doesn't totally fit. The only other guess I have is something along the lines of "without hesitation".
In this context, I think the phrase is used as a state of mind decriptor, not a literal one. Has anyone ever heard the phrase "without abandonment" used in this way?

A: They do not have opposite meanings, and yet they not synonyms either.
The noun abandonment means leaving something or someone behind.
The noun abandon means lack of restraint: it's about someone's manner or behaviour.
The sentence

Without abandonment, she grabbed my hand and pulled me down the pavement

is a tautology; she is not leaving the speaker behind.

A: It should be with abandon as in abandoning all care or inhibitions. Common 2nd language mistake. In this case though I think the writer was trying to say without leaving him or her there.

A:
In this context, I think the phrase is used as a state of mind descriptor, not a literal one.

Unfortunately, you seem to have omitted the actual context of the narrative and the source.
If "with abandon" is, approximately, "with no regard for the consequences" then, if the author is playing with words, "without abandonment" = intentionally and purposefully.
With context it might be a clever reference to the marine insurance use of abandonment, such that "without abandonment" would mean "not relinquishing ownership of me."


text:
Q: Парсинг string в int Есть код, который читает строку и парсит в int. Как заставить видеть переменную s как int?
line0 = line0;

Pattern pattern = Pattern.compile("\\d+\\S?\\d*");
Matcher matcher = pattern.matcher(line0);
while (matcher.find()) {
    String s = matcher.group(0);
    if (s.replaceAll("\\D", " ").length() == s.length()) {
        try {
            integers.add(Integer.parseInt(s));
        } catch (NumberFormatException e) {
        }
    }
}

int i = Integer.parseInt(s);
DaoImpl dao = new DaoImpl();
dao.save(i, line1, line2);

Получаю:
Exception in thread "main" java.lang.NumberFormatException: For input string: "79827956841"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:583)
at java.lang.Integer.parseInt(Integer.java:615)
at com.app.sms.reader.impl.SimpleSmsReader.smsReader(SimpleSmsReader.java:109)
at com.app.sms.reader.impl.SimpleSmsReader.readSms(SimpleSmsReader.java:51)
at com.app.workflow.impl.SimpleSmsWorkflow.processSms(SimpleSmsWorkflow.java:29)
at com.app.starter.Main.main(Main.java:33)

A: Эта ошибка возникает у Вас потому, что число "79827956841" не умещается в тип int.
Я попробовал вставить его в Integer.parseInt() без кавычек (как целое число) и получил следующую ошибку:
error: integer number too large: 79827956841
       System.out.println(Integer.parseInt(79827956841));

Могу посоветовать Вам использовать тип long.
P. S. Как я понял из Вашего стэк-трейса, число 79827956841 - телефонный номер. В таком случае, возможно, хранить номер в виде числа - не лучшая идея, так как чаще всего над номерами необходимо выполнять именно строковые операции. Ну, по крайней мере, я всегда работал с номерами как со строками. Конечно, я не отрицаю, что хранение в виде числа куда экономнее, так что, если у Вас подобный ход обусловлен именно экономией при хранении, прошу простить.

A: Число 79827956841 не помещается в знаковое 32 битное (-2 147 483 648 - 2 147 483 647)
Если вам нужно работать с такими большими числами используйте класс Long и соответственно метод Long.parseLong(). Допустимый диапазон значений от -263 до 263-1


text:
Q: Onboard charging system for hybrid electric tractor I'm in the process of converting a Cub Cadet SLT1554 from gas to a hybrid-electric tractor using a Motenergy ME0909 PMDC Motor. See description/specifications below:
Motenergy ME9090 PMDC Motor
12-48V, 4 hp cont, 12.8 hp pk
4 Hp Brush-Type PM DC. 4000RPM at 48VDC
The Motenergy ME0909 is a Brush-Type, Permanent Magnet DC motor with very high efficiency. Capable of 4.8 KW continuous and 15 KW for 30 seconds. For voltages from 12 to 48 VDC input and 100 amps continuous (300 amps for 30 seconds). Designed for battery operated equipment. It makes a great replacement for the original Etek motor because it has the same  bolt pattern and is actually lighter in weight.
Specifications
Power: 4 cont - 12.8 pk hp
Voltage: 12-48 Volt rated
Speed: 2150-4850 rpm
Size: 6" OD, (w/o shaft)
Shaft: 7/8" x 1-3/4", 3/16" key
Weight: 24 lbs.
Voltage Constant: 0.0107
Revolutions per volt: 93.45 RPM
Torque Constant: 0.102 Nm/Amp
Generated Current: 9.8A per Nm
If possible, I would like to operate the electric motor at 24 volts powered by two 12-volt deep cycle batteries in series.
At the same time in order to guarantee sustained power, I would like to have an onboard generator powered by an 8hp I/C horizontal shaft engine driving a 12 volt, 253 amp alternator recharging the batteries. I'm under the impression that I would need at least 2,984 watts of electricity to create 4hp, and 3,730 watts (5 hp) would be even better.
QUESTION: Is it possible to create some type of configuration so that a 12v alternator can charge two 12-volt batteries in series. Also, I'm concerned that the ME0909 ad speaks of only 100 amps for continuous service.
Would the battery not act as a "cushion" between the alternator and the electric motor?
Any assistance in this project will be greatly appreciated.

A: If you want to charge a 24V battery from a 12V alternator, you will need a huge boost converter, which will be spectacularly expensive.  It would be better to just buy an alternator designed for 24V systems, e.g. from a truck.
Yes, a battery can act as a short-term power source, which means that you can get a bit more power in the short term than the alternator can supply.  But you still need to pay attention to the thermal limits on the motor: 100A continuous or 300A for 30s (and probably off or very low load for a few minutes after a high-power burst, so that it can cool down again).
For example (totally making up numbers here) if you calculate that your average load will be 60A, you could use an 80A alternator.  It would supply the base load, and then when you want a 300A burst, you can pull that from the battery.  While the electric motor is cooling after its burst (e.g. drawing only 20A), the alternator will charge the battery.
With a motor of this design, voltage = speed and current = torque; normally you use a PWM speed controller which acts in conjunction with the motor's internal inductance to behave like a buck converter.  If you run it from 24V not 48V then you can put in only 24*100 = 2400W continuous (electrical) power; it will run half as fast on 24V (about 2400RPM) as it does on 48V (about 4800RPM) while providing the same torque (a function of the 100A limit).  If you want to get the full 4.8kW (electrical) / 4hp (mechanical) power, you need to run it at 48V and 4800RPM.
Note that the motor is rated as 4.8kW electrical and 4hp (3kW) mechanical.  That means its efficiency under full load is about 63%, which is terrible.  If you want 3kW of mechanical power, you need to supply 4.8kW of electrical power.
Because your choice of supply voltage affects motor speed, it will affect your choice of gearbox ratios.

A: The horsepower specifications are inconsistent with the kW specifications. Power specifications for electric motors usually refer to mechanical power delivered whether it is stated on horsepower or in kW. One horsepower is 0.746 kW.
If you operate the motor at 24 volts, you will only get half of the rated horsepower.
In order to charge the batteries with from a generator with a lower voltage rating, you need an electronic voltage boost converter.
You need to look at the recommended charging current for the batteries.
The 100 amp rating of the motor is consistent with the rated output power. 100 A X 48 V = 4800 W
Other than stating "very high efficiency" losses are being ignored.
Additional Comments
The 4 Hp specification seems to be from Robot MarketPlace. They seemed to have confused kW with horsepower. If you look at the "Power Curves" under the "Other Documentation" tab you can see that for operation at 48 volts and 100 amps, the motor produces about 87 lb-in torque and 4050 RPM. That is about 4.17 kW or 5.59 Hp. Since the input power is 4800 watts, the motor efficiency is about 86.9% at that point. You also need to consider controller efficiency, it should be in the neighborhood of 95%.
It seems to me that you should consider how you are going to use the tractor and what benefit you expect to gain from converting it to hybrid electric. Then make a block diagram of the system that you need and study the complete performance characteristics of the components. Make sure that you understand the performance of each component and know how to calculate the relevant parameters from the component specifications and performance requirements.


text:
Q: Inference rule for Non-Empty Domains I am currently experimenting with logic frameworks. I am basically
using something along dependent types as in "Proof-assistants using
Dependent Type Systems" by Henk Barendregt and Herman Geuvers. I then
came across the idea to formulate the following rule:
G, y:t |- s:A
------------- (declE) y not in G, A
   G |- s:A

I call this rule declaration elemination. It removes
declaring that the variable y has sort t und the side
condition is that the proved formula A does not contain
the variable y anymore.
Now I wonder whether this rule is necessary or not.
Can we for example prove:
1) If A is closed then all variable declarations
   are anyway discharged.
Or alternatively maybe we can highlight:
2) What formula A can be proved, not having a
   variable y free, and where we would later
   like to discharge the variable y.
Bye
P.S.: declE can be formulate as the expression
a:sort\b:prop\ ((x:a\b) -> b) where x not in b or
equivalently a:sort\b:prop\ ((a -> b) -> b).

A: When you say you are working in some (unspecified) logical framework, you are not really telling us what logic you are actually working in. However, in type theories that allow empty types, your rule is not admissible: declaring $y$ to be a member of an empty type is a nontrivial assumption.
If you logic does have all types non-empty, then your rule is admissible, but it depends on the other rules of your logic whether it is necessary.

A: It seems that what I am asking for is more or less Proposition
2.33 from Conal Elliott's PhD thesis, Extensions and
Applications of Higher-Order Unification.
Although the contexts/signatures are ordered. The proposition
reads as follows. if we have
D, v:t, G |- s:A

And if v does not occur in G, s, A, then we can derive:
D, G |- s:A

So the error I made in my question is that I did not think
of requiring v to not occur in s as well. And it seems that
it is irellevant whether t is non empty or not.


text:
Q: ASP.NET_Sessionid is getting renewed There is a button in my site in which you have to login first. When clicked, it retrieves a report from the ssrs report server and displays it on the same page.
I took note of the session ID it used in the request cookie.

Now when I clear my cache and run the report again it gets the following error "ASP.NET session has expired" but it gets a response cookie with a session ID.
Now here's the issue, when I click the button again. The site is able to retrieve the report from the ssrs report server but it uses the session ID of the response cookie.

Anyone has an idea on why this behavior is happening? Other threads didn't give me a thorough explaination.

A: What your describing sounds perfectly normal.
A session ID is essentially a pointer to a virtual memory space that contains a table of variables accessible to that user.  The table isn't kept forever-- if the ASP.NET framework doesn't see a session ID for a certain amount of time (say 20 or 30 minutes, depending on config), the memory space is released and reclaimed for other use.  If that session ID shows up later on, it won't know what to do with it and will give you a "session has expired" error.
The first session ID you saw is probably left over from a previous session.  It's old, and its memory space is gone, so ASP.NET gives you the error.
The second session ID is issued automatically for all requests that do not have a valid session.  ASP.NET will automatically create a memory space and a random key and send it back in that response cookie that you saw.  Now that your browser has an up-to-date session cookie, requests will work fine, as you can see when you click the button a second time.


text:
Q: Download HTML Text with Ruby I am trying to create a histogram of the letters (a,b,c,etc..) on a specified web page. I plan to make the histogram itself using a hash. However, I am having a bit of a problem actually getting the HTML.
My current code:
#!/usr/local/bin/ruby

require 'net/http'
require 'open-uri'

# This will be the hash used to store the
# histogram.
histogram = Hash.new(0)

def open(url)
    Net::HTTP.get(URI.parse(url))
end

page_content = open('_insert_webpage_here')

page_content.each do |i|
    puts i
end

This does a good job of getting the HTML. However, it gets it all. For www.stackoverflow.com it gives me:

Object Moved
This document may be found here

Pretending that it was the right page, I don't want the html tags. I'm just trying to get Object Moved and This document may be found here.
Is there any reasonably easy way to do this?

A: When you require 'open-uri', you don't need to redefine open with Net::HTTP.
require 'open-uri'

page_content = open('http://www.stackoverflow.com').read

histogram = {}
page_content.each_char do |c|
  histogram[c] ||= 0
  histogram[c] += 1
end

Note: this does not strip out <tags> within the HTML document, so x! will have { '<' => 4, 'h' => 2, 't' => 2, ... } instead of { 'x' => 1, '!' => 1 }. To remove the tags, you can use something like Nokogiri (which you said was not available), or some sort of regular expression (such as the one in Dru's answer).

A: See the section "Following Redirection" on the Net::HTTP Documentation here

A: Stripping html tags without Nokogiri
puts page_content.gsub(/<\/?[^>]*>/, "")

http://codesnippets.joyent.com/posts/show/615


text:
Q: Live Streaming Android (http or httplive) IS there anybody have run http live Streaming(discovered by Apple) on android device. I have some of Streaming Url. like "" www.abc/iphone/france24/allegro/fr/f24_fr.m3u8 "" type. My task is to make a app for android 3.0 OS type mobile.  Can anybody help me to make it.
The topic is new in android market.So that there is not much help on internet. I have got one of sample code to run livestreaming on android device.but it doesnt run urls that i have. these url are effectively working on IPAD or IPHONE.  Thanks

A: check out the issue in android bug report. replacing http with httplive worked for me.
Here is the sample code below from the bug report
private void playVideo(Integer Media) {
    doCleanUp();
    try {
        switch (Media) {
            case Globals.TEST_HTTP:
                path = "http://devimages.apple.com/iphone/samples/bipbop/gear1/prog_index.m3u8";
                break;
            case Globals.TEST_HTTPLIVE:
                path = "httplive://devimages.apple.com/iphone/samples/bipbop/gear1/prog_index.m3u8";
                break;
        }
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(path);
        mMediaPlayer.setDisplay(holder);
        mMediaPlayer.prepare();
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnVideoSizeChangedListener(this);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    } catch (Exception e) {
        Log.e(TAG, "error: " + e.getMessage(), e);
    }
}


text:
Q: Java data structure read numeric content from a string
Possible Duplicate:
Using Regular Expressions to Extract a Value in Java

For example, the input string is AB100FF10.  I need to read 100 and 10 from the string. Is there any classes/objects in Java that I can use?

A: try this
String[] nums = "AB100FF10".split("\\D+");
for (String num : nums) {
    System.out.println(num);
}

Other than that, you could try passing the string to a class like Scanner
Scanner scan = new Scanner("AB100FF10").useDelimiter("\\D+");
while (scan.hasNextInt()) {
    System.out.println(scan.nextInt());
}

Edit: using \\D instead of \\w as a delimiter, as Bohemian suggested in his answer and comments.

A: Just use split(<non-digits>), like this:
String[] numbers = "AB100FF10CCC".replaceAll("(^\\D*|\\D*$)", "").split("\\D+"); // "[100, 10]"

Now numbers contains an array of Strings that are all guaranteed to be numeric. You can use Integer.parseInt() to get ints.
The replaceAll("(^\\D*|\\D*$)", "") is used to trim non-digits from the front and back of the input string, otherwise split() will give you a blank string as the first/last element. It just makes to code simpler, rather than having to test the first/last specially.
As a method, it would look like this:
public static int[] parseInts(String input) {
    String[] numbers = input.replaceAll("(^\\D*|\\D*$)", "").split("\\D+");
    int[] result = new int[numbers.length];
    for (int i = 0; i < numbers.length; i++) {
        result[i] = Integer.parseInt(numbers[i]);
    }
    return result;
}

A: If you want to get only integers you can do the following:
ArrayList<Integer> numbers = new ArrayList<Integer>();
char[] characters = "AB100FF10".toCharArray();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < characters.length; i++) {
     if (Character.isDigit(characters[i]))
        buf.append(characters[i]);
     else if (buf.length() != 0) {
         numbers.add(Integer.parseInt(buf.toString()));
         buf = new StringBuffer();
     }
}

After that you will have an arrayList of numbers

A: I think pattern might be a better solution to because pattern object is more powerful comparing to simple String split() method.
for example, following code can resolve the same problem without any exception
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(test[0]);
while(m.find()){
  int x = Integer.parseInt( m.group() );
}

But if I use String.split(), there is one NumberFormatException is hard to dealt with.For example, below code can't escape NumberFormatException
for(int i = 0 ; i < test.length; i++){
  String[] numstr= test[i].split("\\D+");
  try{
    for(int j=0; j<numstr.length;j++){
      if( numstr[j] == null || numstr[j] == ""){
    System.out.println("empty string \n");
      }
      else
       Integer.parseInt(numstr[j]);
  }catch(NumberFormatException ie){
      ie.printStackTrace();
  }
}


text:
Q: Can I prevent music through an AirPod from pausing when a single pod is removed? Right now, when I remove one AirPod from an ear, the currently playing track pauses in the other ear.
Instead, I want to continue playing the track.
My control over this using bluetooth settings is quite limited, so I'm hoping there is another location to investigate to disable this feature.

A: Head into Settings > Bluetooth > AirPods > Turn Off Automatic Ear Detection feature
When the automatic ear detection feature is turned off, audio will continue to play even fi you take the AirPods out of your ears.


text:
Q: Managing android's backstack I have an activity hierarchy and I have a button that allows me to go from activity D to activity B.

The thing is that going to B from D would leave C on the backstack, so if I do A->C->D->B and then press back it would send me to C, and not to A (which is what I want).
Is there a way to delete C when I click on the button from B, or is there some kind of workaround?

A: Consider using A as a dispatcher. When you want to launch B from D and finish C in the process, do this in D:
// Launch A (our dispatcher)
Intent intent = new Intent(this, A.class);
// Setting CLEAR_TOP ensures that all other activities on top of A will be finished
//  and setting SINGLE_TOP ensures that a new instance of A will not
//  be created (the existing instance will be reused and onNewIntent() will be called)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Add an extra telling A that it should launch B
intent.putExtra("startB", true);
startActivity(intent);

in A.onNewIntent() do this:
@Override
protected void onNewIntent(Intent intent) {
    if (intent.hasExtra("startB")) {
        // Need to start B from here
        startActivity(new Intent(this, B.class));
    }
}

A: I don't know the specifics of how you're calling B, C and D or what data is getting passed around, but you can close C when you call D if you want.
In C, when starting D, you could do this:
Intent intent = new Intent(this, D.class);
startActivity(intent);
finish();

The finish will close C after starting D.
Again, without much info this is just a shot in the dark though.


text: Q: Methods to prove axiom independence What methods have been used to prove the independence of axioms? For instance, in many abstract algebra books the axiom of choice is stated to be independent of all the other axioms of set theory, but the proof/justification of this often left out.


text:
Q: Managing MySQL Database with Android I created an Android app that interacts with a MySQL database using a PHP file on a server.
I created a final string EXTRA_SOLDE to send with the intent to the other activity to show the result.
Everything is all right, but in the other activity, the TextView is blank as if nothing got sent. Please help.
This is my PHP file:
<?php
unset($_GET);

if( isset($_POST['username'])) {

    echo '<?xml version="1.0"?>'."\n";
    echo "<login>\n";

    // host doit être remplacé par le serveur de la base de données.
    // user représente le nom d'utilisateur de la base de données.
    // pass est le mot de passe pour accéder à cette base de données avec cette
// utilisateur.
    $con = mysql_connect("mysql6.000webhost.com","","");
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("a1287023_auth",$con);

    if(get_magic_quotes_gpc()) {
        $login = stripslashes($_POST['username']);
    } else {
        $login = $_POST['username'];
    }

    unset($_POST);

    $kid = login($login);
    if($kid == -1) {
        error(3);
    } else {
        printf('    <user id="%d"/>'."\n",$kid);
    }

    echo "</login>";
}

function error($ec) {
    printf('    <error value="%d"/>'."\n".'</login>',$ec);
    die();
}

function login($login) {
   $select = "
        SELECT epargne
        FROM auth_table
        WHERE user_id = '$login'
        ";
    $fixedlogin = mysql_real_escape_string($login);
    $query = sprintf($select, $fixedlogin);
    $result = mysql_query($query);
    if(mysql_num_rows($result) != 1) { return -1; }
    $row = mysql_fetch_row($result);
    return $row[0];
    return $row[1];
}

?>

And this is my activity that calls the PHP file set on a server.
public void onClick(View v){
    Intent intent = getIntent();

    if (intent != null) {
        String valeur=intent.getStringExtra(EXTRA_USER);
        doLogin(valeur);
    }
    }
});}

private void doLogin(final String login) {
    // Création d'un thread
    Thread t = new Thread()
    {
        public void run()
        {
            Looper.prepare();
            // On se connecte au serveur afin de communiquer avec le PHP
            DefaultHttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);

            HttpResponse response;
            HttpEntity entity;

            try
            {
                // On établit un lien avec le script PHP
                HttpPost post = new HttpPost(UPDATE_URL);

                List<NameValuePair> nvps = new ArrayList<NameValuePair>();

                nvps.add(new BasicNameValuePair("username", login));

                post.setHeader("Content-Type", "application/x-www-form-urlencoded");
                // On passe les paramètres login et password qui vont être récupérés
                // par le script PHP en post
                post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
                // On récupère le résultat du script
                response = client.execute(post);

                entity = response.getEntity();

                InputStream is = entity.getContent();
                // On appelle une fonction définie plus bas pour traduire la réponse
                read(is);
                is.close();

                if (entity != null)
                    entity.consumeContent();
            }
            catch (Exception e)
            {
                progressDialog.dismiss();
                createDialog("Error", "Connexion Impossible");
            }
            Looper.loop();
        }
    };
    t.start();
}

private void read(InputStream in)
{
    // On traduit le résultat d'un flux
    SAXParserFactory spf = SAXParserFactory.newInstance();

    SAXParser sp;

    try
    {
        sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        // Cette classe est définie plus bas
        LoginContentHandler uch = new LoginContentHandler();

        xr.setContentHandler(uch);

        xr.parse(new InputSource(in));

    }
    catch (ParserConfigurationException e)
    {

    }
    catch (SAXException e)
    {

    }
    catch (IOException e)
    {
    }

}

class LoginContentHandler extends DefaultHandler
{
    // Classe traitant le message de retour du script PHP
    private boolean in_loginTag = false;
    private int userID;
    private String money ;
    private boolean error_occured   = false;

    public void startElement(String n, String l, String q, Attributes a)

    throws SAXException
    {
        if (l == "login")
            in_loginTag = true;
        if (l == "error")
        {
            progressDialog.dismiss();
            switch (Integer.parseInt(a.getValue("value")))
            {
                case 1:
                    createDialog("Error", "Couldn't connect to Database");
                    break;
                case 2:
                    createDialog("Error", "Error in Database: Table missing");
                    break;
                case 3:
                    createDialog("Error", "Invalid username and/or password");
                    break;
            }
            error_occured = true;
        }

        if (l == "user" && in_loginTag && a.getValue("id") != "")
            // Dans le cas où tout se passe bien on récupère l'ID de l'utilisateur
            userID = Integer.parseInt(a.getValue("id"));
        money = String.valueOf(userID) ;

    }

    public void endElement(String n, String l, String q) throws SAXException
    {
        // on renvoie l'id si tout est ok
        if (l == "login")
        {
            in_loginTag = false;

            if (!error_occured)
            {
                progressDialog.dismiss();
                Intent i = new Intent(Budget.this,Epargne.class);
                i.putExtra(EXTRA_SOLDE,money);

                startActivity(i);

            }
        }
    }

    public void characters(char ch[], int start, int length)
    {
    }

    public void startDocument() throws SAXException
    {
    }

    public void endDocument() throws SAXException
    {
    }

}

}

A: it simple for a beginner to use user as Root and without Password!!
In your Php file use no password!
and Set ur PhpmyAdmin setting to root!
PHP -file
*define('DB_SERVER', "localhost"); // db server
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "diplom"); // database name*


text:
Q: Multi-column dependent countifs in Google Sheets Let's say I have 3 columns. I am trying to find the count of Zeros in the 3rd column IF column A is X AND column B is Y.
Is this possible? I've seen other people ask similar questions, but not seeing an answer anywhere. I know how to do the basic "if cell in column A is X, then count #-of-zeros in column B," but I don't know how to extend that dependency to an additional column.  I.e., If A is x, and if B is y, then count C.
Almost everything except the right answer.
=COUNTIFS('1H Run Values'!N:N,"0"&'1H Run Values'!T:T,"A",'1H Run Values'!S:S,"<=200")

does not work.

n/a

A: try like this:
=COUNTIFS(A:A, "=x", B:B, "=y", C:C, 0)


text:
Q: How do I print a struct instance in the console without displaying it's whole stacktrace in Julia? There are two Julia files :
file1.jl
struct MyStruct
    attribute :: String
end

file2.jl
module myModule
    include("file1.jl")
    println(MyStruct("a"))
end

When I execute file2.jl, it's supposed to print an instance of MyStruct
user@user-MS-7823:~$ julia cpsld/file2.jl
Main.myModule.MyStruct("a")
user@user-MS-7823:~$

I was expecting it to only print the struct name (so MyStruct("a")), however I got surprised as it also prints all the modules name, which is a bit annoying...
Is there any way not to print the modules along with the struct name?

A: You can use IOContext like this:
module myModule
    struct MyStruct
        attribute :: String
    end
    println(IOContext(stdout, :module=>myModule), MyStruct("a"))
end

(the fact that you have definitions split into two files is irrelevant here)

A: Thanks @Bogumił Kamiński for your solution.
The problem is that this only works for printing (ok, I know that's why I asked for lol).
Imagine I have three files.
file1.jl
module myFirstModule
    struct MyStruct
        attribute :: String
    end
end

file2.jl
module mySecondModule
    include("file1.jl")
    include("file3.jl")
    myThirdModule.hello(myFirstModule.MyStruct("a"))
end

file3.jl
module myThirdModule
    include("file1.jl")
    function hello(arg)
        println("argument : ", arg)
        println("isa test : ", isa(arg, myFirstModule.MyStruct))
    end
end

Well, there, the second module creates an instance of myStruct, and calls the "hello" function from the third module with that instance as an argument.
That is the console output :
argument : Main.mySecondModule.myFirstModule.MyStruct("a")
isa test : false

As you can see, the result of the isa test is false.
This acutally means that arg's type isn't myFirstModule.MyStruct, but when I print arg, as you can see I'm getting this : Main.mySecondModule.myFirstModule.MyStruct("a")
Does it mean that myFirstModule.MyStruct != Main.mySecondModule.myFirstModule.MyStruct ?


text:
Q: Pdf corrupted when downloading from BD in Primefaces? I have a problem downloading a pdf file, I get it from Database (Sql Server 2008 R2), the data is of type image in BD, but I capture in a blob and then turn it into byte array.
But to transform it into a StreamedContent to download the pdf file goes corrupted and I can not open it.
Code Java DaoImpl:
@Transactional(readOnly=true)
@Override
public DetalleSolicitudBean obtenerDocumentoImg(DetalleSolicitudBean detalle) throws Exception {
StringBuilder sql = new StringBuilder();
sql.append("SELECT iCorImagen, siCodMun, iCodDocumento, ");
sql.append("vNomArcDig, imgImagen ");
sql.append("FROM GAImgDocumento ");
sql.append("WHERE iCodDocumento = ? AND siCodMun = ? ");
List<DetalleSolicitudBean> lista = jdbcTemplateImgDoc.query(sql.toString(),
      new Object[] { detalle.getIcodDocumento(), detalle.getSiCodMun() },
      new RowMapper<DetalleSolicitudBean>() {
         public DetalleSolicitudBean mapRow(ResultSet rs, int rowNum) throws SQLException {
            DetalleSolicitudBean det = new DetalleSolicitudBean();
            det.setIcodImagen(rs.getShort("iCorImagen"));
            det.setSiCodMun(rs.getShort("siCodMun"));
            det.setIcodDocumento(rs.getInt("iCodDocumento"));
            det.setVnomArcDig(rs.getString("vNomArcDig"));
            Blob blob = rs.getBlob("imgImagen");
            byte[] imagen = blob.getBytes(1L, (int) blob.length());
            det.setImgImagen(imagen);
            return det;
         }
      });
}

Code Java Controller:
private StreamedContent file;

---------------------------------------
    DetalleSolicitudBean detalle = new DetalleSolicitudBean();
    detalle.setIcodDocumento(Integer.valueOf(codigoDocumento));
    detalle.setSiCodMun(Constantes.CODIGO_MUNICIPALIDAD);
    DetalleSolicitudBean imagenDocSolicitud = iSolicitudService.obtenerDocumentoImg(detalle);
    if(imagenDocSolicitud == null){
       addWarnMessage(null, getMessage("solicitudes.form.valAdjDocAsociado"));
    }else{
       InputStream stream = null;
       try {
          String nameFile = imagenDocSolicitud.getVnomArcDig();
          stream = new ByteArrayInputStream(imagenDocSolicitud.getImgImagen());
          file = new DefaultStreamedContent(stream, "application/pdf", nameFile);
       } catch (Exception ex) {
          depurador.error(getGenerarError(Thread.currentThread()
                .getStackTrace()[1].getMethodName(),
                Constantes.NIVEL_APP_CONSTROLLER,
                this.getClass().getName(), ex.getMessage()));
       } finally {
          stream.close();
       }
    }

Code .xhtml:
<p:dataTable id="tblSolicitudes" var="item"
   value="#{cBusquedaSolicitud.listSolicitudes}"
   rowIndexVar="rowIndex" lazy="true" rows="10"
   paginator="true" paginatorPosition="top"
   rowKey="#{solicitud.codSolicitud}"
   selection="#{cBusquedaSolicitud.selectSolicitud}">

   ....

   <p:column style="text-align: center;">
      <p:commandLink actionListener="#{cAtencionSolicitud.descargarDocumento}"
         rendered="#{item.icodDocumento != null}" ajax="false"
         action="docVistaEscrito" update=":listaMensajes">
         <span class="ui-icon ui-icon-pdf" />
         <f:param name="paramDocumento" value="#{item.icodDocumento}" />
         <p:fileDownload value="#{cAtencionSolicitud.file}" />
      </p:commandLink>
   </p:column>
</p:dataTable>

A: You don't need field file in class controller. You should have method in your controler:
public StreamedContent getFile(){}

A: I was testing it and I think the problem saving to save the pdf to the database (so I think I bring a damaged pdf).
The pdf file I keep it as a byte array.
Code Java Controller:
public void guardarDocSolicitud(){
   try{
      if(this.fileDocSolicitud) == null){
         addWarnMessage(null, getMessage("solicitudes.form.valAdjuntarDocumento"));
      }else{
         InputStream stream = null;
         try {
            stream = this.fileDocSolicitud.getInputstream();
            byte[] b = new byte[stream.available()];
            this.detalle.setImgImagen(b);
            this.detalle.setVnomArcDig(this.fileDocSolicitud.getFileName());
            iSolicitudService.guardarDocumentoImg(detalle, getCVariableSesion().getSiCodUsu(), getCVariableSesion().getCnomTer());
         } catch (IOException ex) {
            depurador.error(getGenerarError(Thread.currentThread()
                  .getStackTrace()[1].getMethodName(),
                  Constantes.NIVEL_APP_CONSTROLLER,
                  this.getClass().getName(), ex.getMessage()));
         } finally {
            stream.close();
         }
         addInfoMessage(null, getMessage("msg.info.operacionExitosa"));
         buscar(null);
      }
   }catch (Exception ex) {
      addErrorMessage(null, getMessage("msg.error.errorGrabar"));
      depurador.error(getGenerarError(Thread.currentThread()
            .getStackTrace()[1].getMethodName(),
            Constantes.NIVEL_APP_CONSTROLLER,
            this.getClass().getName(), ex.getMessage()));
   }
}

Code Java DaoImpl:
@Transactional
@Override
public void guardarDocumentoImg(DetalleSolicitudBean detalle) throws Exception {
   try{
      StringBuilder sql = new StringBuilder();
      sql.append("INSERT INTO GAImgDocumento ");
      sql.append("(iCorImagen, siCodMun, iCodDocumento, ");
      sql.append("vNomArcDig, imgImagen, bActivo, ");
      sql.append("siCodUsu, sdFecAct, cNomTer) ");
      sql.append("VALUES(?,?,?,?,?,?,?,?,?) ");
      jdbcTemplateImgDoc.update(sql.toString(),
           new Object[] { detalle.getIcodImagen(), detalle.getSiCodMun(), detalle.getIcodDocumento(),
                     detalle.getVnomArcDig(), detalle.getImgImagen(), Constantes.TRUE,
                     detalle.getSiCodUsu(), detalle.getSdFecAct(), detalle.getCnomTer()
      });
   }catch(Exception e){
      throw new Exception( getGenerarError(Thread.currentThread().getStackTrace()[1].getMethodName(),
                      Constantes.NIVEL_APP_DAO,
                      this.getClass().getName(),
                      e.getMessage()) );
   }
}


text:
Q: no alert when two value are called with jquery Neither of the alert box works for following code -
var genvalue=('input[#gender]:checked').val());
alert (genvalue);

var value = $("#edu_det1").val();
alert (value);

But when  genvalue, the whole portion of code is remove it work. Don't know what the problem

A: you are missing $. (jquery object). try to include your jquery library. or else you can use Jquery CDN
var genvalue=('input[#gender]:checked').val());// here $ is missing

use the CDN
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' type='text/javascript'>

A: If you are trying to get an element with an ID, just target that ID as it should be unique :
var genvalue = $('#gender').val();
alert (genvalue);

var value = $("#edu_det1").val();
alert (value);

Otherwise you can also do :
var genvalue = $('input[id="gender"]:checked').val();

But that sort of defeats the point of having an ID !

A: This is correct code and you have missed $
var genvalue=$('input[#gender]:checked').val());
alert (genvalue);

var value = $("#edu_det1").val();
alert (value);

If you are applying something else then it might not work properly. The correction as per your code is that much only but if you need more correction still getting wrong you need to give some more code snippets.
Well try this to get more information and learn about jquery value selection method


text: Q: How to protect a rest api for android app I have an android app that fetches and inserts data to db using rest api hosted on a shared hosting platform. My problem is whenever if someone types the end point of my url in browser they can see all the folders and files. How to restrict access to my android app only. By the way I am not using authentication in my app. How do I restrict my end points to be accessed only from the app


text:
Q: String comparison in Bash script not working I wrote the following script in Bash but it is not printing the desired output:
a="abc"

if (test "$a"="$a ") then
    echo "true "
else
    echo "false "
fi

This script should print false but it isn't. I'm new to Bash scripting, so can anyone please tell me why it is not printing false?

A: You're giving test only one argument: "$a"="$a ", which is equivalent to "$a=$a ". When test gets only one argument, it evaluates to 0/true/success if that argument contains at least one character, and to 1/false/error otherwise. The minimal fix would be to put spaces around the =, so you're giving it three separate arguments:
if (test "$a" = "$a ") then

but I'd really recommend writing it in a Bashier style:
if [[ "$a" = "$a " ]] then

(Note that the ( and ) in the original version merely cause test to be run in a subshell, which really serves no purpose at all.)


text:
Q: How to create equivalent of Java's CardLayout or ASP:MultiView with UIView and subViews? Ideally I'd like to be able to create the views in Interface Builder and then swap them with code.
Any pointers to sample code or tutorials would be appreciated.

A: This is exactly what the pairing of UIViewController and UIView lets you do.  You can lay out the UIView for a UIViewController in Interface Builder, and then just use them from your code with ease.


text:
Q: ShortName in the Display attribute (DataAnnotations) Name attribute works proper, but ShortName doesn't work.
[Display(Name = "Date of the transfer the task", ShortName = "Trans date")]
public DateTime TransferDate { get; set; }

Even when I delete Name attribute, ShortName is ignored ("TransferDate" displays in the column header).
In the view I do this:
@Html.DisplayNameFor(model => model.TransferDate)

A: If you look at the Description for the ShortName property on the Display Attribute you'll see that it has a pretty limited scope out of the box:

Of course, that doesn't limit you from leveraging that value on your Model Metadata, but there aren't any native helpers that do so.
Starting with MVC 2, ModelMetadata provides two methods to access the underlying data: FromStringExpression and FromLambdaExpression, so you don't really need to start from scratch in writing your own helper or extension method.
If you hate writing HTML helper methods, you can do this all inline:
@ModelMetadata.FromLambdaExpression<RegisterModel, string>(
            model => model.TransferDate, ViewData).ShortDisplayName} )

But it's also perfectly valid to add an extension method for consistency of access, deduplication of code, and improved error handling
public static class MvcHtmlHelpers
{
   public static MvcHtmlString ShortNameFor<TModel, TValue>(this HtmlHelper<TModel> self,
           Expression<Func<TModel, TValue>> expression)
   {
       var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
       var name = metadata.ShortDisplayName ?? metadata.DisplayName ?? metadata.PropertyName;

       return MvcHtmlString.Create(string.Format(@"<span>{0}</span>", name));
   }
}

And then use like any other helper method:
@Html.ShortNameFor(model => model.TransferDate)

Further Reading:

*

*How do I display the DisplayAttribute.Description attribute value?

*MVC has long subsisted on custom extension methods, like needing DisplayNameFor before it was added in MVC 4

*See this question for a quick breakdown of the differences between [Display(name="")] vs. [DisplayName("")] attributes

*See this answer for working with ASP.NET MVC 6 / Core 1


text:
Q: Why adding tabs to mat-tab-group doesn't work from separate component? I try to do something like this in a component:
   <mat-tab-group>
     <mat-tab label="Zero">Contents for zero</mat-tab>
     <app-tabs-container></app-tabs-container>
   </mat-tab-group>

tabs-container.component.html:
<mat-tab *ngFor="let tab of tabs; let index = index" [label]="tab">
    Contents for {{tab}} tab
</mat-tab>

tabs-container.component.ts:
tabs = ['First', 'Second', 'Third'];

But it doesn't work. However it works  when I put it all in the component directly:
   <mat-tab-group
     <mat-tab label="Zero">Contents for zero</mat-tab>
     <mat-tab *ngFor="let tab of tabs; let index = index" [label]="tab">
        Contents for {{tab}} tab
    </mat-tab>
   </mat-tab-group>

There is no error or anything. In TabsContainerComponent property tabs is initialized, constructor is called but tabs First-Third are not shown. What is the reason and is it possible to fix?
EDIT: Also if separate component has only 1 tab it's not shown.
tabs-container.component.html:
<mat-tab label="Single tab">
   Contents for single tab
</mat-tab>


text:
Q: teamcity ci/cd - how to install composer and phpunit In TeamCity and CI/CD I want to automate the pipeline of my laravel project.
I'm stuck right now in build steps - since I'm using php I need to install php, composer and phpunit test, but I don't know which commands I should use to install php composer and phpunit. Does anyone know the commands?


text:
Q: Azure Data Factory Incremental data refresh for CosmosDB using change feed when Dataflow->Source is chosen as query I would like to write CosmosDB query as a source within dataflow where Dataflow->Source is set to CosmosDB and Source Option-Input set as Query. Change Feed option available with checkbox disabled and dynamic query available. Say for example query
Select empId, EMPName, joining date from employee

and only modified data /new data to be pushed in target as feed. How to write dynamic content for change feed in this scenario?
Change Feed Option
Expecting an example how to write dynamic content for change feed option for CosmosDB as source when source is chosen as **query **instead **collection **inside Dataflow.


text:
Q: Posting 2 Values on one mysql_query drop down DB MAP:
Carriers "table1": carriername, carrierid, ect... Post data
carrierinfo "table2": carriername, id, contact, ect... carrier list

I am using mysql_query from table2 for my carriername drop down. Using this I am able to post a carrier name to table1. I am trying to use the same drop down to post the related id from the selcected carriername. So in short I need to have one drop down that displays only the Carrier names but querys both  carriername & id from table2. When the form is posted I need to post to the carriername & carrierid to table1. Below is the drop down I am using. Please let me know how I can connect the dots and add what is needed. If its possible.
 <?php

if (isset($_POST["submit"]) && $_POST["submit"] == "Submit")
{
    for ($count = 1; $count <= 9; $count++)
    {
        $fields[$count] = "";
        if (isset($_POST["field" . $count . ""]))
        {
            $fields[$count] = trim($_POST["field" . $count . ""]);
            //echo $fields[$count] . "
";
        }
    }

    $con = mysql_connect("", "", "");
    mysql_select_db("", $con);

    $carrierid = mysql_real_escape_string($_POST['carrierid']);
    $fromzip = mysql_real_escape_string($_POST['fromzip']);
    $tozip = mysql_real_escape_string($_POST['tozip']);
    $typeofequipment = mysql_real_escape_string($_POST['typeofequipment']);
    $weight = mysql_real_escape_string($_POST['weight']);
    $length = mysql_real_escape_string($_POST['length']);
    $paymentamount = mysql_real_escape_string($_POST['paymentamount']);
    $contactperson = mysql_real_escape_string($_POST['contactperson']);
    $loadtype = mysql_real_escape_string($_POST['loadtype']);
    $date = mysql_real_escape_string($_POST['date']);

    $insert = "INSERT INTO Carriers (`carriername` ,`carrierid`, `fromzip` ,`tozip` ,`typeofequipment` ,`weight` ,`length` ,`paymentamount` ,`contactperson` ,`loadtype` ,`date`)
    SELECT carriername ,'$carrierid' ,'$fromzip' ,'$tozip' ,'$typeofequipment' ,'$weight' ,'$length' ,'$paymentamount' ,'$contactperson' ,'$loadtype', NOW()) FROM carrierinfo WHERE id = '$carrierid'";

    mysql_query($insert) or die(mysql_error());

    $select = "SELECT `carriername` ,`fromzip` ,`tozip` ,`typeofequipment` ,`weight` ,`length` ,`paymentamount` ,`contactperson` ,`loadtype` FROM `Carriers` ORDER BY `date` DESC;";
    $result = mysql_query($select) or die(mysql_error());

}
?>

<input type="button" onclick="window.location.href='search.php';" value="Search Board" />

<form action="" method="post";">

    Carrier:
 <?php

$con = mysql_connect("", "", "");
    mysql_select_db("", $con);

$query=("SELECT * FROM carrierinfo");

$result=mysql_query($query) or die ("Unable to Make the Query:" . mysql_error() );
echo "<select name='carrierid'>";
while($row=mysql_fetch_array($result)){
echo "<OPTION VALUE='".$row['id']."'>".$row['carriername']."</OPTION>";
}
echo "</select>";

?>

              Load Type:
              <select name="loadtype">
              <option></option>
              <option value="TL">Truck Load</option>
              <option value="Partial">Partial</option>
              </select>

              Pick Zip:	 <input id="fromzip" name="fromzip" maxlength="50"
 style="width: 100%;" type="text">

              Drop Zip:	 <input id="tozip" name="tozip" maxlength="50"
 style="width: 100%;" type="text">

              Weight:	 <input id="weight" name="weight" maxlength="50"
 style="width: 100%;" type="text">

              Length:	 <input id="length" name="length" maxlength="50"
 style="width: 100%;" type="text">

        Equip:
              <select name="typeofequipment">
              <option></option>
              <option value="AUTO">Auto Carrier</option>
              <option value="DD">Double Drop</option>
              <option value="F">Flatbed</option>
              <option value="LB">Lowboy</option>
              <option value="Rail">Rail</option>
              <option value="Ref">Reefer</option>
              <option value="RGN">Removable Goose Neck</option>
              <option value="SD">Step Deck</option>
              <option value="TANK">Tanker (Food, liquid, etc.)</option>
              <option value="V">Van</option>
              </select>

              Contact:	 <input id="contactperson" name="contactperson" maxlength="50"
 style="width: 100%;" type="text">

              Rate:	 <input id="paymentamount" name="paymentamount" maxlength="50"
 style="width: 100%;" type="text">

<input name="submit" value="Submit"
 class="submit" type="submit"><input type="button" onclick="window.location.href='newcarrier.php';" value="Add Carrier" />

</form>

A: Use a join:
SELECT t1.carrierid, t2.carriername, t2.id
FROM table1 t1 JOIN table2 t2 USING (carriername)

Joining tables should be one of the first things you learn when studying SQL.
UPDATE:
Never mind the above, your original query to populate the dropdown was correct. When you populate the select, you should do:
echo "<select name='carrierid'>";
while($row=mysql_fetch_array($result)){
  echo "<OPTION VALUE='".$row['id']."'>".$row['carriername']."</OPTION>";
}
echo "</select>";

When posting the data, get rid of this line:
$carriername = mysql_real_escape_string($_POST['carriername']);

and change the insert query to:
$insert = "INSERT INTO Loads (`carriername` ,`carrierid`, `fromzip` ,`tozip` ,`typeofequipment` ,`weight` ,`length` ,`paymentamount` ,`contactperson` ,`loadtype` ,`date`)
  SELECT carriername ,'$carrierid' ,'$fromzip' ,'$tozip' ,'$typeofequipment' ,'$weight' ,'$length' ,'$paymentamount' ,'$contactperson' ,'$loadtype', NOW())
  FROM Carriers
  WHERE id = '$carrierid'";

The change to the form makes it display the carrier name, but return the ID in the post data.  Then the new INSERT query uses that ID to get the carrier name from table 2 and combine that with all the other post data when inserting into table 1.


text:
Q: Syntax error: can't assign value to operator while implementing k-nearest neighbour classifier *Edited to include full error stack
Forgive me if this is a silly question, i am a total noob.
I'm creating a k-nearest neighbor classifier in python using numpy. But when i try to run knn_classifier.predict() on CIFAR-10 images (reshaped into 1-D arrays), i get this error.
File "<ipython-input-9-9df7a1ae9044>", line 1
    y-pred = knn.predict(x_ts, k=5)
                                   ^
SyntaxError: can't assign to operator

This didn't happen when i hadn't included 'k'(method varibale in predict) in an earlier version of the classifier, so i'm assuming its related to 'k', but i can't figure out what i'm doing wrong.
This is what I wrote:

   class knn_classifier:

     def __init__(self):

       pass

     def train(self, x, y):

       self.xtr = x
       self.ytr = y

     def predict(self, x, k=1):

       num_images = x.shape[0]
       y_pred = np.zeros(num_images, dtype=self.ytr.dtype)
       for i in range(num_images):
         distance = np.sum(np.abs(self.xtr - x[i,:]), axis=1)
         lowest = np.argsort(distance)
         lowest = lowest[:k]
         lowest_k = list(self.ytr[lowest])
         y_pred[i] = np.argmax(np.bincount(lowest_k))
       return y_pred

A: This is just a typo. You wrote "y-pred" with a dash rather than an underscore, which Python interprets as the operation y minus pred.


text:
Q: BJT transistors AND gate I am trying to build a simple AND gate using 2 2N2222 transistors and the +5V source from an Arduino board. At first I tried the circuit without the R1 and R2 resistors but the output was 1 when B was 1 (second input) and 0 otherwise, regardless of A. After adding R1 and R2, if only B is 1 and A is 0 then the LED is dimly lit and if both inputs are 1 then the LED is brightly lit. Can I make it such that only when both inputs are true the LED is lit and off otherwise?

I also measured the current between R2 and Q2 and I'm not quite sure how to interpret the readings or what they mean. With the ampmeter on the scale 2m, with A = 1 the display reads .406 (which I presume means 0.4 mA?) and with the scale 20m, with A = 0, the display reads 2.23 (2.23 mA?) and with A = 1 the display reads 0.43 (which means 0.43 mA?). Am I reading the values correctly off the ampmeter and why does the current through B change if A is connected orn ot?

A: Your basic circuit is a shot in the right direction BUT it would only work properly if you would use NMOS transistors insteat of bipolar ones.
The problem with NPNs here is that if Q1 is off but you're switching Q2 on, Q2 will behave as a diode pulling the voltage across R3 and D1 up. So D1 starts to light up (a bit). When you also switch on Q1 then more current can flow and Q2 will operate in saturation, the LED will light up more.
If you can, try using NMOSFETs, two 2n7000 would to the trick I guess.
It can also be done with NPNs but then you would need to build a NAND first and then invert it's output OR (even simpler) connect the LED in series with R2 in the schematic from this tutorial.

Place LED in series with R2: Done :-)


text:
Q: Alternaitive function to Matlab's esort.m I need to sort a vector of eigenvectors Ev (obtained from  [Ev, Ed] = eig (A)) in descending order. I also need indices used in the sort.
I cannot use esort.m which comes with the controls system toolbox (which I don't have and cannot get). Is there an alternative function to esort.m which I can use?
Thanks.

A: Using the function sort, real and imag you can "copy" the esort function:
imre = rand(10,1)+rand(10,1)*1i; %random imaginary number

re = real(imre);                 %extract the real part
im = imag(imre)*1i;              %extract the imaginary part

[sorted,ind] = sort(re);         %sort according to the real part
imre_sort = sorted+im(ind);      %add the imaginary part.

So simply a function similar to:
function imre_sort = todelete(imre,ord)
%ord can be 'ascend' or 'descend'
    if nargin == 1
        ord = 'ascend';
    end

    re = real(imre);
    im = imag(imre)*1i;

    [sorted,ind] = sort(re,ord);
    imre_sort = sorted+im(ind);

end


text:
Q: 14.04: Icons missing in system settings This problem has appeared here before, but in my case it has a special twist:
I am running Ubuntu 14.04, fresh install, no upgrade.

*

*the icon for the System settings shown in the launcher (the wheel with a stick through it) is perfectly there when I first start a session. However, after clicking on it once, it just disappears and a question mark on a gray background shows up.
The same happens with the terminal icon in the launcher: first it is there, after opening one terminal and then closing it again, the icon is gone.

*Inside the System Settings all the items are there and can be clicked (and work), but many of them have no icon.
I have tried all the remedies given in the earlier posts. None of them works. In particular, sudo apt-get install ubuntu-desktop shows no change.
Running gnome-control-center in a terminal gives first a lot of error messages of the kind
** (unity-control-center:3443): WARNING **: Could not find icon 'preferences-desktop-wallpaper'
So, what to do?

A: use this command in Terminal then reboot your system.
 sudo apt-get install ubuntu-desktop


text:
Q: Latency with animationiteration So I've got this modal that I've designed to be opened via a checkbox input, but the problem with that was that I have my divs and section arranged in such a manner that #yt-modal-cont can't be in the same container as my input due to z-index issues. So I used javascript:
if(modalToggle.checked === true) {
  oLay.style.display = 'block';}

Simple enough fix, however, that's not my issue. For the animation, the route I chose was:
#yt-modal-cont {
  animation: fade-before 0.3s ease-out 0s 2 alternate-reverse;
}

@keyframes fade-before {
  0%{opacity:1;}
  100%{opacity:0;}
}

<script>
  var oLay = document.getElementById('yt-modal-cont');
  var modalToggle = document.getElementById('vids');

  function fadein(){
    oLay.style['animation-play-state'] = 'paused';
  }

  function isOpen(){
    if(modalToggle.checked === true) {
       oLay.style.display = 'block';}
       oLay.addEventListener('animationiteration', fadein);
    }
  }
  modalToggle.addEventListener('click', isOpen);
</script>

and then for the closing function I have it setting animation-play-state=running to play through to the end, but that's not relevant. My issue is that javascript seems to be catching the end of the first iteration--and thusly adding the style--too late, as when the modal opens it's opacity is faded slightly. What's weirder, is that it's only sometimes; I open it once and it's kinda faded, I open it again and it's full opacity, then again and it's really faded... I tried adding oLay.style.opacity = 1 to the fadein function to try and override the CSS but it's still hit-or-miss. After looking at
Lag in animated image array
I feel that requestAnimationframe might be the answer, but my js newb-iness makes it so that I don't really understand what that's all about... Is that the right track or is there a different solution?


text:
Q: Javascript Image onload function in IE I am trying to place the image in the middle of the screen but in IE it's not working
here is my sample code.
function showMap(event, url, element)
{
        var map_container = $('map_container'),
        viewport = document.viewport.getDimensions(),
        offset = $(element).viewportOffset(),
        top = offset.top + getScrollTop() + $(element).getHeight() + 10,
        image_mapgross = $('image_mapgross');
        image_mapgross.onload = middleMap;
        image_mapgross.src = url;
        map_container.style.cssText = "display:block;left:10px;top:" + top + "px;";

        Event.stop(event);
        //Event.observe(map_container, 'click', stopEvent);
}

in IE the function middleMap is never called.
function middleMap() {

    var map_container = $('map_container');
    middle(map_container);
}

A: use writeAttribute() method to set attributes with prototype
 $('image_mapgross').writeAttribute('src', url);

OLD:
you need to get a DOM element first
image_mapgross = $('image_mapgross').get(); //or  $('image_mapgross')[0]

if you want to set it events and properties using dot notation
image_mapgross.onload = middleMap;
image_mapgross.src = url;

A: in IE if i set the source like this
image_mapgross.setAttribute("src", url);

then it works.


text:
Q: How to get ssh under xterm not to break alt key? I have started running in an Ubuntu 16 VM, running tigervnc 1.7.0, and run into an odd environment.  Local windows behave as expected when I use alt-, for instance in a shell to back up a word via alt-b.  But when I use xterm to ssh to another host, it treats the character differently -- for example generating "â" rather than backing up.  Sounds like it's mapping the character differently, maybe via UTF.  But I haven't run into this on other systems.  I can't really tell if it's an issue with ssh, xterm, or the VNC server.
Googled and searched on ask ubuntu, but I'm coming up short.  If it's a dup, sorry, please point me the right direction.   I had high hopes for this one, but it seems different, as it's just ssh that's getting confused: Alt key works on Ubuntu 14.04 VM, ignored on 15.10 VM

A: I shared my question on facebook and got a pointer that at first I thought would be totally irrelevant, but actually pointed me toward the solution.
I added the following to my X environment and started a new xterm, which no longer suffered from the ALT problem.

XTerm*eightBitInput: false

The solution was via the following, where someone had manually added true to their own environment: https://bbs.archlinux.org/viewtopic.php?id=163632
Looks like in my case, the new system has that as the system default, which I need to override.  Though I imagine there is a more elegant solution.


text:
Q: Problems interpreting ar file within code I've been trying to interpret an ar(the libglib-2.0.a) file using this struct here declared in ar.h. Acording to the wiki the ending characters shoud be 0x60 and 0x0A, but what I got is  0x35 and 0x34, in fact the ending characters are actually 8 bytes ahead in the stream!
Here's the code:
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <elf.h>
#include <ar.h>

int main(){
    int fd = open("libglib-2.0.a", O_RDONLY);

    char b[1000];

    read(fd, b, 1000);

    ar_hdr *arS = (ar_hdr*) b;

    int dummy = 0;
}

Am I missing something?

A: First of all, you miss the 8 bytes offset at the top.
#define ARMAG   "!<arch>\n" /* String that begins an archive file.  */
#define SARMAG  8       /* Size of that string.  */

Then, you create a buffer of a bizarre size — 1000. That value makes absolutely no sense, we have a correct buffer size for it, which is the size of header itself — we know it statically, it's 60 bytes. Not to mention that to interpret the buffer as a correct struct, memory representation should be properly aligned.
Here's a working example, for the sake of brevity, error-checking is omitted.
#include <stdio.h>
#include "unistd.h"
#include <fcntl.h>
#include <string.h>

#include "ar.h"

int main() {
    int fd = open("/usr/lib/libc.a", O_RDONLY);

    lseek(fd, SARMAG, SEEK_SET);

    ssize_t bufSize = sizeof(struct ar_hdr);
    char buf[bufSize];
    read(fd, buf, bufSize);

    struct ar_hdr header;
    memcpy(&header, buf, bufSize);

    printf("\%02hhx, \%02hhx\n", header.ar_fmag[0], header.ar_fmag[1]);

    return 0;
}

$ ./read
60, 0a


text:
Q: Is there any way to formate dates as MMDDYYYY instead of YYYYMMDD in SQL Server? I've just been setting my dates as VARCHARs instead of dates because they need to maintain a MMDDYYYY format and I was wondering it there was a better way to be doing this. The standard date seems to just do it as YYYYMMDD

A: Store dates as dates (or datetime) in the database. You should be formatting dates in the presentation layer (on-screen, reports, etc.). That is the point where you use your tools' formatting capabilities to display dates in the desired format. Remember, the dates in most DBMS are stored as long integers. You're query tools are actually formatting those values into a formatted date that is displayed.
Here is a quick query to display today as a numeric:
SELECT 'Yesterday', CAST(DATEADD(DAY, -1, @Today) AS DECIMAL(32,20))
UNION
SELECT 'Today', CAST(@Today AS DECIMAL(32,20))
UNION
SELECT 'Tomorrow', CAST(DATEADD(DAY, 1, @Today) AS DECIMAL(32,20))

Output is as follows (the fraction should represent the time element, if I'm correct):
Today       43717.61447052469200000000
Tomorrow    43718.61447052469200000000
Yesterday   43716.61447052469200000000

Here is a query-level method of converting the presentation of GETDATE() in SQL Server:
SELECT CONVERT(VARCHAR, GETDATE(), 110)

Output:
09-11-2019


text:
Q: ng-grid how to enable Edit and Delete buttons I am still new to Angular and learning about the ngGrid.
I have a basic ng-grid with some data on schedules. I have Add, Edit and Delete buttons at the bottom of the grid.
I want to disable the Edit and Delete buttons by default when the grid is loaded.
I would like to enable those buttons when any row from the ng-grid is selected.
I have been able to implement this functionality on a HTML table, but not a ng-grid.
Here is my HTML.

  Enabled
  Recurrence
  Type
  Protection
  Estimated Duration
  Priority
  Description

  ...
  ...
  ...
  ...
  ...
  ...
  ...

<button ng-click="openAddModal()">Add</button>
<button ng-click="openModal(getSelected())" ng-disabled="!singleSelection()">Edit</button>
<button ng-click="deleteSchedules()" ng-disabled="!somethingSelected()">Death to Schedules!</button>
<button ng-click="deleteAllSchedules()" ng-disabled="">Schedule Extermination!</button>

And here is my app.js
$scope.gridOptions = {
  data: 'scheduleData.scheduleList',
  columnDefs: [
               ...
  ],
  enableCellSelection: true,
  enableSorting: true,
  enableColumnResize: true,
  enableColumnReordering: true,
  showGroupPanel: true,
  showColumnMenu: true,
  showFilter: true,
  showFooter: true
};

How would I go about implementing the same in ngGrid too?

A: You will need to do a few simple things...
Add the following to your gridOptions:
selectedItems: $scope.selections,
afterSelectionChange: function() {
    if($scope.selections != null){
        $scope.disabled = true;
    } else {
        $scope.disabled = false;
    }
 }

Use ng-disabled="disabled" on your elements and make sure that you set $scope.disabled = true to begin with.
Here is a plunker for a better explanation


text:
Q: I am having trouble getting last emitted state with BlocBuilder in other widgets/classes in flutter using Bloc/cubit I have a sign in cubit, which will take two parameters, email and password. then it will ask repository to give him response of that request. Before calling the function of repository I emit loading state, and when I received data from repository another state is emitted which is SigninLoaded. My SigninCubit:
final SignInRepository signInRepository;

SigninCubit({required this.signInRepository}) : super(SigninInitial());

Future<void> signIn({String email = '', String password = ''}) async {
  print("Cubit is invoked");
  emit(SigninInLoading());
  Timer(Duration(seconds: 0), () async {
    await signInRepository
        .signIn(email: email, password: password)
        .then((signinModel) {
      // print("SignIn Model is : ${signinModel}");‹‹
      emit(SigninLoaded(signInModel: signinModel));
    });
  });
}
}

SigninState
@immutable
abstract class SigninState {}

class SigninInitial extends SigninState {}

class SigninInLoading extends SigninState {}

class SigninLoaded extends SigninState {
  SignInModel? signInModel;
  SigninLoaded({required this.signInModel});
}

This is how I invoked my signinCubit from LoginPage class.
   BlocProvider.of<SigninCubit>(context).signIn(email: email, password: password);
When signinCubit is invoked from LoginPage class, I see it's response in the same class using BlocBuilder like this;
BlocBuilder<SigninCubit, SigninState>(
        builder: (context, state) {
          if ((state is SigninInitial)) {
            print("Initial State");
          } else if (state is SigninInLoading) {
            return Center(
              child: CircularProgressIndicator(
                color: AppColors.mainColor,
              ),
            );
          } else {
            final signinData = (state as SigninLoaded).signInModel;

            data = signinData;
          }

But when I try to access response or the last emitted state which was SigninLoaded, I get initial state in other class, I tried to get response in Profile class like this;
BlocBuilder<SigninCubit, SigninState>(
                builder: (context, state) {
                  print("State : $state");
                  if (state is SigninLoaded) {
                    name = (state as SigninLoaded).signInModel?.data?.firstName;
                    print("Name $name");
                  }
                  return Text(
                    'Welcome, ${name}!',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 20,
                      fontWeight: FontWeight.w800,
                    ),
                  );
                },
              ),

And I get no response back, because it says it is in initial state.
Even though I have provided Blocs as well like so;
BlocProvider to LoginPage class;
MaterialPageRoute(
          builder: (_) => BlocProvider(
            create: (BuildContext context) =>
                SigninCubit(signInRepository: signInRepository),
            child: LoginPage(),
          ),
        );

BlocProvider to Profile class;
 MaterialPageRoute(
            builder: (_) => BlocProvider(
                  create: (context) =>
                      SigninCubit(signInRepository: signInRepository),
                  child: Profile(),
                ));

A: May be Im wrong, but in my oppinion, if you want to use the SignInModel in Profile page, you've to call signIn function Again

*

*Another Solution : define just one BlocProvider of SignInCubit as parrent of both Profile page and SignIn page, for example :
MaterialPageRoute(
builder: (_) => BlocProvider(
create: (context) =>
SigninCubit(signInRepository: signInRepository),
child: MyApp(),
));

*Save signinModel or (sign in information) in local database, and when we enter ProfilePage, get it from db