text:
Q: Closing Parenthesis Recognition and Precedence of Operators In Infix to Postfix Stack Program C++ I have an assignment in my Data Structures course where the C++ program calls a function named infixToPostfix, which reads an infix expression from standard input and writes the equivalent postfix expression to standard output.
However, I'm having difficulties with two logic errors at the moment:

*

*My closing parenthesis isn't getting recognized in my program. When I attempt to pop the ')' out of the stack, it causes a segmentation error, crashing the program.

*The precedence of operators during the conversion isn't in proper order. I'm guessing it's because my program is recognizing the operators to where each operator pops the previous one out of the stack, no matter what their precedence is.

My current code:
#include <iostream>
#include <stack>    // Library used to store a stack of characters
#include <string>

using namespace std;

bool isOperator(char ch)    // Checks if character is operator
{
    if(ch == '^' || ch == '*' || ch == '/' || ch == '+' || ch == '-')
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool isOperand(char ch)     // Checks if character is operand
{
    // If not an operator or a parenthesis, then assume operand
    if(!isOperator(ch) && ch != '(' && ch != ')')
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Retrieves weight of operators as per precedence
// Higher weight = higher precedence in operators
// Returns 0 for non-operators
int getWeight(char ch)
{
    switch(ch) {
        case '^': // exponents
            return 3;
        case '/':
        case '*':
            return 2;
        case '+':
        case '-':
            return 1;
        default :
            return 0;
    }
}

string infixToPostfix(string expression)
{
    // Declare stack
    stack<char> op_stack;
    // Initialize postfix as empty string
    string postfix = "";

    for(int i = 0; i < expression.length(); i++)
    {
        // Scanning each character from left.
        // If character is a delimiter, move on.
        if(expression[i] == ' ' || expression[i] == ',')
        {
            continue;
        }
        // If character is operator, pop two elements from stack,
        // perform operation, and push result back.
        else if(isOperator(expression[i]))
        {
            while(!op_stack.empty() && op_stack.top() != \
            getWeight(op_stack.top()) <= getWeight(expression[i]))
            {
                postfix += op_stack.top();
                op_stack.pop();
            }
            op_stack.push(expression[i]);
        }
        // Else if character is operand
        else if(isOperand(expression[i]))
        {
            postfix += expression[i];
        }
        // Parenthesis
        else if(expression[i] == '(')
        {
            // Push operator onto stack if empty
            op_stack.push(expression[i]);
        }
        else if(expression[i] == ')')
        {
            while(!op_stack.empty() && op_stack.top() != '(')
            {
                postfix += op_stack.top();
                op_stack.pop();
            }
            //op_stack.pop();
        }
    }

    while(!op_stack.empty())
    {
        postfix += op_stack.top();
        op_stack.pop();
    }

    return postfix;
}

int main() {
    string expression;
    cout << "Enter Infix Expression: \n";
    getline(cin, expression);

    // Displays inputted infix string and calculated
    // Postfix string
    cout << "Infix Expression: " << expression << '\n';
    cout << "Postfix Expression: " << infixToPostfix(expression) << '\n';

    return 0;
}

Sample output:
Enter Infix Expression:
(6+2)*5^8/4
Infix Expression: (6+2)*5^8/4
Postfix Expression: 6(2+5*8^4/

Where the correct postfix should be 62+58^*4/
Any help would be greatly appreciated.


text:
Q: Как сделать, чтобы метод вызывался у свойства экземпляра? Решаю задачу, в которой необходимо создать декоратор класса, который бы обладал методом get_change для определения было ли изменено свойство экземпляра класса или нет. Я накарябал вот такую ерунду, и в принципе оно даже можно сказать работает.
Я бы хотел узнать, можно ли как-то сделать, чтобы данный метод работал напрямую, т.е. вызывать его следующим образом: экземпляр_класса.свойство_экземпляра_класса.get_change() .Без всяких аргументов внутри метода.
def change_detection(cls):
    class NewClass:
        changes = {}

        def __init__(self, *args, **kwargs):
            pass

        def __setattr__(self, key, value):
            if not hasattr(self, key):
                super().__setattr__(key, value)
                type(self).changes[key] = 'I am newborn'
            else:
                super().__setattr__(key, value)
                type(self).changes[key] = 'I have been modified already'

        def get_change(self, key):
            return type(self).changes[key]

    return NewClass

@change_detection
class DecorateMe:

    def __init__(self):
        pass

a = DecorateMe()

a.y = 5
a.y = 6
a.x = 'some string'

print(a.get_change('y')) #I have been modified already
print(a.get_change('x')) #I am newborn

A: Не знаю, может в последних версиях Python и добавили методы расширения для стандартных классов, но насколько пишут в старых ответах на английском SO так сделать невозможно: ссылка1, ссылка2.

You can add whatever methods you like on class objects defined in
Python code (AKA monkey patching):

>>> class A(object):
>>>     pass

>>> def stuff(self):
>>>     print self

>>> A.test = stuff
>>> A().test()

This does not work on builtin types, because their dict is not
writable (it's a dictproxy). So no, there is no "real" extension
method mechanism in Python.

Проблема в том, что у вас в свойствах лежат стандартные типы Python - например, int или str и метод вы хотите вызывать от них, а это значит, что вы хотите сделать метод расширения для стандартного класса, что невозможно.
По идее, если вы сделаете класс-обёртку, и будете класть в свойства экземпляра класса не исходные данные (стандартные классы Python), а эту обёртку, то у неё можно написать такой метод. Не знаю, может правда потом возникнут проблемы при использовании таких свойств, если от них будет ожидаться поведение и свойства стандартных классов, а там придёт эта обёртка со своим поведением и свойствами. В общем, дальше надо ещё думать, я так не соображу сразу можно ли сделать эту обёртку достаточно прозрачной. Но простого метода тут вроде нет.

A: Это можно реализовать с помощью дескрипторов.
class StateMon:
    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, instance, owner):
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        cur_value = instance.__dict__.get(self.name)
        instance.__dict__[f"old_{self.name}"] = cur_value
        instance.__dict__[self.name] = value

class Foo():
    a = StateMon()

f = Foo()
f.a = 10
print("Old:", f.old_a, "Current: ", f.a)
# Old: None Current:  10
f.a = 90
print("Old:", f.old_a, "Current: ", f.a)
# Old: 10 Current:  90
print(type(f.a))
# <class 'int'>

Таким образом мы можем контролировать доступ к атрибуту так как нам вздумается.
Еще пример когда мы храним историю изменения объекта и можем по ней откатываться
import functools

class StateMon:
    def __set_name__(self, owner, name):
        self._states = []
        self.name = name

    def __get__(self, instance, owner):
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        cur_value = instance.__dict__.get(self.name)
        self._states.append(cur_value)
        instance.__dict__[f"prev_{self.name}"] = functools.partial(self.prev, instance, self.name)
        instance.__dict__[self.name] = value

    def prev(self, instance, name):
        if not self._states:
            return
        instance.__dict__[self.name] = self._states.pop()

class Foo:
    a = StateMon()

f = Foo()
f.a = 10
f.a = 90
print(f.a)
# 90
f.prev_a()
print(f.a)
# 10

redpajama_set_name: RedPajamaStackExchange


text:
Q: Checkbox doesn't work when I use several renderUi on Shiny I used a checkbox in my Shiny app that didn't work (couldn't update).
I tried to reach the root of the problem, and found that it appeared when I wrote the second "renderUi" function in my code (output$secondSelectionVarIllu, the 2nd function in the server) : when I delete it, the checkbox works.
Does anyone know why ?
What is the problem in my code ?
PS : I use renderUi because if I write the sliderInput in the ui, I don't achieve to include "input$choix_var" in the parameters. If there is another solution for that, it could also delete the problem, even if I'd like to understand this matter of checkbox !
PS2 : it isn't a problem of data, the only thing that doesn't work is the TRUE/FALSE option of the checkbox
Thank you very much !
# Define UI ----
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(

      selectInput(inputId = "choix_var",label="Variables utilisées pour la construction des axes :",
                  choices=as.list(noms_var),multiple=T),

      uiOutput("secondSelectionNbAxes"),
      uiOutput("secondSelectionVarIllu"),

      checkboxInput(inputId = "aff_histo_vp","Affichage de l'histogramme des valeurs propres",TRUE)
   ),

    mainPanel(
        conditionalPanel(condition = "input.aff_histo_vp",
             plotOutput("histo_vp")
        )
    )
  )
)

# Define server ----
server <- function(input, output) {

  output$secondSelectionNbAxes <- renderUI({
    sliderInput(inputId = "nb_axes",label="Choix du nombre de composantes principales :",
                min=2,max=length(input$choix_var),value=2,step=1)
  })

  output$secondSelectionVarIllu <- renderUI({
    conditionalPanel(condition="length(input$choix_var) < nb_var",
                     selectInput(inputId = "choix_var_illu",label="Variables illustratives :",
                                 choices=names(data_acp_cr)[which(!names(data_acp_cr) %in% names(data_acp_cr[,which(names(data_acp_cr) %in% input$choix_var)]))],multiple=T))
  })

  output$histo_vp <- renderPlot({
     acp <- dudi.pca(data_acp_cr[,which(names(data_acp_cr) %in% input$choix_var)],scannf = F,nf=input$nb_axes)
    fviz_eig(acp,main="Histogramme des valeurs propres")
  })
}


text:
Q: How to draw ASCII art on python I'm having a problem printing out a specific ASCII art that I saw and was wondering if anyone could help me. The program does not want to run, but I don't know where the error in my code is.
Input
print("(\\                   (\/)")
print("( '')     (\_/)      (.. )   //)")
print('O(")(") (\\'.'/)'  '(")(")O (" )')
print('         (")_(")           ()()o')

The expected output should be this:
(\\               (\/)
( '')    (\_/)   (.. )   //)
O(")(") (\'.'/) (")(")O (" )
        (")_(")        ()()o

Would really appreciate your help.

A: Try this:
print('''(\\                   (\/)''')
print('''( '')     (\_/)      (.. )   //)''')
print('''O(")(") (\\'.'/)'  '(")(")O (" )''')
print('''         (")_(")           ()()o''')


text:
Q: Adding headers to a library in CMake I have quite a few libraries that look like this:
libs

     \lib1-- src
          \- include

      \lib2--src
           \- include

Where lib2 requires lib1. The way I have gotten by doing this is by doing something like this:
lib2/CMakeLists.txt:
    include ../lib1/include
    target_link_libraries(lib2 lib1)

How can I include the lib1 header/include files in the lib2 library?
I am currently trying to do this, but during compilation I get errors that lib2 can't find the lib1 header files.
libs/CMakeLists.txt:

file(GLOB lib1_src
    "lib1/src/*.cc"
 )

#header files
file (GLOB lib1_h
    "lib1/include/*.h"
 )

file(GLOB lib2_src
    "lib2/src/*.cc"
 )

#header files
file (GLOB lib2_h
    "lib2/include/*.h"
 )

add_library(lib1 ${lib1_src} ${lib1_h})
add_library(lib2 ${lib2_src} ${lib2_h})
target_link_libraries(lib2 lib1)

I can get it to work by adding include_directories(lib1/include) to the libs/CMakeLists.txt but I'm getting to the point where one library requires 3 others, which each requires 3 others, etc. and it's getting pretty tedious.

A: When you have a repetitive folder structure like this it is often handy to create a macro that automates this kind of stuff.
MACRO(ADD_SUBLIB libname)
  #Compute required sources
  file(GLOB sublib_sources "${libname}/src/*.cc")

  #Create library
  ADD_LIBRARY(${libname} SHARED ${sublib_sources})

  #add this library's header folder to the global include set
  INCLUDE_DIRECTORIES("${libname}/include")

ENDMACRO(ADD_SUBLIB)

#Call macro once per library
ADD_SUBLIB(lib1)
ADD_SUBLIB(lib2)
ADD_SUBLIB(lib3)

#Sample executable, who as a side effect of the macro calls will
# be able to include.
ADD_EXECUTABLE(myprog main.cpp)

#Link any of the created libraries
TARGET_LINK_LIBRARIES(myprog lib1 lib2 lib3)


text:
Q: By Using Gmail API in android, I want gmail data by filtering between two dates of particular email address I am using Gmail API and I want data between two dates.
Here is my code for query which currently I am using.
listMessagesMatchingQuery(mService, user, "abc@gmail.com");

Tell me how to pass two dates and email address to get the proper response
And I am getting response like
  {
  "id" : "1622745d8ee96a59",
  "threadId" : "1622745d8ee96a59"
  }

but without date.

A: You can give seconds since the epoch to after and before in your query to get messages between two dates.
If you would like messages from abc@gmail.com sent between Wed, 04 Apr 2018 00:00:00 GMT and Thu, 05 Apr 2018 00:00:00 GMT you would write:
listMessagesMatchingQuery(mService, user, "from:abc@gmail.com after:1522800000 before:1522886400");


text:
Q: Not able to work with properties in matlab class The following MATLAB code does not work.  I guess it has something to do that in the function changer, MATLAB tries to equal the objects A and B and not just setting the values to the same. Any workaround for that?
classdef foo
    %FOO Summary of this class goes here
    %   Detailed explanation goes here

    properties
        A=5
        B=0
    end

    methods
        function changer(obj)
            obj.B=obj.A
        end
    end

end

A: I think the code is actually working fine, just not doing quite what you expect.
The way you've defined it, foo is a value class, so it has value semantics, rather than reference (or handle) semantics. When you execute changer(myobj), MATLAB is creating a copy of myobj with the new value of B and returning it to you. The original myobj remains unchanged. When implementing a value class, you would typically add an output argument to changer in order to be able to further work with this new copy.
function obj = changer(obj)

If you set foo to be a handle class, by inheriting from handle:
classdef foo<handle

it will then have reference (or handle) semantics, where the original myobj is modified (you then no longer need the output argument from changer):
>> myobj = foo;
>> changer(myobj); % or alternatively myobj.changer
>> myobj.B
ans =
     5


text:
Q: How to set up forward search: from .tex under Emacs to position .pdf under Okular I edit .tex file under Emacs and view them with Okular.
I have already set up the backward search: from .pdf to .tex by pressing Shift+Left click on the .pdf file. The related part of .emacs file is here:
(server-start)
(add-hook 'LaTeX-mode-hook 'TeX-PDF-mode)

(defun pdf-with-okular ()
 (add-to-list 'TeX-output-view-style
 (quote ("^pdf$" "." "okular %o %(outpage)"))))

(add-hook 'LaTeX-mode-hook 'pdf-with-okular t)
(setq TeX-view-program-list '(("Okular" "okular %o")))
(setq TeX-view-program-selection '((output-pdf "Okular") (output-dvi "Okular")))

(custom-set-variables
 '(LaTeX-command "latex -synctex=1")
 '(cua-mode t nil (cua-base))
 '(show-paren-mode t))

However, I do not see how to make "forward" search work. Someone says when we position somewhere in the .tex file, press C-c C-v, we could go to the corresponding location of .pdf file. But here, when I press C-c C-v it opens another okular and we are always on the first page of the .pdf file.
P.S. My whole .emacs.

A: Try this instead:
okular --unique %o#src:%n%b

This is what I use and works fine. Should definitely not open another window with the --unique command so something else is up if that occurs. A similar solution is in link below but through the menus not in the .emacs file. Should just be able to use the command above with what you already have and should bring you to the line(%n) in the file when you run view or C-c C-v:
http://mathieu.3maisons.org/wordpress/how-to-configure-emacs-and-auctex-to-work-with-a-pdf-viewer

A: Unfortunately things became more complicated with TeX Live 2011. A temporary solution to make forward search work with Okular is described here:
https://bugs.kde.org/show_bug.cgi?id=274294#c20
Works for me, hope it will do for you, too.

A: Instead of
(quote ("^pdf$" "." "okular %o %(outpage)"))))

I have
(quote ("^pdf$" "." "okular --unique -p %(outpage) %o"))))


text:
Q: Python--always get "must be str not int" I want to read in words in a loop until the user types stop or <space>. When the loop is stopped I want to concatenate and print all the words previously typed by the user (not including stop or space).
while True:
    reply = input('Enter text, [type "stop" to quit]: ')
    print (reply)
    if reply == 'stop':
        break
    while len(reply) >3:
        reply=reply+1
        print (reply)

For example:

reply1 is "how"
reply2 is "long"
reply 3 is "has"
reply 4 is"it"
reply5 is "been"
expect output: "how long has it been"

A: It is hard to tell what you want, but based on your edits it looks like you are trying to do something like this:
replys = []
while True:
    reply = input('Enter text, [type "stop" to quit]: ')
    print(reply)
    if reply == 'stop' or reply == ' ':
        print(" ".join(replys))
        break
    replys.append(reply)

A: The question is not clear, but I think what you're saying is that you want to iterate over a number and modify it as the loop, loops. If that is true, the below may help...
while True:
    reply = input('Enter text, [type "stop" to quit]: ')

    print (reply)

    if reply == 'stop':
        break

    replyInt = int(reply)

    while replyInt < 100:
        replyInt = replyInt+1
        print (str(replyInt))

EDIT:
OK, based on your new comments, this may work for you:
totalReplies = ""

while True:

    reply = raw_input('Enter text, [type "stop" to quit]: ')

    if reply == "stop":
        print(totalReplies)
        break

    totalReplies = totalReplies + " " + reply

OUTPUT:
Enter text, [type "stop" to quit]: how
Enter text, [type "stop" to quit]: long
Enter text, [type "stop" to quit]: has
Enter text, [type "stop" to quit]: it
Enter text, [type "stop" to quit]: been
Enter text, [type "stop" to quit]: stop
 how long has it been


text:
Q: How to cast : 'System.IO.Enumeration.FileSystemEnumerable`1[System.String]' to type 'System.Collections.Generic.IEnumerable`1[System.String[]]' I'm struggling with connecting these two codes:
//Program.cs
using System;

namespace Find_Duplicate_Files
{
    public class Finder
    {
        public static void Main(String[] args)
        {
            var CWD = System.IO.Directory.GetCurrentDirectory();
            Console.WriteLine(CWD);
            //HashFile.Hash("Find_Duplicate_Files.exe");
            var files = Walk.From("here");

            foreach (var filelist in files)
            {
                foreach (var _files in filelist)
                {
                    foreach (var file in _files)
                        Console.WriteLine(file);
                }
            }
        }
    }
}

//Walk.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Find_Duplicate_Files
{
    internal class Walk
    {
        public static IEnumerable<IEnumerable<String[]>> From(String dir)
        {
            if (dir == null) throw new ArgumentNullException(dir);
            if (dir.ToLower() == "here")
            {
                dir = System.IO.Directory.GetCurrentDirectory();
            }
            if (Directory.Exists(dir))
            {
                var files = Directory.EnumerateFiles(dir);
                var dirs = Directory.EnumerateDirectories(dir);

                foreach (var d in dirs) From(d);
                yield return (IEnumerable<String[]>)files;
            }
            else
            {
                throw new DirectoryNotFoundException(dir);
            }
        }
    }
}

I don't know how to access the files, it says
Unable to cast object of type 'System.IO.Enumeration.FileSystemEnumerable`1[System.String]' to type 'System.Collections.Generic.IEnumerable`1[System.String[]]'.

Sadly, I don't understand anything from it.
I'm Using VS 2022, but it doesn't highlight anything else to change.


text:
Q: The method read(String, String) is undefined for the type JsonPath am using the below code get the value from json file using jsonexpression, iam unable to use Jsonpath.read method getting pop saying that The method read(String, String) is undefined for the type JsonPath
    try {
        BufferedReader bufferreader = new BufferedReader(
                new FileReader("C:\\Users\\****\\eclipse-workspace\\json_files\\jsonfile\\db-AAPL.json"));
        String line = null;
        StringBuilder builder = new StringBuilder();
        while ((line = bufferreader.readLine()) != null) {
            builder.append(line);
        }
        String jsoncontent = builder.toString();
        JSONArray  array=JsonPath.read(jsoncontent,"$.response.data.arrayRowData[1].header.headerId");
        System.out.println(array.get(0));
    } catch (Exception e) {
        e.printStackTrace();
    }

A: After changing the json path verion to 2.7.0 able to access the Jsonpath.read method


text:
Q: Third point of a triangle in the complex plane I have an equilateral triangle with two points equal to $(2+2i)$ and $(5+i)$. I want to find the third point(s) (there are $2$ of these). I have that the side length of the triangle is $\sqrt{10}$.

A: A different Hint:  if $A,B\in\mathbb{C}$ and $\omega=e^{\frac{\pi i}{3}}=\frac{1+\sqrt{-3}}{2}$, the points you are looking for are given by:
$$ A+(B-A)\omega, \qquad A+(B-A)\omega^{-1}.$$
This happens because the multiplication by $\omega$ ($\omega^{-1}$) acts like a $60^\circ$ ($-60^\circ$) rotation.

A: Hint: You already  know that $\big|z-(5+i)\big|=\big|z-(2+2i)\big|=\ldots$ (you are to fulfil the gap), where $z=x+yi$ the complex number(s) you are looking for. Plus, you have an equilateral triangle, which means all sides are equal!

A: Yet another hint: Why not work in $\Bbb R^2$ with vectors? You have the points $A = (2,2)$ and $B = (5,1)$, and the length $\ell = \sqrt{10}$. Find the perpendicular bisector of $\overline{AB}$ and go $h = \frac{\ell\sqrt{3}}{2} = \frac{\sqrt{30}}{2}$ in both senses.

A: (I'm purposely not trying
to be clever here
and doing all calculations in my head.)
The distance
$d$
between the two known points
satisfies
$d^2
=(2-5)^2+(2-1)^2
=10
$.
If the point is
$(x, y)$,
then
$(x-2)^2+(y-2)^2
=(x-5)^2+(y-1)^2
=10
$,
or
$x^2-4x+4+y^2-4y+4
=x^2-10x+25+y^2-2y+1
=10
$,
or
$x^2-4x+y^2-4y+8
=x^2-10x+y^2-2y+26
=10
$.
Subtracting the first two,
$6x-2y-18 = 0$,
or
$y = 3x-9$.
Substituting this
in the first equation,
$10
=x^2-4x+(3x-9)^2-4(3x-9)+8
=x^2-4x+9x^2-54x+81-12x+36+8
=10x^2-70x+125
$
or
$10x^2-70x+115=0$
or
$2x^2-14x+23=0$
Using the good old
quadratic equation formuls,
$D^2
= b^2-4ac
= 14^2-4\cdot 2 \cdot 23
=196-184
=12
$
so
$D = 2\sqrt{3}$.
The roots are therefore
$x
=\dfrac{-b \pm D}{2 a }
=\dfrac{14\pm 2\sqrt{3}}{2\cdot 2}
=\dfrac{7\pm \sqrt{3}}{2}
$
and
$y
=3x-9
=\dfrac{21\pm 3\sqrt{3}-18}{2}
=\dfrac{3\pm 3\sqrt{3}}{2}
$.
Note:
I find it somewhat
embarrassing and dishearting
how many errors
I made
while doing this
all in my head.


text:
Q: Extract characters after a symbol in sql server 2012 I have a table List shown below:
+------+-------------------------------------+
| Code |                name                 |
+------+-------------------------------------+
| A001 | ABBOTT_1000000                      |
| A002 | AGCO_1000001                        |
| A003 | ALFA LAVAL_1000002                  |
| A004 | ALSTOM POWER INDIA LIMITED_1000003  |
| A005 | AMERICAN BUREAU OF SHIPPING_1000004 |
+------+-------------------------------------+

I need to update the table extracting the characters present after _ in name and replace them in code column. like this.
+---------+-------------------------------------+
|  Code   |                name                 |
+---------+-------------------------------------+
| 1000000 | ABBOTT_1000000                      |
| 1000001 | AGCO_1000001                        |
| 1000002 | ALFA LAVAL_1000002                  |
| 1000003 | ALSTOM POWER INDIA LIMITED_1000003  |
| 1000004 | AMERICAN BUREAU OF SHIPPING_1000004 |
+---------+-------------------------------------+

This is has to be done in sql server 2012. please help me.

A: Try this
with cte as
(
select substring(name,charindex('_',name)+1,len(name)) as ext_str,*
from yourtable
)
update cte set code = ext_str

A: You can try to use SUBSTRING in following:
SAMPLE DATA
CREATE TABLE #MyTable
(
Code NVARCHAR(60),
Name NVARCHAR(60)
)
INSERT INTO #MyTable VALUES
('A001','ABBOTT_1000000'                      ),
('A002','AGCO_1000001'                        ),
('A003','ALFA LAVAL_1000002'                  ),
('A004','ALSTOM POWER INDIA LIMITED_1000003'  ),
('A005','AMERICAN BUREAU OF SHIPPING_1000004' )

QUERY
UPDATE #MyTable
SET Code = SUBSTRING(Name, CHARINDEX('_', Name) + 1, LEN(Name))

TESTING
SELECT * FROM #MyTable
DROP TABLE #MyTable

OUTPUT
Code    Name
1000000 ABBOTT_1000000
1000001 AGCO_1000001
1000002 ALFA LAVAL_1000002
1000003 ALSTOM POWER INDIA LIMITED_1000003
1000004 AMERICAN BUREAU OF SHIPPING_1000004

SQL FIDDLE
DEMO

A: You can use RIGHT together with CHARINDEX:
SQL Fiddle
UPDATE tbl
    SET Code = RIGHT(Name, LEN(Name) - CHARINDEX('_', Name))
WHERE CHARINDEX('_', Name) > 0

A: UPDATE <table>
SET name = STUFF(name, 1, CHARINDEX('_', name), '')
WHERE name like '%[_]%'

A: You can do this:
First, you select the number that you want to place as code
select substr(name,-1,7) from table_name

After this, you can update the table.So,The complete statement will be :
update table_name t set t.code = (select substr(name,-1,7) from table_name where code = t.code);


text:
Q: Why my code error? find call value in R code this is my code
whats miss? Im confused why my code error
please help me
this code like black-scholes but in geske formula
Values Call = VT1*N(d1)-K2*exp(-r*(T2-T1))*N(d2)
N=distribution normal
d1=(log(VT1/K2)+((r+(1/2) x sigmaˆ2/2) x (T2-T1))/(sigma x sqrt(T2-T1)))
d2=d1-(sigma*sqrt(T2-T1))
thats the formula
> Call_On_Call<-function(VT1,K1,K2,r,sigma,T2,T1)
+ {
+
+ #VT1    ...   initial stock price
+ #T1    ... maturity of the compound option
+ #K1    ... strike of the compound option
+ #T2     ... maturity of the underlying option
+ #K2     ... strike of the underlying option
+ #r     ... interest rate
+ #sigma ... volatiliy

+ #Valuescall

+ d1<−(log(VT1/K2)+((r+(1/2)*sigmaˆ2/2)∗(T2-T1))/(sigma*sqrt(T2-T1));
Error: unexpected input in:
"
d1<-(log(VT1/K2)+((r+(1/2)*sigmaˆ"
> d2<-d1-(sigma*sqrt(T2-T1));
Error: object 'd1' not found
>
> valuescall<-VT1*pnorm(d1)-K2*exp(-r*(T2-T1))*pnorm(d2);
Error: object 'VT1' not found
>
> }
Error: unexpected '}' in "}"
>

A: You have 2 problems that I can see in your definition of d1:

*

*strange character ˆ instead of ^

*missing ) at the end

So your d1 should be defined like this:
d1<−(log(VT1/K2)+((r+(1/2)*sigma^2/2)∗(T2-T1))/(sigma*sqrt(T2-T1)));


text:
Q: Implementing a math formula in Scheme (DrRacket) Let me start off by saying that I am a complete novice when it comes to Scheme/Racket. I am trying to implement the following formula:
        αi = (3/h)((ai+1 – ai) – (ai – ai-1))
Here is how I've defined my function:
(define alpha_values (lambda (y_values h n) (...))

What I would like it to do is to run the function with a list of y_values along with some constant h and a number n, then compute and return a list of α values. n will go from 1 to n-1, so the first and last element of the list are not going to be iterated upon.
For example, if the list of y_values is '(2 4 6 8) and h is 1 and n is 3 then there should be two α values returned: one for i=1 (y=4), and one for i=2 (y=6), like so: 3*((6-4)-(4-2)) = 0 and 3*((8-6)-(6-4)) = 0 returns '(0 0) for α.
Truthfully, I'm lost as to how to even begin to implement this. I thought about using map but I don't know if it's possible to skip the first and last element while doing so. I've tried doing so recursively using car and cdr but I ran into the issue of "losing" an element in the list needed for the calculation when recursively calling the function again without the first element. I would appreciate some insight as to how to approach the implementation of this formula – not an answer, just an idea as to how to get the ball rolling.

A: Whenever you are unsure about how to approach a particular problem, consider breaking it down to smaller tasks that are easier to manage, think about, and implement.
For example, going backwards from the end result, you want to produce a list of alphas, whereby each alpha is created from h and an interval {a_i-1, a_i, a_i+1}  using the noted formula.
So one small function you can create would be the function, lets call it compute-alpha, that takes an interval and h as arguments, then produces an alpha using the formula. Ie:
(define (compute-alpha interval h)
  ...)

The body of this function will simply be the formula, and it will behave as follows:
> (compute-alpha '(2 4 6) 1)
0
> (compute-alpha '(4 6 8) 1)
0

But then you realize that you don't have the intervals (eg. '(2 4 6), '(4 6 8) etc) in order to use compute-alpha. So next step is to define another small function, lets call it build-intervals, that takes y-values and n as arguments, and produces a list of intervals. Ie:
(define (build-intervals y-values n)
  ...)

and behaves as follows:
> (build-intervals '(2 4 6 8) 3)
'((2 4 6) (4 6 8))
> (build-intervals '(1 2 3 4 5 6 7) 4)
'((1 2 3) (2 3 4) (3 4 5))

Now, all that is left is applying compute-alpha on every interval produced by build-intervals. And this is where map shines:
(define (alpha-values y-values h n)
  (map (lambda (interval)
         (compute-alpha interval h))
       (build-intervals y-values n)))

Then you can have:
> (alpha-values '(2 4 6 8) 1 3)
'(0 0)

Once you implement build-intervals and compute-alpha, you might notice ways of combining them to reduce alpha-values to a single function that iterates y-values only once before producing the list of alphas.


text:
Q: Run-time error -2147417848 (80010108) after some time of inactivity I have not the closest idea what could cause the problem, but I encounter the following symptoms:
Sometimes after some time of not using an excel workbook connected to a running xlwings server instance, suddenly all calls to the python side fail with a runtime error.
"Sometimes" and "some time" are pretty random. It might happen after 10 minutes or it might not happen at all. I could not find a pattern yet.
It seems as if it does not happen on all computers as well.

Run-time error -2147417848 (80010108) Automation error: The object invoked has disconnected from its clients"

or in german

Laufzeitfehler -2147417848 (80010108) Automatisierungsfehler: das aufgerufene Objekt wurde von den Clients getrennt

The only way to get things working again is by closing the server instance. It is restarted without problems.
The problem has been seen with Python 3.5.3/xlwings 0.10.4 in combination with  Windows 7+Office 2010 and Windows 10+Office 2016.
Has anyone encountered this problem? Or any idea how to avoid/debug the issue?


text:
Q: What happens when GIT runs out of hash values for your Revisions? What happens when GIT runs out of hash values for your Revisions?
Not that it would happen anytime soon, but theoretically it is possible.

A: According to the Git's Documentation
"If you do happen to commit an object that hashes to the same SHA-1 value as a previous object in your repository, Git will see the previous object already in your Git database and assume it was already written. If you try to check out that object again at some point, you'll always get the data of the first object."

A: I think this will help you understand better Probability of SHA1 collisions
I think you'd run out of space in the real world ;-)


text:
Q: How to keep bootstrap carousel paused until it enters in the viewport? EDIT: reason for this request. This edit has been added when the solution has been found for the sake of describing my needs. I had a Carousel that showed a logical sequence step 1, step 2, step 3.. That carousel is not a top of page, so I want it to stay stopped / paused until the user sees it and when it will see it, as first, I want the user to see the first slide, step 1. Nevertheless, some users (and they are not few, believe me) don't know about carousels and sliders, so I don't wanna miss their view on the subsequent slides. This is the reason for what follow.
I'm wondering about this
I have a bootstrap 3.1 carousel that is not at top of the home page.
Instead you "reach it" when scrolling down some "bootstrap' rows".
Well I'd like it to keep the carousel stopped / paused until the user will scroll the page down to where the carousel is placed (let's say the carousel height is 500 pixel, when at least the first top 150 pixels are entered in the viewable area)
when those 150 pixel have been scrolled in, the pause / stop should turn to "play" and so, if the pause between each slide is 5000 msec, after 5000 msec the next slide should turn.
According with this solution it is matter of javascript but it is not what I'm seeking for also excuse me but currently I'm not so strong with javascript and jquery, so thank you for any hint with some explanation.
EDIT 01
This script looks to be the correct and also a great solution :-), especially reading the comments at bottom of that page, but as stated above, I miss the knowledge to properly take advantage of it, thank you for any hint.

A: Here's a method using Intersection Observer API; it will fail silently for IE and other unsupported browsers.
setTimeout(function() {
  if (IntersectionObserver === undefined) return;
    const carousels = $(".carousel");
    if (carousels.length === 0) return;
    const RATIO = 0;
    // You can set a intersection percentage, such as 0.25 for 25% visible, but
    // if you want pixels, I'm using `rootMargin` in the options below
    var observer = new IntersectionObserver(function (entries, observer) {
        entries.forEach(function(entry) {
            jQuery(entry.target).carousel(entry.intersectionRatio < RATIO ? 'pause' : 'cycle');
        });
    }, {
            root: null,
            rootMargin: '-150px 0px', // 150px visible on top or bottom of viewport
            threshold: RATIO
        });
    carousels.each(function () {
        observer.observe(this);
    });
  }
});

A: I went for the long path, self answered myself.
I've tried several plugins, but they were not effective or either they were breaking the Carousel engine.
Researching so much, finally I've landed on this jQuery plugin
http://www.jqueryscript.net/other/jQuery-Plugin-To-Determine-If-An-Element-Is-In-the-Viewport-Viewport-Checker.html
It works pretty fine, straight and as expected and there is a bonus included: the offset I was seeking for!!! (yeeeh!)
Pretty easy to implement
<script src="viewportchecker.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    $('.carousel').carousel('pause'); /** load page with carousel paused

    $('.carousel').viewportChecker({
        offset: 200,                  /** wait for the first 200 pixel of the element
                                          to enter in the viewport
        callbackFunction: function(elem){
            setTimeout(function(){
                $('.carousel').carousel(''); /** remove pause
            },500);
        }
    });

});
</script>

"thank you" to myself :-)

A: I suppose this would also help the problem when the viewport cuts the carousel in half.   ie: With a carousel at the top of the page and you scroll down, forcing the top of browser window to show only the bottom half of carousel.
Currently, when the carousel cycles, the carousel images load to the top of the viewport, not the top of the carousel container.
When you scroll back up, the carousel only displays half the image and the top half is grey.  This is very annoying.  Will try this to see if it fixes.


text:
Q: Partial converse to Novikov's conjecture In Jim Davis's paper "Manifold aspects of the Novikov conjecture" (Surveys on surgery theory, vol 1, pages 195-224) he writes down (Theorem 6.5) a sort-of converse to the Novikov conjecture. He writes:
Theorem: Let $M$ be a closed, oriented, smooth manifold of dimension $\ge5$, together with a map $f\colon M\to B\pi$ to the classifying space of a discrete group, inducing an isomorphism on fundamental groups. Given any cohomology class
$${\mathcal L}={\mathcal L}_1+{\mathcal L}_2+\cdots$$ in $H^{4\ast}(M; {\mathbb Q})$ with the ${\mathcal L}_i\in H^{4i}(M; {\mathbb Q})$, if $f_\ast({\mathcal L}\cap [M])=0$ in $H_{n-4\ast}(B\pi;{\mathbb Q})$, then there is a nonzero integer $R$ so that, for any multiple $r$ of $R$, there is a homotopy equivalence $h\colon M\to N$ of closed smooth manifolds so that
$$h^\ast({\mathcal L}_N)-{\mathcal L}_M=r{\mathcal L},$$
where ${\mathcal L}_M$ and ${\mathcal L}_N$ are the total Hirzebruch $L$-classes of $M$ and $N$.
There are many versions of the Novikov conjecture. One version states that, if $h\colon N\to M$ is an orientation-preserving homotopy equivalence between closed orientable manifolds, then for any discrete group $\pi$ and any map $f\colon M\to B\pi$, we have
$$f_\ast\circ h_\ast({\mathcal L}_N \cap [N])=f_\ast({\mathcal L}_M\cap [M])$$ in $H_\ast(B\pi; {\mathbb Q})$.
Another version is the following:  Suppose that $M$ is a closed oriented manifold of dimension $4k+i$ with
fundamental group $\pi$.
Let $f\colon M\to BG$ be a map and suppose that $\alpha\in H^i(B\pi; {\mathbb Q})$.
Then the higher signature given by
\begin{equation*}
\mathrm{sig}_\alpha(M)\equiv \langle f^\ast(\alpha)\cup {\mathcal L}_M, [M]\rangle
\end{equation*}
is an oriented rational homotopy invariant.
Note: The map $f\colon M\to B\pi$ induces an isomorphism on the fundamental group in the theorem, but the Novikov conjecture does not require an isomorphism.
My question is: how does the theorem in his paper serve as a (partial) converse to Novikov? Maybe it's just a matter of playing with cup and cap products and sliding symbols around but I couldn't get things to match up. Thanks for reading. [Apologies for any typos.]


text:
Q: I can't get the linear regression with Python of a scatter plot to have the expected values obtained with Origin I am writing a code that allows me to obtain the linear regression of some measures. I have used different codes but with all of them I get strange result. Instead of being a line with a constant slope, the line I get is first horizontal and between the penultimate point and the last point the slope decreases.
The code I am using is:
import matplotlib.pyplot as plt
import numpy as np

x0=[0.00000001,0.000001,0.0001,0.01]
y0=[0.9974209723854539,0.9945196648709005,0.9914759279447916,0.9852556749265332]

x=np.array(x0)
y=np.array(y0)

m,b=np.polyfit(x,y,1)
print(m,b)

plt.scatter(x,y)
plt.plot(x,m*x+b,color='green')

plt.xscale('log')
d=['linear fit   '+str(round(m,4))+'*x+'+str(round(b,4)),'real measure']

plt.legend(d,loc="upper right",borderaxespad=0.1,title="")

And I get the following graph:
Phyton plot
Which is very different from what I should get, which I have been able to draw in Origin:
Origin plot
I have tried various linear fit methods but with all of them I get this form which is wrong.
Hopefully you can help me find the error.
Thank you very much.


text:
Q: Error in datagridview using ms acess(c#) the below mentioned code raises error "SYNTAX ERROR IN INSERT INTO STATEMENT"
here i took name and number field has text
no as autonumber(primary key)
con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/ppd/db1.mdb;Jet OLEDB:Database Password=techsoft");

    da = new OleDbDataAdapter("select * from contacts", con);

    DataSet ds = new DataSet();

    da.Fill(ds, "contacts");

    dt = ds.Tables[0];

    dataGridView1.DataSource = dt;
    OleDbConnection con;

     OleDbDataAdapter da;

     DataTable dt;

     OleDbCommand cm;

    string insertQuery = @"insert into  contacts(names,number,no) Values (@names,@number,@no)";

    cm = new OleDbCommand(insertQuery, con);

    cm.Parameters.Add("@names", OleDbType.VarChar, 10, "names");

    cm.Parameters.Add("@number", OleDbType.VarChar, 10, "number");

     cm.Parameters.Add("@no", OleDbType.VarChar, 10, "no");

    da.InsertCommand = cm;

    private void button26_Click(object sender, EventArgs e)
            {
                da.Update(dt);
            }

A: You can't put text in a number-type field.  If "no" is autonumber, don't give it a value at all and it will auto-increment.  Just change the line that say:
string insertQuery = @"insert into  contacts(names,number,no) Values (@names,@number,@no)";

to
string insertQuery = @"insert into  contacts(names,number) Values (@names,@number)";

and remove the line that says
cm.Parameters.Add("@no", OleDbType.VarChar, 10, "no");

A: no is Autonumber, you can not give autonumber as parameter in your insert query.
Use below code :
con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/ppd/db1.mdb;Jet OLEDB:Database Password=techsoft");

    da = new OleDbDataAdapter("select * from contacts", con);

    DataSet ds = new DataSet();

    da.Fill(ds, "contacts");

    dt = ds.Tables[0];

    dataGridView1.DataSource = dt;
    OleDbConnection con;

     OleDbDataAdapter da;

     DataTable dt;

     OleDbCommand cm;

    string insertQuery = @"insert into  contacts([names],[number]) Values (@names,@number)";

    cm = new OleDbCommand(insertQuery, con);

    cm.Parameters.Add("@names", OleDbType.VarChar, 10, "names");

    cm.Parameters.Add("@number", OleDbType.VarChar, 10, "number");

    da.InsertCommand = cm;

Note : I have just removed no from
  parameter list.


text:
Q: How to set the value of CPATH in the below script. The script does not recognise the classpath in the 2nd line of the below script. I have to execute the below script
export CPATH="cpath=.:/mdcode/mtrxmdsb2/WaferChecks/bin/WaferChecksFile.jar"
/sail/lpp/IBM/Java/1.6.0/jre/bin/java \
    -classpath "$CPATH" com/ibm/md/waferchecks/ReadPasswordMain $1 $2 $3

The script accepts 3 arguments. But when im running the script from the cmd prompt, I am getting the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: com.ibm.md.wafercheck
s.ReadPasswordMain
Caused by: java.lang.ClassNotFoundException: com.ibm.md.waferchecks.ReadPassword
Main
        at java.net.URLClassLoader.findClass(URLClassLoader.java:421)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:652)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:346)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:618)
Could not find the main class: com/ibm/md/waferchecks/ReadPasswordMain.  Program
 will exit.

I understand that this is a problem with classpath variable not being properly set. I gues im wrong with the syntax somewhere. Can anyone please help with it. Thanks

A: export CPATH=".:/mdcode/mtrxmdsb2/WaferChecks/bin/WaferChecksFile.jar"

Also you don't have to put shell variable in quotation marks.

A: Remove the export CPATH= from the assignment line.  This forced java to look for a file or directory with the name cpath=. instead of ..
#! /bin/bash
jarfile=/mdcode/mtrxmdsb2/WaferChecks/bin/WaferChecksFile.jar
cpath=.:${jarfile?}

You don't need the export, as you're passing $cpath as an argument to the java -classpath option.

En passant, you can perform some checks prior to invoking java to eliminate
some trivial errors with the following line:
(< ${jarfile?}) || exit # abort on missing or unreadable file[*]

*

*${path:?} aborts if the path variable is empty or undefined

*( < file ) || exit is a minimal test on the ability to open a file for reading.
(This is common idiom for bash, ksh93 and zsh.)

The final script then becomes:
#! /bin/bash
jarfile=/mdcode/mtrxmdsb2/WaferChecks/bin/WaferChecksFile.jar
cpath=.:${jarfile?}
(< ${jarfile?}) || exit

/sail/lpp/IBM/Java/1.6.0/jre/bin/java \
    -classpath "${cpath?}"  \
    com/ibm/md/waferchecks/ReadPasswordMain $1 $2 $3


text:
Q: Django - overriding save/delete functions of the model vs doing it in the view I have a model Quote, which has a foreign key to the user model. A user can have between 0 and 10 quotes, and if there s/he has one or more quotes, one of them should be the primary quote(primary is a field of the Quote model).
When a quote is added by the user, it is checked whether the user has other quotes, if not the new quote is set as the primary. And when the primary quote is deleted another quote is set as the primary quote, if the user has any other quotes.
Right now I do this in the respective views. I was wondering whether it would better to override the save and delete functions of the model and do all of this there.
So which is the right place to perform these tasks the model or the view?

A: The general consensus is, thick models and helpers, thin views. In other words, your views should be as simple as possible; your models as rich as possible, and plenty of helper code for the outlying bits.
Also keep in mind that if you override the model methods, you are offering a sort of "guarantee" that no matter how the ORM is accessed, your rules will be applied. If you do the logic only in the view, then anywhere else; for example using custom management commands or the django shell, a template tag, or even in another view, there is a chance that your rules will not be applied.


text: Q: What is the definition for an interval in a finite field $\mathbb{F}_p$? I read in some number theory papers about interval in finite field. For example one such interval is $\{1,2,...,N\}$ of $N$ consecutive residues modulo $p$. Does there exists other kind of interval also? I am curious to know about the proper definition of an interval in a finite field.


text:
Q: Search API with Field Collections Problem: I want to index my field collection items, so that they are searchable by the user.
My Content Types are based of several Field-Collections, which are containing many text fields that should be searchable.
The fields belonging to the Field Collection (e.q. subtitle, text, etc.) are missing and NOT indexed. What can I do to add them to the search index?

A: Add a the field "collection" in the schema.xml as below.
<field name="collection" type="text_general" indexed="true" stored="false" multiValued="true"/>

Its not stored as the other fields that come under collection field (Eg. text, subtitle ) will be copied to this field.
Therefore define the field text, subtitle and then copy them using copyField to the collection field as below.
<field name="text" type="text_general" indexed="true" stored="true" />
<field name="subtitle" type="text_general" indexed="true" stored="true" />

Now copy the above two fields to the collection field as below.
<copyField source="text" dest="collection"/>
<copyField source="subtitle" dest="collection"/>


text:
Q: How to load a model using Tensorflow Hub and make a prediction? This should be a simple task: Download a model saved in tensorflow_hub format, load using tensorflow_hub, and use..
This is the model I am trying to use (simCLR stored in Google Cloud): https://console.cloud.google.com/storage/browser/simclr-checkpoints/simclrv2/pretrained/r50_1x_sk0;tab=objects?pageState=(%22StorageObjectListTable%22:(%22f%22:%22%255B%255D%22))&prefix=&forceOnObjectsSortingFiltering=false
I downloaded the /hub folder as they say, using
gsutil -m cp -r \
"gs://simclr-checkpoints/simclrv2/pretrained/r50_1x_sk0/hub" \

.
The /hub folder contains the files:
/saved_model.pb
/tfhub_module.pb
/variables/variables.index
/variables/variables.data-00000-of-00001

So far so good.
Now in python3, tensorflow2, tensorflow_hub 0.12 I run the following code:
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub

path_to_hub = '/home/my_name/my_path/simclr/hub'

# Attempt 1
m = tf.keras.models.Sequential([hub.KerasLayer(path_to_hub, input_shape=(224,224,3))])

# Attempt 2

m = tf.keras.models.Sequential(hub.KerasLayer(hubmod))
m.build(input_shape=[None,224,224,3])

# Attempt 3

m = hub.KerasLayer(hub.load(hubmod))

# Toy Data Test

X = np.random.random((1,244,244,3)).astype(np.float32)

y = m.predict(X)

None of these 3 options to load the hub model work, with the following errors:
Attempt 1 :

ValueError: Error when checking input: expected keras_layer_2_input to have shape (224, 224, 3) but got array with shape (244, 244, 3)

Attempt 2:

tensorflow.python.framework.errors_impl.UnknownError:  Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.
     [[{{node sequential_3/keras_layer_3/StatefulPartitionedCall/base_model/conv2d/Conv2D}}]] [Op:__inference_keras_scratch_graph_46402]

Function call stack:
keras_scratch_graph

Attempt 3:

ValueError: Expected a string, got <tensorflow.python.training.tracking.tracking.AutoTrackable object at 0x7fa71c7a2dd0>

These 3 attempts are all code taken from tensorflow_hub tutorials and are repeated in other answers in stackoverflow, but none works, and I don't know how to continue from those error messages.
Appreciate any help, thanks.
Update 1:
Same issues happen if I try with this ResNet50 hub/
https://storage.cloud.google.com/simclr-gcs/checkpoints/ResNet50_1x.zip

A: As @Frightera pointed out, there was an error with the input shapes. Also the error on "Attempt 2" was solved by allowing for memory growth on the selected GPU. "Attempt 3" still does not work, but at least there are two methods for loading and using a model saved in /hub format:
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub

gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)

hubmod = 'https://tfhub.dev/google/imagenet/mobilenet_v2_035_96/feature_vector/5'

# Alternative 1 - Works!

m = tf.keras.models.Sequential([hub.KerasLayer(hubmod, input_shape=(96,96,3))])
print(m.summary())

# Alternative 2 - Works!

m = tf.keras.models.Sequential(hub.KerasLayer(hubmod))
m.build(input_shape=[None, 96,96,3])
print(m.summary())

# Alternative 3 - Doesnt work

#m = hub.KerasLayer(hub.load(hubmod))
#m.build(input_shape=[None, 96,96,3])
#print(m.summary())

# Test

X = np.random.random((1,96,96,3)).astype(np.float32)
y = m.predict(X)

print(y.shape)


text:
Q: Retrieve Function Key Name used in HTTP Hook in Azure Function I am assuming that the purpose of Function Keys in Azure Functions is to allow for multiple consumers of a function to each have their own unique Function Key. Thus, it would be easy for me to Revoke a key should we no longer want a vendor to be able to call that function.
However, I would also like to use that Function Key as a lookup to find which vendor called the Function. I could not find anything in the documentation on how to do this, nor is there anything in the HttpRequestMessage object that would indicate a place to find it.
Is there a way to retrieve the Key Name of the Function Key used to call an Azure Function?

A: Drovani,
Your assumption about the key usage is correct.
Unfortunately, that information isn't easily exposed today, but the actual key used is passed to you with the request (depending on how the client authenticated, either in as a query string named "code" or a header named "x-function-keys"), so you can derive the consumer from that information, but I agree that is not ideal, so I've opened an issue here so we can improve this.
Thank you!


text:
Q: How can there be a name before a class name? #ifndef __DynTex_H__
#define __DynTex_H__

#include "SdkSample.h"

using namespace Ogre;
using namespace OgreBites;

class _OgreSampleClassExport Sample_DynTex : public SdkSample
{
public:

    Sample_DynTex() : TEXTURE_SIZE(128), SQR_BRUSH_RADIUS(Math::Sqr(12))
    {

The class name is Sample_DynTex, as you can see from the constructor name. But how is _OgreSampleClassExport a valid syntax? What does it mean to have _OgreSampleClassExport? I couldn't even find a file with that name in the Ogre source.

A: _OgreSampleClassExport is almost certainly defined in a header along with it's import counterpart:
#define _OgreSampleClassExport __declspec(dllexport)
#define _OgreSampleClassImport __declspec(dllimport)


text:
Q: Marker current location android google map? How I can use from bellow marker for my map ?
I don't need to use mMap.setMyLocationEnabled(true);.I just need to this icon.

A: Try this :
GoogleMapOptions options = new GoogleMapOptions();
options.mapType(GoogleMap.MAP_TYPE_SATELLITE)
    .compassEnabled(true)
    .rotateGesturesEnabled(false)
    .tiltGesturesEnabled(false);

for details check this link.
https://developers.google.com/android/reference/com/google/android/gms/maps/UiSettings
or
https://developers.google.com/maps/documentation/android-api/controls
I use from this link and good work :
alazsbalazs


text:
Q: Trouble keeping buttons positioned at the bottom of the image - In responsive image gallery I've made a image gallery and I'm stuck on this problem from from quite time now as I want to position next and previous button on the bottom of the image but how can I make the buttons relative to the image as images are different and changes. How to put controller button at the bottom of the image.
What I'm trying to do:

*

*It has Full Screen background modal. (Done)

*Upon that modal it shows images. (Done)

*On image's bottom I want to keep a constant showing controller buttons which are next and previous button to change through images. (Stuck from two days)

Tried Till Now:

*

*Tried to make buttons relative to div's class "modal-content and image" but according to width size my buttons moves.

*Tried changing heights and widths of the divs and tried some other things too.

*At the end when nothing worked. I tried to achieve layout in a improper way by positioning buttons all the way from 1900px to 400px by media queries. But it still doesn't look good and accurate. (Have to use media queries only.)

*I know this is not a right way. What am I missing here? how to make elements responsive in this type of situations?
Please let me know by your expertise if I should try any different approach or If I do some mistakes with my CSS code.

function openModal() {
  document.getElementById('myModal').style.display = "block";
}

function closeModal() {
  document.getElementById('myModal').style.display = "none";
}

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");

  if (n > slides.length) {
    slideIndex = 1;
  }

  if (n < 1) {
    slideIndex = slides.length;
  }

  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }

  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }

  slides[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " active";
}
.photos-thumbnail {
  width: 440px;
}

.photos-thumbnail img {
  margin: 10px 2px 0 0;
  width: 140px;
  height: 100px;
  cursor: pointer;
}

.view-all-photos:hover {
  opacity: 0.7;
}

.column {
  float: left;
  width: 16.6%;
}

.pro-modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
}

.modal-content {
  position: relative;
  margin: 50px auto 0;
  width: 100%;
  height: 90%;
  background-color: rgba(0, 0, 0, 0.1);
}

.myslides img {
  object-fit: contain;
  background-color: rgba(0, 0, 0, 0.1);
  width: 100%;
  height: 100%;
}

.mySlides {
  display: none;
}

.column img {
  width: 100%;
}

.controller {
  position: absolute;
  background: linear-gradient(transparent, #1A1A1A);
  text-align: center;
  height: 12%;
  width: 100%;
  padding-top: 20px;
  margin-top: -110px;
}

.prev,
.next {
  position: absolute;
  cursor: pointer;
  background-color: rgba(0, 0, 0, 0.4);
  color: #ffffff;
  border: 1px solid #02BFC1;
  border-radius: 50%;
  width: 33px;
  padding: 15px;
  font-size: 25pt;
  transition: 0.6s ease;
  user-select: none;
  -webkit-user-select: none;
}

.next {
  margin-left: 50px;
}

.prev {
  margin-left: -50px;
}

      ❮
      |
      ❯

Output I want Even While Resizing

This happens after Browser window Resize. Image will start to fit the window and shrink as I want but buttons will be statically at the bottom.

A: If you change the display of the slides to this:
slides[slideIndex - 1].style.display = "inline-grid";

and with a few additionally changes at the css it should work.

The green marks are my changes.
I inserted a smaller image so that you can see the result in the code below.
I hope it helps.
EDIT:
To make the images resizing just add to your css:
img{
  max-width: 100%;
  height: auto;
}

And if you want the buttons staying in the middle during resizing, just put the controller div into the mySlides div -> see my code snippet

function openModal() {
  document.getElementById('myModal').style.display = "block";
}

function closeModal() {
  document.getElementById('myModal').style.display = "none";
}

var slideIndex = 1;

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");

  if (n > slides.length) {
    slideIndex = 1;
  }

  if (n < 1) {
    slideIndex = slides.length;
  }

  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }

  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }

  slides[slideIndex - 1].style.display = "inline-grid";
  dots[slideIndex - 1].className += " active";
}
.photos-thumbnail {
  width: 440px;
}

.photos-thumbnail img {
  margin: 10px 2px 0 0;
  width: 140px;
  height: 100px;
  cursor: pointer;
}

.view-all-photos:hover {
  opacity: 0.7;
}

.column {
  float: left;
  width: 16.6%;
}

.pro-modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
}

.modal-content {
  text-align: center;
  position: relative;
  width: 100%;
  height: 90%;
  background-color: rgba(0, 0, 0, 0.1);
}

.mySlides img {
  padding-left:75px;
  object-fit: contain;
  background-color: rgba(0, 0, 0, 0.1);
}

img{
  max-width: 100%;
  height: auto;
}
.mySlides {
  display: none;
  margin-right:75px;
  margin-top:25px;
}

.column img {
  width: 100%;
}

.controller {
  background: linear-gradient(transparent, #1A1A1A);

  height: 100px;
  width: 100%;
  padding-top: 20px;
  margin-top: -100px;
}

.prev,
.next {
text-align: center;
  position: absolute;
  cursor: pointer;
  background-color: rgba(0, 0, 0, 0.4);
  color: #ffffff;
  border: 1px solid #02BFC1;
  border-radius: 50%;
  width: 50px;
  padding: 15px;
  font-size: 25pt;
  transition: 0.6s ease;
  user-select: none;
  -webkit-user-select: none;
}

.next {
  margin-left: 50px;
}

.prev {
  margin-left: -50px;
}

      ❮
      |
      ❯

      ❮
      |
      ❯

      ❮
      |
      ❯

A: You can add display: flex, justify-content: (wherever in the image you want your buttons to be), and text-align to centre your buttons and their text.


text:
Q: Testing Ember Simple Auth in Ember App Kit with sinon I would like to mock server login responses when testing Ember Simple Auth in my Ember App Kit application. However, with the following code I get an opaque error 'Unexpected end of input' when the click action is called on the visit function :
var App;

module('Acceptances - SignIn', {
  setup: function(){
    App = startApp();
    this.xhr                = sinon.useFakeXMLHttpRequest();
    this.server             = sinon.fakeServer.create();
    this.server.autoRespond = true;
    sinon.spy(Ember.$, 'ajax');

    this.server.respondWith('POST', '/oauth/token', [
      200,
      { 'Content-Type': 'application/json' },
      '{"access_token":"secret token 2!","token_type":"bearer","expires_in":7200}'
    ]);

  },
  teardown: function() {
    Ember.run(App, 'destroy');
  }
});

test('authentication works correctly', function() {
  visit('/login').fillIn('#identification', "foo@bar.com").fillIn('#password', "password").click('button[type="submit"]').then(function() {
    ok(!exists('a:contains(Login)'), 'Login button is not displayed when authenticated');
  });
});

The #identification and #password input fields exists, and the submit button exists on the field that contains them.
I am including sinon and qunit in my headers. Am I calling sinon the wrong way or making some other mistake?
Edit: Resolution: By also including sinon-qunit the problem disappeared. It seems like you can not use sinon with Ember App Kit qunit tests without including sinon-qunit.
Edit 2: I open sourced an example with tests that mocks login responses with sinon here: https://github.com/digitalplaywright/eak-simple-auth

A: I open sourced an example with tests that mocks login responses with sinon here at https://github.com/digitalplaywright/eak-simple-auth
The example is made using Ember App Kit, Ember Simple Auth, and Ember.
This is how I use mock login responses in the:
var App;

module('Acceptances - SignIn', {
  setup: function(){
    App = startApp();
    this.xhr                = sinon.useFakeXMLHttpRequest();
    this.server             = sinon.fakeServer.create();
    this.server.autoRespond = true;
    sinon.spy(Ember.$, 'ajax');

    this.server.respondWith('POST', '/oauth/token', [
      200,
      { 'Content-Type': 'application/json' },
      '{"access_token":"secret token 2!","token_type":"bearer","expires_in":7200}'
    ]);

  },
  teardown: function() {
    Ember.run(App, 'destroy');
  }
});

test('authentication works correctly', function() {
  visit('/').then(function() {
    ok(exists('a:contains(Login)'), 'Login button is displayed when not authenticated');
    ok(!exists('a:contains(Logout)'), 'Logout button is not displayed when not authenticated');
  });

  visit('/login').fillIn('#identification', "foo@bar.com").fillIn('#password', "password").click('button[type="submit"]').then(function() {
    ok(!exists('a:contains(Login)'), 'Login button is not displayed when authenticated');
    ok(exists('a:contains(Logout)'), 'Logout button is displayed when authenticated');
  });
});


text:
Q: Invariant Violation - Unable to import custom component react native After read through many other similar questions I am still unable to import my custom component.
Here is main view:
import React from 'react';
import {Image, StyleSheet, Text, View} from 'react-native';
import {LOGO} from '../../assets/logo.png';
import {testingInput} from './testingInput';

function tempScreen({navigation}) {
    return (
        <View style={
            styles.container
        }>
            <View style={
                styles.topContainer
            }>
                <Image styles={
                        styles.logo
                    }
                    scoure={LOGO}
                    resizeMode={'cover'}/>
                <Text>
                    Here
                </Text>
            </View>

            <View style={
                styles.bottomContainer
            }>
                <testingInput/>
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    ...
})

export default tempScreen;

Here is tempButton File:
import React, {Component} from 'react';
import {TextInput, StyleSheet} from 'react-native';

const testingInput = (prop) => {
    return (
        <TextInput style={
                styles.TextInput
            }
            placeholder="Email"
            color="#ffffff"
            placeholderTextColor="#ffffff"
            autoCapitalize="none"></TextInput>
    )
}

const styles = StyleSheet.create({
    TextInput: {

        height: 50,
        flex: 1,
        padding: 10,
        marginLeft: 20
    }
})

export default testingInput;

Im getting the error

"Invariant Violation: View config getter callback for component testingInput must be a function (received undefined). Make sure to start component names with a capital letter."

Any help would be greatly appreciated!

A: When you use a default export you do not need destructuring the import.
with export default testingInput; you will import import TestInput from './testinputfile. Here the name of the import is not important
with export testingInput; you will import import {functionName} from './testinputfile. Here the name of the import need to be equal to the name of the function exported


text:
Q: Disable button if txtbox validates Edit
Solved! Thanks to @Peter Campbell for pointing me in the right direction (and then doing most of the leg work to get me there). Code changed to this:
If String.IsNullOrEmpty(output) Then
        exists = False
    Else
        exists = True
    End If
    If String.IsNullOrEmpty(output) Then Return String.Empty
    Dim c As GPCUser

    If TypeOf HttpContext.Current.Session("Customer") Is GPCUser Then
        c = CType(HttpContext.Current.Session("Customer"), GPCUser)

        If c.AccountNo > 0 Then Return ""
    End If

By moving the if statement that sets the 'exists' boolean to before any return statements, they still fire correctly and validate the emails properly, but will correctly disable the button as well.
End Edit
I have a page that checks the customer's email address to see if it's in our database. If it is, the page should ask the customer to log-in with that email instead of continuing with the new account, but it doesn't actually prevent them from continuing.
I would like to disable the continue button if the email address is already in the system but I can't figure out where (I'm the store's new web developer and there is no documentation to help me with the existing site).
Code Below,
<%@ Page Language="VB" MasterPageFile="~/Standard-no-menu.master"    AutoEventWireup="false" CodeFile="billing-details.aspx.vb" Inherits="billing_details" %>

"); -->
"); -->

<asp:Panel runat="server" DefaultButton="btnContinue">

Shopping Cart

Personal and Shipping Details

Payment Details

Payment Method

*

How would you like to pay?

<asp:DropDownList ID="lstPaymentOptions" runat="server" AppendDataBoundItems="True" CssClass="drop-down-list"></asp:DropDownList>

<asp:RequiredFieldValidator ID="paymentValidator" runat="server"
            ControlToValidate="lstPaymentOptions" ErrorMessage="Please select a payment method" ForeColor="Red" InitialValue="Please Select">
        </asp:RequiredFieldValidator>

Your Contact Details

Company / Account Name:

<asp:TextBox name="txtAccountName" ID="txtAccountName" MaxLength="60" Width="270" runat="server" CssClass="textbox"></asp:TextBox>

*

Email: <asp:RequiredFieldValidator ID="emailValidator" runat="server"
            ControlToValidate="txtEmail" ErrorMessage=" Required" ForeColor="Red">
        </asp:RequiredFieldValidator>

<asp:TextBox ID="txtEmail" MaxLength="60"
                    Width="270" runat="server" CssClass="textbox" AutoPostBack="True"></asp:TextBox> We have this email address already in our database. Click here to retrieve password?

*

First Name: <asp:RequiredFieldValidator ID="firstNameValidator" runat="server"
            ControlToValidate="txtFirstName" ErrorMessage=" Required" ForeColor="Red">
        </asp:RequiredFieldValidator>

<asp:TextBox name="txtFullName" ID="txtFirstName" MaxLength="30" Width="270" runat="server" CssClass="textbox"></asp:TextBox>

*

Last Name: <asp:RequiredFieldValidator ID="lastNameValidator" runat="server"
            ControlToValidate="txtLastName" ErrorMessage=" Required" ForeColor="Red">
        </asp:RequiredFieldValidator>

<asp:TextBox name="txtFullName" ID="txtLastName" MaxLength="30" Width="270" runat="server" CssClass="textbox"></asp:TextBox>

Additional Information relating to this order.

<asp:TextBox TextMode="MultiLine" Width="463" Height="212" runat="server" ID="txtAdditionalInfo" CssClass="textbox"></asp:TextBox>

<asp:Panel ID="pnlVerticalResponse" runat="server" Visible="false">

<asp:Label ID="lblSubscribe" runat="server" Text="
You are not subscribed to our Newsletter:"></asp:Label>

<asp:CheckBox ID="chkSubscribe" runat="server" />   I would like to receive information and promotional material from Global PC

</asp:Panel>
<asp:Panel ID="pnlOutOfStockBlurb" runat="server" Visible="false" >

<asp:Label ID="lblOutOfStockMessage" runat="server" Text="Items out of Stock:
You have ordered one or more items that are currently out of stock. Normal procedure is for Global PC to hold the order until all items are in stock and ship entire order at once. However, if you wish you can elect to have your order split into two shipments with the out of stock items arriving at a later date. Would you like your order split into two shipments?
"></asp:Label>

<asp:RadioButtonList ID="radlistSplit" runat="server" CellSpacing="5" AutoPostBack="true" CausesValidation="True" OnSelectedIndexChanged="radlistSplit_SelectedIndexChanged" CssClass="textbox" Borderwidth="0px"><asp:ListItem Value="0" Text="Yes, I want to recieve my order as two separate deliveries"></asp:ListItem><asp:ListItem Value="1" Text="No, I want to wait and receive all my items at once"></asp:ListItem></asp:RadioButtonList>
<asp:RequiredFieldValidator ID="splitvalidator" runat="server"
            ControlToValidate="radlistSplit" ErrorMessage="Please select one Shipping Option" ForeColor="Red">
        </asp:RequiredFieldValidator>

</asp:Panel>

            Back To Cart

            <asp:linkButton text="Checkout" OnClientClick="return validateForm();" runat="server" ID="btnContinue" />

</asp:Panel>

</asp:Content>

VB.NET
Imports DataAccessLayer
Imports System.Net
Imports System.Data
Imports System.Net.Mail
Imports com.verticalresponse.api

Partial Class billing_details
    Inherits System.Web.UI.Page
    Protected c As GPCUser
    Dim isMember As Boolean = False
    Dim beMember As Boolean = False
    Shared exists As Boolean = False

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Master.Page.Title += " - Checkout"

        Dim listID As Integer
        Dim sessionID As Integer
        Dim VRUser As New VRAPI()
        Dim newSession As New loginArgs()

        newSession.username = "******@********.co.nz"
        ' Your VerticalResponse username
        newSession.password = "**********"
        'Your VerticalResponse password
        ' objLA.impersonate_user = "subaccount@emailaddress.com"; // If accessing or acting as a subaccount, uncomment this and replace it with the applicable email address.
        newSession.session_duration_minutes = "120"
        Dim [date] As DateTime = DateTime.Now
        listID = 284662333

        If TypeOf Session("Customer") Is GPCUser Then
            c = CType(Session("Customer"), GPCUser)
        Else
            c = New GPCUser
        End If

        If c.CartObjects.Count <= 0 Then
            Response.Redirect("cart.aspx")
        End If

        If Not Page.IsPostBack Then

            ' Check shipping to see if delivery details need to be displayed
            If c.ShippingMethodName Like "*Pick-Up*" Then
                pnlShippingDetails.Visible = False
            End If

            'Check if customer has ordered out of stock items
            If c.intOutOfStockItems >= 1 Then
                pnlOutOfStockBlurb.Visible = True
            Else
                pnlOutOfStockBlurb.Visible = False
            End If

            txtEmail.Attributes.Add("onblur", CStr(IIf(c.AccountNo > 0, "", "CallMe(this.id,this.id);")))
            lstPaymentOptions.DataSource = SqlHelper.ExecuteDataset(System.Configuration.ConfigurationManager.AppSettings("dbConn"), "xw_GetPaymentTypes").Tables(0)
            lstPaymentOptions.DataTextField = "PTDESC"
            lstPaymentOptions.DataValueField = "PTNO"
            lstPaymentOptions.Items.Insert(0, "Please Select")
            'lstPaymentOptions.DataBind()

            If c.CustomerID > 0 Then
                'populate the table
                txtAccountName.Text = c.AccountName
                txtFirstName.Text = c.FirstName
                txtLastName.Text = c.LastName
                txtEmail.Text = c.Email
                txtAddress.Text = c.Address
                txtCityTown.Text = c.City
                txtSuburb.Text = c.Suburb
                txtPostcode.Text = c.PostCode
                txtPhone.Text = c.Phone
                txtMobile.Text = c.Mobile

                Try
                    sessionId = VRUser.login(newSession)
                Catch ex As System.Exception
                    'lblMessage.Text = ex.ToString()
                End Try
                Dim getMember As New getListMemberByEmailAddressArgs()
                getMember.session_id = sessionId
                getMember.list_id = listID
                getMember.email_address = txtEmail.Text
                Try
                    VRUser.getListMemberByEmailAddress(getMember)
                    isMember = True
                    pnlVerticalResponse.Visible = False
                Catch ex As System.Exception
                    isMember = False
                    pnlVerticalResponse.Visible = True
                End Try

                If (isMember = False) Then
                    pnlVerticalResponse.Visible = True
                End If

                Dim dt As Data.DataTable = GPCUser.GetAccount(c.AccountNo)
                If dt IsNot Nothing Then
                    If dt.Rows.Count > 0 Then
                        Dim dr As Data.DataRow = dt.Rows(0)
                        If dr("CREDITSTATUS") > "0" And dr("STOPCREDIT") = "N" And dr("CREDLIMIT") > "0" Then
                            lstPaymentOptions.Items.Remove("Please Select")
                            lstPaymentOptions.Items.Insert(0, New ListItem("My Global PC Account", "99"))
                            lstPaymentOptions.Items.Insert(0, "Please Select")
                        End If
                    End If
                End If
                dt.Dispose()

            End If
        End If
    End Sub

    'RadioButtons to set whether customer wants split shipping
    Protected Sub radlistSplit_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles radlistSplit.SelectedIndexChanged
        If radlistSplit.SelectedIndex = "0" Then
            c.Instructions = "**CUSTOMER HAS SELECTED SPLIT SHIPPING**"

        ElseIf radlistSplit.SelectedIndex = "1" Then
            c.Instructions = ""

        End If
    End Sub

    Protected Sub btnContinue_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnContinue.Click

        If TypeOf Session("Customer") Is GPCUser Then
            c = CType(Session("Customer"), GPCUser)
        Else
            Exit Sub
        End If

        If chkSubscribe.Checked = True Then
            Dim listID As Integer = 284662333
            Dim isMember As Boolean = False

            Dim newSession As New loginArgs()
            newSession.username = "austin@globalpc.co.nz"

            ' Your VerticalResponse username
            newSession.password = "global2012"

            'Your VerticalResponse password
            ' objLA.impersonate_user = "subaccount@emailaddress.com"; // If accessing or acting as a subaccount, uncomment this and replace it with the applicable email address.
            newSession.session_duration_minutes = "120"

            Dim [date] As DateTime = DateTime.Now

            ' This is generated by creating a Service Reference that points to the VerticalResponse WSDL.
            Dim VRUser As New VRAPI()

            ' Let's try to log in. The login call will return a session ID, which we will use in all subsequent calls.
            Dim sessionId As String = Nothing
            Try
                sessionId = VRUser.login(newSession)

            Catch ex As System.Exception
                txtAdditionalInfo.Text = ex.ToString()
                Exit Sub
            End Try

            Dim getMember As New getListMemberByEmailAddressArgs()
            getMember.session_id = sessionId
            getMember.list_id = listID
            getMember.email_address = txtEmail.Text

            Try
                VRUser.getListMemberByEmailAddress(getMember)
                isMember = True
            Catch ex As System.Exception
                isMember = False
            End Try
            If (isMember = False) Then
                Dim nMember As New ListMember()
                nMember.list_id = listID

                Dim memberData As NVPair() = New NVPair(2) {}

                memberData(0) = New NVPair()
                memberData(0).name = "email_address"
                memberData(0).value = txtEmail.Text

                memberData(1) = New NVPair()
                memberData(1).name = "first_name"
                memberData(1).value = txtFirstName.Text

                memberData(2) = New NVPair()
                memberData(2).name = "last_name"
                memberData(2).value = txtLastName.Text

                nMember.member_data = memberData

                Dim objAL As New addListMemberArgs()

                objAL.list_member = nMember
                objAL.session_id = sessionId

                Try
                    VRUser.addListMember(objAL)

                Catch ex As System.Exception
                    txtAdditionalInfo.Text = ex.ToString()
                    Exit Sub
                End Try

            Else

            End If

        End If

        c.PaymentType = lstPaymentOptions.SelectedValue
        c.CustomerOrderNo = txtOrderNumber.Text
        c.Instructions += txtAdditionalInfo.Text
        c.CreateCustomerDetails(txtAccountName.Text, txtFirstName.Text, txtLastName.Text, txtEmail.Text, txtAddress.Text, txtSuburb.Text, txtCityTown.Text, txtPostcode.Text, txtPhone.Text, txtMobile.Text, lstCountry.SelectedValue)
        c.AddShippingDetails(txtShippingFullName.Text, txtShippingAddress.Text, txtShippingCityTown.Text, txtShippingSuburb.Text, txtShippingPostcode.Text, lstShippingCountry.SelectedValue)

        If c.CustomerID = 0 Then
            Dim strPassword As String = ""
            If c.GeneratedPassword <= "" Then
                strPassword = UCase(RandomPassword.Generate(8, 8))
                c.GeneratedPassword = strPassword
            Else
                strPassword = c.GeneratedPassword
            End If

            GPCUser.AddUpdateCustomer(c)

            Dim dt As DataTable = GPCUser.GetUser(c.Email, strPassword)
            If Not dt Is Nothing Then
                If dt.Rows.Count > 0 Then
                    c.UpdateUser(dt.Rows(0)("CustID"))
                    Dim obj As Object = Session("Customer")
                    Session("Customer") = c
                Else

                End If
            Else
            End If

            Session("Customer") = c
        End If

        SendUpdateAccountEmailMessage(c.EmailCount)

        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

        Response.Redirect("payment-details.aspx")
    End Sub

    'Email Validation
    <System.Web.Services.WebMethod()> _
    Public Shared Function ValidateEmail(email As String) As String
        Dim wbClient As WebClient = New WebClient()
        Dim strUrl As String = ConfigurationManager.AppSettings("WebsiteURLFull") + "/ajax/check_email_address.aspx?Email=" + email
        Dim reqHTML As Byte()
        reqHTML = wbClient.DownloadData(strUrl)
        Dim objUTF8 As UTF8Encoding = New UTF8Encoding()
        Dim output As String = objUTF8.GetString(reqHTML)
        If String.IsNullOrEmpty(output) Then Return String.Empty
        Dim c As GPCUser

        If TypeOf HttpContext.Current.Session("Customer") Is GPCUser Then
            c = CType(HttpContext.Current.Session("Customer"), GPCUser)
            exists = False
            If c.AccountNo > 0 Then

                exists = True
            End If
            Return ""
        End If

        Return output
    End Function

    'Method to send an email from GlobalPC
    Private Sub SendMessage(fromEmail As String, fromEmailName As String, _
   toEmails As String(), IsBodyHtml As Boolean, message As String, subject As String)
        Dim mail As MailMessage = New MailMessage
        mail.From = New MailAddress(fromEmail, fromEmailName)

        For Each toEmail As String In toEmails
            mail.To.Add(New MailAddress(toEmail))
        Next

        mail.Bcc.Add(fromEmail)
        mail.IsBodyHtml = IsBodyHtml
        mail.Subject = subject
        mail.Body = message
        Dim s As New SmtpClient(System.Configuration.ConfigurationManager.AppSettings("MailServer"))
        s.Send(mail)
    End Sub

    'Sends email to GlobalPC if customer updates account details.
    Private Sub SendUpdateAccountEmailMessage(emailCount As Integer)
        Dim subject As String = "ALERT : Website user has updated his details"
        Dim message As String
        message &= "Account number " & c.AccountNo & " with email address " & c.Email & " has updated his account. Via page billing-details" & vbCrLf & vbCrLf
        message += "Account Name : " & txtAccountName.Text & vbCrLf
        message += "First Name : " & txtFirstName.Text & vbCrLf
        message += "Last Name : " & txtLastName.Text & vbCrLf
        message += "Email : " & txtEmail.Text & vbCrLf
        message += "Address : " & txtAddress.Text & vbCrLf
        message += "Suburb : " & txtSuburb.Text & vbCrLf
        message += "City Town : " & txtCityTown.Text & vbCrLf
        message += "Country : " & lstCountry.SelectedValue & vbCrLf
        message += "Postcode : " & txtPostcode.Text & vbCrLf
        message += "Phone : " & txtPhone.Text & vbCrLf
        message += "Mobile : " & txtMobile.Text & vbCrLf
        message += vbCrLf & vbCrLf
        message += "Shipping Information" & vbCrLf
        message += "txtShippingFullName.Text : " & txtShippingFullName.Text & vbCrLf
        message += "txtShippingAddress.Text  : " & txtShippingAddress.Text & vbCrLf
        message += "txtShippingCityTown.Text : " & txtShippingCityTown.Text & vbCrLf
        message += "txtShippingSuburb.Text : " & txtShippingSuburb.Text & vbCrLf
        message += "txtShippingPostcode.Text : " & txtShippingPostcode.Text & vbCrLf
        message += "lstShippingCountry.SelectedValue : " & lstShippingCountry.SelectedValue & vbCrLf
        message += vbCrLf & vbCrLf
        message += "More Information" & vbCrLf
        message += "Order No: " & c.CustomerOrderNo & vbCrLf
        message += "Payment Type: " & c.PaymentType & vbCrLf
        message += "Instructions: " & c.Instructions & vbCrLf
        message += vbCrLf & vbCrLf
        message += "Regards" & vbCrLf & vbCrLf & "GlobalPC Admin Team"

        SendMessage(ConfigurationManager.AppSettings("AccountDetailsUpdateEmail"), "Global PC", _
                                New String() {ConfigurationManager.AppSettings("AccountDetailsUpdateEmail")}, False, message, subject)
    End Sub

    Protected Sub txtEmail_TextChanged(sender As Object, e As System.EventArgs) Handles txtEmail.TextChanged

        Dim listID As Integer = 284662333
        Dim isMember As Boolean = False
        Dim newSession As New loginArgs()
        newSession.username = "austin@globalpc.co.nz"
        ' Your VerticalResponse username
        newSession.password = "global2012"
        'Your VerticalResponse password
        ' objLA.impersonate_user = "subaccount@emailaddress.com"; // If accessing or acting as a subaccount, uncomment this and replace it with the applicable email address.
        newSession.session_duration_minutes = "120"
        Dim [date] As DateTime = DateTime.Now
        ' This is generated by creating a Service Reference that points to the VerticalResponse WSDL.
        Dim VRUser As New VRAPI()

        ' Let's try to log in. The login call will return a session ID, which we will use in all subsequent calls.
        Dim sessionId As String = Nothing

        Try
            sessionId = VRUser.login(newSession)
        Catch ex As System.Exception
            'lblMessage.Text = ex.ToString()
        End Try

        Dim getMember As New getListMemberByEmailAddressArgs()
        getMember.session_id = sessionId
        getMember.list_id = listID
        getMember.email_address = txtEmail.Text
        Try
            VRUser.getListMemberByEmailAddress(getMember)
            isMember = True
            pnlVerticalResponse.Visible = False
        Catch ex As System.Exception
            isMember = False
            pnlVerticalResponse.Visible = True
        End Try

    End Sub

    Protected Sub chkSubscribe_CheckedChanged(sender As Object, e As System.EventArgs) Handles chkSubscribe.CheckedChanged

        If chkSubscribe.Checked = True Then
            beMember = True
        Else
            beMember = False
        End If

    End Sub
End Class

A: Looks like the email is checked against current addresses here
'Email Validation
    <System.Web.Services.WebMethod()> _
    Public Shared Function ValidateEmail(email As String) As String
        Dim wbClient As WebClient = New WebClient()
        Dim strUrl As String = ConfigurationManager.AppSettings("WebsiteURLFull") + "/ajax/check_email_address.aspx?Email=" + email
        Dim reqHTML As Byte()
        reqHTML = wbClient.DownloadData(strUrl)
        Dim objUTF8 As UTF8Encoding = New UTF8Encoding()
        Dim output As String = objUTF8.GetString(reqHTML)
        If String.IsNullOrEmpty(output) Then Return String.Empty
        Dim c As GPCUser

        If TypeOf HttpContext.Current.Session("Customer") Is GPCUser Then
            c = CType(HttpContext.Current.Session("Customer"), GPCUser)
            exists = False
            If c.AccountNo > 0 Then

                exists = True
            End If
            Return ""
        End If

so exists is the variable that tells you if the address is matched.
Try adding to the Page_Load method
 If Page.IsPostBack Then
   If exists Then
      btnContinue.enabled = false
   End If
 End If

As the page is posted back to the server after the button click, this will check to see if exists is true and if it is disable the button.

p.s. I would change the username/password to use
  ConfigurationManger.Appsettings and put your username in web.config.


text:
Q: Priorizing CSS properties
I am building websites for a while, and I have a question about CSS I can't really rid over. So there is that frequent situation when multiple classes affect a DOM element, and both classes declare the same properties. For example:
.first {
    color:white;
}

.second {
    color:black;
}

I know that if I have an element with class="first second" in that the text will be black. If I rather want it to be white, I have several options:

*

*Using !important: I know this one is handy and I use it, but sometimes, if I use it too often, my CSS may become messy. I mean, multiple !important's can result the same basic situation.

*Reordering the classes inline: if I am correct, which class comes first, it will be the priority one. This is nice, but i often work with environments where I can't affect that. Secondly, this is not a global but a local solution.

*Reorder the CSS itself: well, this sounds interesting, but if I work with many stylesheets (and I do), it is hard to track, especially when it is WIP.

Actually what I am looking for is some workaround like z-index but for priorizing which class is stronger. Because I can't really find anything useful in this topic, I am just curious maybe it is a user error, and you guys know something I don't. How do you manage this? What do you suggest?

A: class="first second" is the same as class="second first". The priority is based on the position of the declarations in your css and not in their position on the html element.
So, if you want priority of a class against another, put the top priority class LAST on the css file.
.first {
color:white;
}
.second {
color:black;
}

in this example, class second has always priority over class first. This happens because browser scans through the css top-to-bottom and always applying the rules of matched classes that finds. So, the last matched class has priority over the previous matched classes.
see this fiddle: http://jsfiddle.net/5c29dzrr/

A: At the same specificity level, the CSS selector that is furthest down the stylesheet will be applied. So in your example, if you wanted in that situation to have the element with the white colour you would have to order your properties like so:
.second {
    color: black;
}

.first {
    color: white;
}

The order of the classes in the HTML tag is not important; it is the order in which they appear in your CSS.
The better way to handle this is to go with some better naming convention such as BEM or SMACSS so that you don't have the issue of conflicting class names.
Edit: It might be worth reading up on specificity and the cascade for a better understanding of this. I found this calculator to be pretty handy in determining which rules will take precendence, although these days you can just use the developer tools to find out that information.


text:
Q: CI-Neo4jPHP, getting labels from a node This script below writen in CI and Neo4jPHP environment.
    $client = new Everyman\Neo4j\Client("localhost", 7474);
    $client->getTransport()->setAuth("admin","password");

    $all_labels = $client->getLabels();
    foreach ($all_labels as $key=>$a_label)
    {
        echo $key.": ".$a_label->getName()."\n";
    }

List of labels expected,
but i didn't get anything.


text:
Q: Determinant of $(p(x_i-x_j))_{1 \leq i,j \leq n}$ for polynomial $p(x)$. Let $p(x) = a_0 + a_1 x + \ldots + a_k x^k$ be a polynomial.
Can anything be said in general about the determinant $\mathrm{det}_{1 \leq i,j \leq n} (p(x_i-x_j))$ for a collection of variables $x_1,\ldots,x_n$?
It seems that for small $n,k$, the first order term in the determinant - which is itself a polynomial in the variables $x_1,\ldots,x_n$ - is a Vandermonde determinant.


text:
Q: Object is possibly null - even after null check I'm using Typescript 2.8
My code is this:
class Wizard extends React.Componenet {

    private divElement: null | HTMLDivElement = null;

    componentDidUpdate(_: IWizardProps, prevState: IWizardState) {
        if (this.divElement) {
            this.getOverflowParent(this.divElement).scrollTop = 0;
        }
    }

}

I wrap it with an if to ensure it is not null, however compiler keeps failing saying it is possibly null. May you please advise?

A: You should also check if this.getOverflowParent(this.divElement) is null before using its scrollTop property. For example,
if (this.divElement) {
    var overflowParent = this.getOverflowParent(this.divElement);
    if (overflowParent)
        overflowParent.scrollTop = 0;
}


text:
Q: how to avoid EventBus Exception (Android)? I"m working on existing application and they are using EventBus that get every network exception like this :
  public void onEvent(final NetworkErrorEvent event) {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {

            Log.e("EventBus Event" + "(IOException)");

            if (event.getType() == NetworkError.Timeout) {
                L.e("timeout");
            } else if (event.getType() == NetworkError.Disconnected) {
                L.e("disconnected");
            } else if (event.getType() == NetworkError.UnknownHost) {
                L.e("UnknownHost");
            }

             showConnectionErrorDialog(event.getType(), true);
        }
    });
}

i want to add api call that i don't want to notify EventBus if failed , how it can be done ?
i don't see eventBus.post(event) in my project , the code i wrote is capture every network error even if i don't want him to .

A: The NetworkErrorEvent is not part of the EventBus - I suggest finding out where it comes from and starting there. I suspect it may be custom code wrapping something from Retrofit.
The EventBus is perfect for something like logging network failures because you can fire the events off everywhere in your code, and then simply choose to handle those events somewhere, or even multiple places, or nowhere..


text:
Q: Updating text box from subform I have the main form "MForm" with 2 subforms "subform1" and "subform2".
On subform1 i have 5 tabbed pages: Page1, Page2, Page3, Page4, Page5. Each tab will have a subfom included.
On Page1 i have a form "subform3".
My question is, how i can update a text box "txt_test" from subform3 from subform2?
I tried:
Forms!MForm!subform1.Form!subform2.Form!txt_test.Value

Forms!MForm!subform1!Tab.Pages("Page1").txt_test.Value

I am new to access and i can't find a way to access the data from other subforms.

A: Try this:
Forms!mform!subform2!txt_test.Value = Me.txt_test3.Value

txt_test3 is the textbox in subform3 (on Page 1 of subform1).

A: IF you put code into module of form subform3 then this code should change value of txt_test inside subform2:
Me.parent.subform2.form.controls("txt_test").Value = "some value"


text:
Q: Coil unit testing - how to do this? Is it possible to mock coil network level when unit testing? With MockWebServer? Or test it somehow else? I can't find information on the Internet about it.

A: I've found the answer. We can use OkHttp's mock web server. Also check out: https://coil-kt.github.io/coil/image_loaders/#testing


text:
Q: How to crop and resize image using vb.net and SQL Server I'm using vb.net and sql server 2008 and a picturebox for uploading photos.
This is what I want to do.
1.The image can be anything. It can be bitmap,jpg,png, anything
2. upload image from my computer
3. Crop the image and resize it to fit in my picture box.
4. Save it to the SQL Server database
This is my working code for uploading and saving images in the database.
Public Class Form1
  Dim a As New OpenFileDialog

 Private Sub PictureBox1_DoubleClick(sender As Object, e As EventArgs) Handles PictureBox1.DoubleClick
        Dim picl as string
        a.filter = nothing
        picl = a.filename
        a.showdialog()
        picturebox1.image = image.fromfile(a.filename)
 End Sub

 Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
 cn.Open()
    Using cmd As New SqlClient.SqlCommand("dbo.uspAdd", cn)
                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.Add(New SqlClient.SqlParameter("@customerPic", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
                cmd.ExecuteNonQuery()
                MsgBox("Save Record New record Successfully")
            End Using
cn.close
End Sub

I have read some reference here but it does not work for me and now I'm stuck for almost an hour.
This is what i have tried.
Imports System.Drawing.Drawing2D
    Public Class Form1
    Dim a As New OpenFileDialog
    Private Sub PictureBox1_DoubleClick(sender As Object, e As EventArgs) Handles PictureBox1.DoubleClick
        Dim picl As String
        a.Filter = Nothing
        picl = a.FileName
        a.ShowDialog()
        PictureBox1.Image = Image.FromFile(a.FileName)
        Dim OriginalImage = Image.FromFile(a.FileName)
        Dim CropRect As New Rectangle(100, 0, 100, 100)
        Dim CropImage = New Bitmap(CropRect.Width, CropRect.Height)
        Using grp = Graphics.FromImage(CropImage)
            grp.DrawImage(OriginalImage, New Rectangle(0, 0, CropRect.Width, CropRect.Height), CropRect, GraphicsUnit.Pixel)
            OriginalImage.Dispose()
        End Using
    End Sub

Can someone please help me to fix my code. Any help would be very much appreciated. Thanks

A: you can crop image and designate the path and the name of cropped image with the following code sample , anyway ur sql fucntion needs  image file path
  Dim LocX = 100 'x cord. of where crop starts
    Dim LocY = 0 'y  cord. of where crop starts
    Dim CropW = 100 'Crop width
    Dim CropH = 100 'Crop height
    Dim CropRect As New Rectangle(LocX, LocY, CropW, CropH)
    Dim OriginalImage = PictureBox1.Image
    Dim CropImage = New Bitmap(CropRect.Width, CropRect.Height)
    Using grp = Graphics.FromImage(CropImage)
        grp.DrawImage(OriginalImage, New Rectangle(0, 0, CropRect.Width, CropRect.Height), CropRect, GraphicsUnit.Pixel)
        CropImage.Save("cropped file path and name here")
    End Using