text:
Q: How do I set up a multi-project solution in C++? I'm new to C++ and I'm having a hard time getting my dll references to work. I've been trying to get it to work for a couple of days, but the few explainations I've found often refer to doing x or y, but don't tell me how to do x or y. Since I'm not a C++ veteran, I need someone to walk me through it. What I want to do is the following:
MySolution
    MyExe (Win32 .exe)
        Main.h
        Main.cpp
            (constructs ImplementationB calls the methods as defined by InterfaceA, then deletes the instances)
            (calls/fills HelperC.Foobar)
    MyInterfaces (dll)
        InterfaceA.h
            ~InterfaceA();
            virtual void DoSomething();
    MyUtils (dll)
        HelperC.h
            static float Foobar;
        HelperD.cpp
            float HelperC::Foobar = 1.0f;
    MyImplementations (dll)
        ImplementationB : InterfaceA
            (uses the value from HelperC.Foobar)

The MyExe and MyImplementations projects contain most of the executing code. But, I need an interface, so I need an interface project (MyInterfaces). I need some helper classes that need to be accessible from both MyExe and MyImplementations, hence MyUtils. I would like this helper class to be statically available, though it is not mandatory.
I had a compiling version before I started adding MyUtils with the HelperC class. I had to mark the interface destructor with __declspec(dllexport), along with the DoSomething method. I also had to mark the constructor of ImplementationB in order to instantiate it from MyExe, which makes sense. However, when I tried to mark the entire class (both the implementation and the interface) with __declspec(dllexport), the example wouldn't compile (which does not make sense).
From what I've read, having static fields in a dll and using them from external code doesn't really work all too well. So, as an alternative, I made Foobar non-static and passed a HelperC instance to the method as described by InterfaceA. Since I had already gotten simple classes to work, I figured that should work as well. However, now the compiler is throwing errors on the constructor of ImplementationB (LNK2019).
In short: I'm getting link errors all over the place in sections that have nothing to do with my changes, and there's little documentation describing the specific steps I need to perform in order to get a simple dll reference to work.
Can someone point out what I need to add and where I need to add it in order to make it compile? Also, some do's and don't's about C++ dll references would help a lot (e.g. don't use statics across projects).

A: After much digging, I found out that the culprit was a magical project setting. It is called Ignore Import Library and is located at Project Properties->Linker->General, and is set to Yes by default, while it should be set to No in most cases. The setting tells the executable project to use the dll's lib file during compilation. This still sounds strange to me (sounds like duplicate build output), but as far as I understand it, the lib file describes how to link to the dll. If your dll produces a lib during build, you probably want to set the setting to No.
I also learned that to be able to use the HelperC class as a statically accessible helper, I needed to use dllimport in combination with the macro trick, as described by @drescherjm. The dllimport declaration is only ever needed to be able to use data members across libraries (static class fields or globally defined variables). It may be applied to functions as well, though it is not required, in which case it provides a slight performance boost during library linking.
For completeness, my project structure after getting it to work:
MySolution
    MyExe (Win32 .exe, Debugger Type=Mixed)
        Main.h
        Main.cpp
            (constructs ImplementationB calls the methods as defined by InterfaceA, then deletes the instances)
            (calls/fills HelperC::Foobar)
    MyInterfaces (dll, Ignore Import Library=Yes, because there is no .lib after building)
        InterfaceA.h
            class __declspec(dllexport) InterfaceA
                ~InterfaceA() {};
                virtual void DoSomething() = 0;
    MyUtils (dll, Ignore Import Library=No)
        HelperC.h
            class __declspec(dllimport/dllexport) HelperC // (see macro trick)
                static float Foobar;
        HelperD.cpp
            float HelperC::Foobar = 1.0f;
    MyImplementations (dll, Ignore Import Library=No)
        ImplementationB.h
            class __declspec(dllexport) ImplementationB : public InterfaceA
                ImplementationB();
                ~ImplementationB();
                void DoSomething();
        ImplementationB.cpp
            ImplementationB::ImplementationB() {};
            ImplementationB::~ImplementationB() {};
            ImplementationB::DoSomething() { /* Omitted */ };
                (uses HelperC::Foobar in implementation)

On a side note: if you added a default C++ class library project in Visual Studio, you may need to flip the Project Properties->Debugging->Debugger Type setting to Mixed before you will be able to set/use breakpoints in the dll code. See this.
I hope this helps others who are wrestling with dll's in C++ (and Visual Studio).


text:
Q: Security Analysis for Android app APK I am working on a project where I am asked to manually conduct security analysis on android app APKs, such as Misuse of Phone Identifiers, Exposure of Physical Location ...ect. The burden lies in the fact that I don't know how to go about it. I know how to decompile the apk into java classes but what after that?
My question: are there best practices, tools, universal guide to conduct such analysis?

A: While this is a very general question that requires extensive understanding the security field, here are some options...

*

*Decompile the app from dex->jar->java and see how well the code is obfuscated. More info here: decompiling DEX into Java sourcecode

*Intercept the packets that are being sent through a WiFi router using WireShark or some alternative. If the packets are sending raw locations you know something is wrong. A real life example was this: Marijuana app reveals location

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mostrar resultado de la resta de fechas en pantalla, he tratado de visualizar el resultado y me genera error o simplemente no lo muestra en Python Aca la consulta
for BBDDEscuela in elUsuario:
    miID.set(BBDDEscuela[0])
    miNombre1.set(BBDDEscuela[1])
    miNombre2.set(BBDDEscuela[2])
    miApellido1.set(BBDDEscuela[3])
    miApellido2.set(BBDDEscuela[4])
    miSexo.set(BBDDEscuela[5])
    miFecha=(BBDDEscuela[6])
    c=miFecha

Llamada de función para calcular días
Calculo_Dias(c)
miConexion.commit()

Aquí la función para calcular días
def Calculo_Dias(b):
    a=datetime.datetime.today()
    f=datetime.datetime.strptime(str(b), '%Y-%m-%d')
    miDias=(a-f)
    k=miDias.days
    miDias=int(k)

Aquí muestro en pantalla
cuadroDias=Entry(miFrame1, width=30, textvariable=miDias, state=DISABLED)
cuadroDias.grid(row=4, column=2, padx=10, pady=10)

Me pueden ayudar quizás es simple pero llevo una semana tratando de resolverlo y no he podido.


text:
Q: Flutter, ScaleTransition vs Transform.scale So there are 2 types in explicit animations right?
Aren't ScaleTransition and Transform.scale both explicit animations?
Why do you need two methods?

A: Transform.scale is a static scaling widget, that cannot perform animation itself, and should be wrapped inside a TwennAnimationBuilder. The animation cannot be controlled once completed.
ScaleTransition takes Animation as a value of its scale parameter which is controlled by AnimationController hence it's an explicit animation.


text:
Q: Java Android studio Application - How to rename correctly photos after taking them with the camera? I've a little problem. There are 2 days that I am trying to solve it without success.
I am trying to create an app that name every photo taken by a predefined name (ex : "coucou.jpg" instead of "IMG_20191119_201907.jpg").
So I've applyed some tutorials on the internet (https://developer.android.com/training/camera/photobasics.html#TaskPhotoView  -  https://www.youtube.com/watch?v=8890GpBwn9w (in french))
And it works !... Almost !
The photo are well created in the folder "Pictures".
But the problem that I have is the following : Created files don't receive the name that I gave to them. They are named 1574245595878.jpg - 1574245714222.jpg - 1574358229963.jpg - etc.
And I don't know where I'm wrong... I give you my code, normally, they should be called "coucou.jpg")
Can someone help me to give them the good name (or at least to rename them after creation in the same code) please ? It would be wonderful !
public class MainActivity extends AppCompatActivity {

    private static final int RETOUR_PRENDRE_PHOTO = 1;
    private Button btnPrendrePhoto;
    private ImageView imgAffichePhoto;
    private String photoPath = null;
    private Bitmap image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initActivity();
    }

    private void initActivity(){
        btnPrendrePhoto = (Button)findViewById(R.id.btnPrendrePhoto);
        imgAffichePhoto = (ImageView)findViewById(R.id.imgAffichePhoto);
        btnPrendrePhoto.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View v) {
                prendreUnePhoto();
            }
        });
    }

    private void prendreUnePhoto(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(intent.resolveActivity(getPackageManager()) != null){
            File photoDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            try {
                File photofile = File.createTempFile("coucou",".jpg",photoDir);
                photoPath = photofile.getAbsolutePath();
                Uri photoUri = FileProvider.getUriForFile(MainActivity.this, MainActivity.this.getApplicationContext().getPackageName()+".fileprovider", photofile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(intent, RETOUR_PRENDRE_PHOTO);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==RETOUR_PRENDRE_PHOTO && resultCode==RESULT_OK){
            image = BitmapFactory.decodeFile(photoPath);
            imgAffichePhoto.setImageBitmap(image);
            MediaStore.Images.Media.insertImage(getContentResolver(), image, "coucou.jpg", "description");
        }
    }
}

A: When you say createTempFile() it will append timestampInMillis to end of created File, that's the numbers you are looking at in your case, so try creating a normal File
replace
File photofile = File.createTempFile("coucou",".jpg",photoDir);

with
File image = new File(photoDir, "coucou.jpg");


text:
Q: Find first string in text string that is numbers only. Formulas only Is it possible to find the first string within a string that contains only numbers/digits? I have a few thousand addresses to process and some of them have Apartment numbers. I need to find the address number and extract it but the apartment number get extracted instead.
I was able to extract the first number string with this Formula, OneToZero is {1,2,3,4,5,6,7,8,9,0}
=MID($A1,MIN(IFERROR(FIND(OneToZero,$A1),"")),FIND(" ",$A1,MIN(IFERROR(FIND(OneToZero,$A1),"")))-MIN(IFERROR(FIND(OneToZero,$A1),""))-0)

Returns this.
1417 Horne RD #1445A (Building 15) ----- 1417(Correct)
Westwood #104A 801 Cantwell Ln --------- 104A(wrong)  801(Correct)
I tried using
=MID($A1,MIN(IFERROR(FIND(" "&OneToZero," "&$A1),"")),FIND(" ",$A1,MIN(IFERROR(FIND(" "&OneToZero," "&$A1),"")))-MIN(IFERROR(FIND(" "&OneToZero," "&$A1),""))-0)

But returns this if the first number doesn't have a non-digit character in front.
Westwood 104A  801 Cantwell Ln --------- 104A(wrong)  801(Correct)
Cannot just remove the first string using the "#" due to it may say "Apt#" or just "104A".
Thank you.

A: I found this to test the String
=IF(AND(ISNUMBER(--(MID(A1,ROW(INDIRECT("1:"&LEN(A1))),1)))),A1,"")

and placed the code to locate the first string and second string.
Here is the entire thing. I don't know much about this, just pieced a bunch of different little snippets. I am now hoping that someone can help me streamline this.
    =IF(AND(ISNUMBER(--(MID(

MID([@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),"")),FIND(" ",[@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),"")))-MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),""))-0),ROW(INDIRECT("1:"&LEN(MID([@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),"")),FIND(" ",[@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),"")))-MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),""))-0)))),1)))),

MID([@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),"")),FIND(" ",[@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),"")))-MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),""))-0),

MID([@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin],FIND(" ",[@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),""))+0)),"")),FIND(" ",[@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin],FIND(" ",[@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),""))+0)),""))),"")))-MIN(IFERROR(FIND(" "&OTZ," "&[@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin],FIND(" ",[@Origin],MIN(IFERROR(FIND(" "&OTZ," "&[@Origin]),""))+0)),""))),""))-0))

It is very long. I changed "OneToZero" is {1,2,3,4,5,6,7,8,9,0} to OTZ. [@Origin] is the column where the "raw data"(Unformatted Addresses) is.

A:
Since you asked for an example of a VBA solution, this will print the first only numeric sub-string in the cell to the right -
Option Explicit

Public Sub ExtractStreetNumber()
    Application.ScreenUpdating = False
    Const nullCharacter As String = " "
    Dim subString As String
    Dim fullAddress As String
    Dim subStringArray() As String
    Dim arrayPosition As Long
    Dim testCell As Range
    Dim addressTestRange As Range
    Set addressTestRange = Range("A1:A3") 'put your range of addresses here

    For Each testCell In addressTestRange
        fullAddress = testCell
        subStringArray = Split(fullAddress, nullCharacter)
        For arrayPosition = 0 To UBound(subStringArray)
            subString = subStringArray(arrayPosition)
            If IsNumeric(subString) Then
            testCell.Offset(, 1) = subString
            GoTo NextIteration
            End If
        Next
NextIteration:
    Next
    Application.ScreenUpdating = True
End Sub

You could also create a user-defined function to use on the worksheet like ExtractStreetNumber(A1) -
Option Explicit

Public Function ExtractStreetNumber(ByVal fullAddress As String) As Long

    Const nullCharacter As String = " "
    Dim subString As String
    Dim subStringArray() As String
    Dim arrayPosition As Long

        subStringArray = Split(fullAddress, nullCharacter)
        For arrayPosition = 0 To UBound(subStringArray)
            subString = subStringArray(arrayPosition)
            If IsNumeric(subString) Then
                ExtractStreetNumber = subString
            Exit Function
            End If
        Next

End Function

A: Here's another way to do it with a formula, but you need to text to columns it and I'm blatantly ripping off Scott's answer to a different question.
First I'd copy the data to a new sheet.
Go to data - data tools - text to columns - delimited - space
Now you can find the first only numeric substring in each row with something like
=INDIRECT(ADDRESS(ROW(),MIN(IF(ISNUMBER(A1:F1),COLUMN(A1:F1)))))

It's an array formula so you need to use Ctrl+Shft+Entr and make sure it gets curly brackets.
Now you can copy - paste special the number back to the original sheet.


text:
Q: pyparsing: example JSON parser fails for list of dicts All,
I'm trying to understand how to handle a list of Dicts using pyparsing. I've gone back to the example JSON parser for best practices but I've found that it can't handle a list of dicts either!
Consider the following (this is the stock example JSON parser, but with some comments removed and my test case instead of the default one):
#!/usr/bin/env python2.7

from pyparsing import *

TRUE = Keyword("true").setParseAction( replaceWith(True) )
FALSE = Keyword("false").setParseAction( replaceWith(False) )
NULL = Keyword("null").setParseAction( replaceWith(None) )

jsonString = dblQuotedString.setParseAction( removeQuotes )
jsonNumber = Combine( Optional('-') + ( '0' | Word('123456789',nums) ) +
                    Optional( '.' + Word(nums) ) +
                    Optional( Word('eE',exact=1) + Word(nums+'+-',nums) ) )

jsonObject = Forward()
jsonValue = Forward()
jsonElements = delimitedList( jsonValue )
jsonArray = Group(Suppress('[') + Optional(jsonElements) + Suppress(']') )
jsonValue << ( jsonString | jsonNumber | Group(jsonObject)  | jsonArray | TRUE | FALSE | NULL )
memberDef = Group( jsonString + Suppress(':') + jsonValue )
jsonMembers = delimitedList( memberDef )
jsonObject << Dict( Suppress('{') + Optional(jsonMembers) + Suppress('}') )

jsonComment = cppStyleComment
jsonObject.ignore( jsonComment )

def convertNumbers(s,l,toks):
    n = toks[0]
    try:
        return int(n)
    except ValueError, ve:
        return float(n)

jsonNumber.setParseAction( convertNumbers )

if __name__ == "__main__":
    testdata = """
[ { "foo": "bar", "baz": "bar2" },
  { "foo": "bob", "baz": "fez" } ]
    """
    results = jsonValue.parseString(testdata)
    print "[0]:", results[0].dump()
    print "[1]:", results[1].dump()

This is valid JSON, but the pyparsing example fails when trying to index into the second expected array element:
[0]: [[['foo', 'bar'], ['baz', 'bar2']], [['foo', 'bob'], ['baz', 'fez']]]
[1]:
Traceback (most recent call last):
  File "json2.py", line 42, in <module>
    print "[1]:", results[1].dump()
  File "/Library/Python/2.7/site-packages/pyparsing.py", line 317, in __getitem__
    return self.__toklist[i]
IndexError: list index out of range

Can anyone help me in identifying what's wrong with this grammar?
EDIT: Fixed bug in trying to parse as JSON Object, not value.
Note: This is related to: pyparsing: grammar for list of Dictionaries (erlang) where I'm basically trying to do the same with an Erlang data structure, and failing in a similiar way :(

A: This may be valid JSON, but your grammar won't handle it. Here's why:
jsonObject << Dict( Suppress('{') + Optional(jsonMembers) + Suppress('}') )

This says the grammar object must be surrounded by {...}. You are bracing it as an array [...]. Since the top-level object must be a dictionary, it will need key names. Changing your test data to:
{ "col1":{ "foo": "bar", "baz": "bar2" },
  "col2":{ "foo": "bob", "baz": "fez" } }

or
{ "data":[{ "foo": "bar", "baz": "bar2" },
          { "foo": "bob", "baz": "fez" }] }

will allow this grammar to parse it. Want a top-level object to be an array? Just modify the grammar!

A: The parse results object that you get back from this expression is a list of the matched tokens - pyparsing doesn't know if you are going to match one or many tokens, so it returns a list, in your case of list containing 1 element, the array of dicts.
Change
results = jsonValue.parseString(testdata)

to
results = jsonValue.parseString(testdata)[0]

and I think things will start to look better.  After doing this, I get:
[0]: [['foo', 'bar'], ['baz', 'bar2']]
- baz: bar2
- foo: bar
[1]: [['foo', 'bob'], ['baz', 'fez']]
- baz: fez
- foo: bob


text:
Q: Do hex-changed torrent files (*.torrent) create issues? I am aware of that torrent files have the function of hash-check, but what about the files not in the *.torrent files themselves? To check torrent files, it needs the original hash checksum values of the torrent files themselves.
For example, anyone can hex edit like marking 00 codes or anything to create torrent files.
Torrent files can be changed in this way, but I found they can be run by torrent client with no warning. After that, i wonder if torrent files are already changed by hex edit, or whether they are making any kind of changes to check, hash files in torrents.

A: Each torrent has an unique ID called the infohash, and you can only download files from peers who seed the exact same infohash. If the infohash is different, even though the files themselves might be the same, that still makes it an entirely new torrent.
The infohash is directly based on the info dict structure inside the .torrent file. All .torrent files are structured data, encoded in the bencode format. Converted to text, this Ubuntu torrent – for example – would look like this:

{
    "announce": "http://torrent.ubuntu.com:6969/announce"
    "announce-list": [
        0: [
            0: "http://torrent.ubuntu.com:6969/announce"
        ]
        1: [
            0: "http://ipv6.torrent.ubuntu.com:6969/announce"
        ]
    ]
    "comment": "Ubuntu CD releases.ubuntu.com"
    "creation date": "1469103218"
    "info": {
        "length": "1513308160"
        "name": "ubuntu-16.04.1-desktop-amd64.iso"
        "piece length": "524288"
        "pieces": bytes [
            92 90 ed e1 86 46 26 1c 7f 40 02 6f 60 e1 17 1f a8 4b 3b ce 81 d2 c2 30
            13 d5 9c d3 b7 14 d9 d8 4e e3 21 d8 04 44 be 97 db ce c0 87 b3 d0 26 22
            c0 e1 80 d6 ec 83 75 40 86 6b 8d 88 9b bf ea db ad 49 d8 54 e4 69 ba b6
            bc ca dd ed b0 02 5c 74 22 1b bf 00 97 89 b1 b3 fa f8 21 45 5e ff 0c 65
            8f c3 00 a8 23 cd bd be 5d e5 5e 7e 2f 32 66 e3 0c 68 b3 09 de d3 1d 12
            c7 32 6b 92 2e ce 3d 67 79 dc e0 5c 53 f2 a3 a8 84 55 b8 38 c4 26 2d ac
            ... (57596 more bytes)
        ]
    }
}

Notice how the info: { ... } structure describes all the contents of the torrent – file names, sizes, the hash of every 'piece', and sometimes things like the "private torrent" bit. If your edits change this part in any way, this will result in the infohash changing, and you won't be able to download it from old peers.
But if you change something outside the info dict, however, there shouldn't be any problems at all – provided, of course, that the edits actually make sense. For example, you can freely change the trackers listed in announce-list, edit the comment, and maybe even add additional fields.
That said, instead of blindly hex-editing the raw file, why not use a program that actually understands the structure – e.g. an actual "torrent editor"? Those definitely exist.
And finally, if your edits result in the file no longer having valid bencode syntax, that will definitely "create issues", as in programs won't be able to load the .torrent file anymore. This includes, for example, making a piece of text longer or shorter. (In the raw format that your hex-editor shows, notice how each string is prefixed by its length, e.g. 5:hello. They must always match.)


text:
Q: How to write a python script that can communicate with the input and output of a swift executable? So, I have a simple swift program, a one file, main.swift program, that looks like this.
import Foundation

var past = [String]()

while true {
    let input = readLine()!
    if input == "close" {
        break
    }
    else {
        past.append(input)
        print(past)
    }
}

I want to write a python script that can send an input string to this program, and then return the output of that, and have it be run over time. I can't use command line arguments as I need to keep the swift executable running over time.
I have tried os.system() and subprocess.call() but it always gets stuck because neither of them give input to the swift program, but they do start the executable. My shell gets stuck basically waiting for my input, without getting input from my python program.
This is my last python script i attempted:
import subprocess

subprocess.call("./Recommender", shell=True)
f = subprocess.call("foo", shell=True)
subprocess.call("close", shell=True)

print(f)

any ideas on how to do this correctly?
EDIT:
So now I have this solution
import subprocess
print(True)
channel = subprocess.Popen("./Recommender", shell = False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(True)
channel.stdin.write(("foo").encode())
channel.stdin.flush()
print(True)
f = channel.stdout.readline()

channel.terminate()
print(f)
print(True)

However, it stops at reading the line from stdout any ideas how to fix this?

A: I think the following code is what you're looking for. It uses a pipe so you can programmically send data without using command line arguments.
process = subprocess.Popen("./Recommender", shell=True, stdin=subprocess.PIPE)
process.stdin.write(('close').encode())
process.stdin.flush()


text:
Q: Lenovo thinkpad thunderbolt 3 dock gen 2 drops connected devices on Ubuntu Linux I am using a Dell XPS 9570 laptop with dual boot Windows 10/Ubuntu 18.04 with lenovo thinkpad thunderbolt dock gen 2. The dock works fine on Windows. But on Ubuntu, it works for 5-10 minutes but then drops my connected devices like mouse, keyboard. The external monitor still works if I use the laptop keyboard or touchpad. I need to unplug and replug the thunderbolt cable for it to work, but it again drops the connections and its the same problem all over. How do I fix that?
I successfully updated the firmware/drivers for dock on Windows but that didn't help.

*

*Dock firmware version: V1.0.6.06161

*Dock driver version: V1.0.6.01201

*Windows 10 OS: Works fine

*Ubuntu 18.04: External input devices disconnects after sometime

A: I've seen the hub_ext_port_status failed (err = -110) message with Asus notebooks connected to docking ports in the past. A remarkable amount of effort, trial, and error later, the issue turned out to be a conflict between the USB 2.0 and 3.0 drivers — the ehci_pci kernel module, specifically.
To resolve the issue you can block the module but, be warned, this will affect how your machine uses USB2.0 devices. If your devices are mostly 3.0, which uses the xhci_pci kernel module, then you should have no serious issues.
So long as you're good with this, follow these steps to test whether this is the issue or not:

*

*Open Terminal (if it's not already open)

*Remove the ehci_pci kernel module:
rmmod ehci_pci

*Test your dock

If everything works well, then you can make this a permanent fix by adding the module to your modprobe.blacklist:

*

*Open Terminal (if it's not already open)

*Edit /blacklist.conf as root:
sudo vi /etc/modprobe.d/blacklist.conf

*Add the following line:
modprobe.blacklist=ehci_pci

*Save the file

*Reboot

*Check the module is not loaded with:
sudo lsmod

So long as your Dell is having the same issue I saw with Asus notebooks, this should be all you need.


text:
Q: C adding one char to buffer I would like to ask how to add one char to a buffer. For example:
char buffer[50];
char one_symbol;

How to add one_symbol to buffer? I don't know how long the buffer is at the time, so I cant just write, for example buffer[5] = one_symbol;
Thanks.

A: Keep track or the buffers current size. You can do it by adding a new variable for that.
Something like:
char buffer[50];
size_t current_size = 0;  /* Buffer is of size zero from the size */

/* ... */

/* Add one character to the buffer */
buffer[current_size++] = 'a';

A: You need to do something to keep track of the length of the data in the buffer.
You have a couple of choices about how to do that. Strings store data in the buffer (a NUL byte) to signal where there data ends. Another possibility is to store the length externally:
typedef struct {
    char data[50];
    size_t len;
} buffer;

This latter is particularly preferable when/if you want to allow for data that itself might include NUL bytes. If you don't want your buffer size fixed at 50, you can go a step further:
typedef struct {
    size_t allocated;
    size_t in_use;
    char data[];
};

Note that this uses a flexible array member, which was added in C99, so some older compilers don't support it.


text:
Q: Swift 2 - replacement for the deprecated function extend (Swiftache) I have Swiftache in my Swift 2 project, and after the Xcode 7 update, the following line is complaining (the error is there is no longer an extend method).
public func renderText(text: String) {
        if !renderable {
            return
        }

        _text.extend(text)
    }

So _text.extend(text) is the offending line. What could I replace it with?
What did the extend method even do, originally? I can't find an equivalent because I'm not familiar with the original method back when it worked in the older version of Xcode.
Thanks!


text:
Q: VSTS extension - Create and run build definition I'm developing VSTS plugin in Javascript. As part of it, I need to build and run a task on any agent.
The flow is: Run build -> Wait the build to finish -> Click on a button -> Another different task is built and run.
I found a build REST client that create build definitions and queue builds.
I didn't find any examples nor any detailed documentation. Does anyone have a simple example that creates and runs a new build definition using that build REST client?

A: There's already such extensions to queue/trigger build tasks in Marketplace.
You can refer to below link to get the extensions:

*

*Queue Build(s) Task

*Trigger Build Task
If you want to develop your own extension, then you can reference the source code of the extension Trigger Build Task on GitHub


text:
Q: Create drop down list which will show the first item from the drop down menu when it is generated Using Google App Script I am trying to create a drop down list in google sheet using google app script.
Sheet Link: https://docs.google.com/spreadsheets/d/1TESZNYgSJC-ye8r9CcW57-Vt1yU5VcvELiJw4oRwAZQ/edit#gid=0
In this sheet, in column B there is responsible person. Whenever I will select any name from the drop down list of this column, the another drop down list will create in column C and in column D the current date will appear. For example, If I select 'Anushka' in cell B2, a drop down list 'New', 'on going', 'done', 'on hold' will create in cell C2 with the first value from the list of the drop down and a current date will appear in cell D2.
Till now, I can create the drop down menu in cell C2 and also  current date in cell D2 based one cell B2. But I don't know how to show always the first item from the drop down list in cell C2. Now it's giving me blank cell and I need to select something from the menu but I want in a way that when drop down menu will create, it will show the first item not empty cell.
I have attached the code also.
Can anyone please help me where I should modify?
  var sheet = event.source.getActiveSheet();
  var colrange=sheet.getRange("B2:B").isBlank()
  var actRng = event.source.getActiveRange();
  var index = actRng.getRowIndex();
  var cindex = actRng.getColumnIndex();

   if(colrange){
    sheet.getRange(index,4).clearContent()
    sheet.getRange(index,3).clearDataValidations()
   } else{
    var date = Utilities.formatDate(new Date(),"EST", "MMMM-dd-yyyy");
    var list=["New", "Ongoing", "Done", "On-Hold"]

    var rule=SpreadsheetApp.newDataValidation().requireValueInList(list).build()
    sheet.getRange(index,3).setDataValidation(rule)
    sheet.getRange(index,4).setValue(date)
   }

A: Custom Validations
function onEdit(e) {
  e.source.toast("Entry");
  const sh = e.range.getSheet();
  if(sh.getName() == "Sheet0" && e.range.columnStart == 2 && e.value) {
    e.source.toast("Flag1");
    let rg = e.source.getRangeByName("Status");
    e.range.offset(0,1).setDataValidation(SpreadsheetApp.newDataValidation().requireValueInRange(rg));
    e.range.offset(0,2).setValue(new Date());
    Logger.log(e.source.getRangeByName("Status").getValues()[0][0])
    e.range.offset(0,1).setValue(e.source.getRangeByName("Status").getValues()[0][0]);
  }
}

Demo:

Named Ranges:

In answer to your comment below:
function onEdit(e) {
  //e.source.toast("Entry");
  const sh = e.range.getSheet();
  if(sh.getName() == "Sheet0" && e.range.columnStart == 2 && e.value) {
    //e.source.toast("Flag1");
    let rg = e.source.getRangeByName("Status");
    e.range.offset(0,1).setDataValidation(SpreadsheetApp.newDataValidation().requireValueInRange(rg));
    e.range.offset(0,2).setValue(new Date());
    //Logger.log(e.source.getRangeByName("Status").getValues()[0][0])
    e.range.offset(0,1).setValue(e.source.getRangeByName("Status").getValues()[0][0]);
  }
  if(sh.getName() == "Sheet0" && e.range.columnStart == 2 && !e.value) {
    //e.source.toast("Flag2");
    let rg = e.source.getRangeByName("Status");
    e.range.offset(0,1).clearDataValidations();
    e.range.offset(0,2).setValue('');
  }
}


text:
Q: transform count table into disaggregated table of observations I have data in the form of a count table of successes and trials, but for modeling I need these data in a disaggregated trial-level table.
How do I get from this:
dplyr::tibble(
    user_id = c(1,2),
    success = c(3,4),
    trials = c(9, 10)
)

To this:
dplyr::tibble(
    user_id = c(rep(1, 9), rep(2, 10)),
    success = c(rep(1, 3),rep(0, 6), rep(1, 4), rep(0, 6))
)

A: We can uncount based on the 'trials', then grouped by 'user_id', change the 'success' to binary by creating a logical condition with row_number
library(dplyr)
library(tidyr)
df1 %>%
    uncount(trials) %>%
    group_by(user_id) %>%
    mutate(success =  +(row_number() <= first(success))) %>%
    ungroup
# A tibble: 19 x 2
#   user_id success
#     <dbl>   <int>
# 1       1       1
# 2       1       1
# 3       1       1
# 4       1       0
# 5       1       0
# 6       1       0
# 7       1       0
# 8       1       0
# 9       1       0
#10       2       1
#11       2       1
#12       2       1
#13       2       1
#14       2       0
#15       2       0
#16       2       0
#17       2       0
#18       2       0
#19       2       0

Or with base R using Map and stack
stack(setNames(Map(function(x, y) rep(1:0, c(x, y)),
     df1$success, df1$trials - df1$success), df1$user_id))[2:1]


text:
Q: Cannot access website I have two ISP. The other one is hosting my website which is pcc.edu.ph. But when I try to access it from the other IP, it does not load the page it just says The connection was reset. But when I tried it from other IPs its loading ok. What could be the problem? Could it be a DNS or server problem? Im hosting it in ubuntu 12.04. I really need help!! Thanks in advance!

A: A "connection reset" error is a problem between the client and the webserver - it's the webserver sending the "connection reset", which means all of the DNS lookups have already occurred (successfully) before you even get to this stage.
If it was a DNS problem, you would be getting a "Server not found error", not connection reset. So whatever it is, it's on the server.
If there is nothing in the webserver config regarding these IPs, could there be some kind of iptables rule for the IPs the affected ISP is using? (iptables -L -n)


text:
Q: How to backup laptop SSD with UEFI I have an Acer Aspire R laptop with 260GB SSD, UEFI, Ubuntu and Windows 10 dual boot. How can I backup / clone / image the whole drive to be reinstalled on a new drive if current drive fails?

*

*Clonezillla: Will it backup all partitions (EFI, recovery, Ubuntu, swap, Windows) to external drive, so I can restore it to a new drive, no problem? Which file system should the external drive have?

*GParted: Or should I partition the external drive like the existing drive and copy the partitions with gparted?

A: You can use Clonezilla to make a bootable copy of the whole existing SSD with all of its partitions including Windows.
The boot menu comes from Grub2 and it gets created from templates in /etc/grub.d and settings from /etc/default/grub.
So, if your Clonezilla ISO file lives at /srv/iso/clonezilla-live-disco-amd64.iso and /srv directory lives in hard drive 0 in partition 13, then create a new executable file in /etc/grub.d, such as 40_clonezilla and put the following in it:
#!/bin/sh
exec tail -n +3 $0
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
menuentry "Clonezilla live" {
set root=(hd0,13)
set isofile="/iso/clonezilla-live-disco-amd64.iso"
loopback loop $isofile
linux (loop)/live/vmlinuz boot=live union=overlay username=user config components quiet noswap nolocales edd=on nomodeset ocs_live_run=\"ocs-live-general\" ocs_live_extra_param=\"\" keyboard-layouts= ocs_live_batch=\"no\" locales= vga=788 ip=frommedia nosplash toram=live,syslinux,EFI findiso=$isofile
initrd (loop)/live/initrd.img
}

Then, run update-grub to regenerate your grub menu.
When you reboot, you will have a new boot option that boots from Clonezilla, and, from there, you can make a bootable copy of the existing hard-drive onto an external drive and overwrite whatever is already on that external drive.
All of this stuff, editing Grub templates and overwriting drives is quite dangerous and the penalty for getting something wrong is high.


text:
Q: Adding If/End If to macro I'm trying to add a condition to a copy and paste macro where it copies a row from table1 and pastes it onto table2 if the row in table1 is red.
I've tried:
Sub ColdLake1()

If Range("B55").Interior.ColorIndex = 3 Then

    Range("B55:H55").Select
    Selection.Copy
    Range("C140").Select
    Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
        , SkipBlanks:=False, Transpose:=False
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        End If
End Sub

It returns nothing. Any ideas?
Thanks (I'm quite new to all this).

A: This worked for me:
Sub ColdLake1()
    With ActiveSheet
        Debug.Print "ColorIndex", .Range("B55").Interior.ColorIndex
        If .Range("B55").Interior.ColorIndex = 3 Then
            .Range("B55:H55").Copy
            With .Range("C140")
                .PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, _
                    SkipBlanks:=False, Transpose:=False
                .PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
                    SkipBlanks:=False, Transpose:=False
            End With
        End If
    End With
End Sub

If your code isn't doing anything it may be because the color isn't what you think it is, or for some reason your code is not entering the If block.  Put some breakpoints and see what is going on.  https://www.excel-easy.com/vba/examples/debugging.html


text:
Q: Unity: use UWP project in unity windows standalone application I am making a windows standalone application using unity.
I want to record video from PC webcam and save it locally. The only solution that I found is a UWP project that records video and saves it to PC.
I want to know if there is a way to use this UWP solution in my windows standalone application.
For C# projects (not UWP), I build it to dll and use it as dll in my application.
I need to find a way to do just like this with UWP project.
Edit 1:
I tried Unity VideoCapture Example in both editor and build. In unity editor, the application runs without errors but it didn't enter to this function "VideoCapture.CreateAsync()", as they said it didn't work with the editor.
When I tried to build to windows standalone build, it gives me this error :
"Assets/Scripts/Controllers/Other/VideoCaptureExample.cs(4,26): error CS0234: The type or namespace name 'WebCam' does not exist in the namespace 'UnityEngine.XR.WSA'. Are you missing an assembly reference?"

A: If you are using the HoloToolkit / MRTK, you had best delete that folder and use the newer asset, or better yet, use the Master Branch which has more fixes in it.
Or you can try update your Unity to 2017.2 and the sample works when testing on my machine.


text:
Q: How to attach an event to the Residential Delivery checkbox on the Customers screen in 2020R2? I need to change the default value of the Residential Delivery checkbox on the Customers AR.30.30.00 screen (Shipping tab) to checked by default. See screenshot:

In 2017R2, this event handler worked without error:
public class CustomerMaint_Extension : PXGraphExtension<CustomerMaint>
{
    protected virtual void LocationExtAddress_CResedential_FieldDefaulting(PXCache sender, PXFieldDefaultingEventArgs e)
    {
        var row = (LocationExtAddress)e.Row;
        if (row != null)
        {
            e.NewValue = true; // checked by default
        }
    }
}

I'm updating this customization for 2020R2. It appears that LocationExtAddress has been replaced with DefLocationExt in newer versions. (Resedential is mis-spelled intentionally in the code... that's how Acumatica defined it.) I've tried changing the event handler to:
protected virtual void DefLocationExt_CResedential_FieldDefaulting(PXCache sender, PXFieldDefaultingEventArgs e)
{
    var row = (DefLocationExt)e.Row;
    if (row != null)
    {
        e.NewValue = true; // checked by default
    }
}

But this results in a run-time error:

Failed to subscribe the event PX.Objects.AR.CustomerMaint_Extension::DefLocationExt_CResedential_FieldDefaulting in the graph PX.Objects.AR.CustomerMaint. The method signature looks like an event handler, but the cache DefLocationExt has not been found in the list of auto-initialized caches. Remove unused event handlers from the code.

How can I attach an event to this field in 2020R2?

A: Try a generic event handler and see if you get the same result.
It might look something like this.
protected virtual void _(Events.FieldDefaulting<PX.Objects.CR.Standalone.Location.cResedential> e)
    {
        var row = (PX.Objects.CR.Standalone.Location)e.Row;
        if (row != null)
        {
            e.NewValue = true; // checked by default
        }
    }


text:
Q: sending data to javascript worker I have an JS worker like this:

    function ler_valores()
    {
        self.addEventListener('message', function (e) {
            var data = e.data;
            //verifica se existem dados e se não existe mais do que um destinatário
            if ( data.lista.indexOf(",") == -1 )
            {
                var dados = new FormData();
                dados.append( 'tipo', 'refresca_painel_mensagens' );
                dados.append( 'txtDe', data.lista );
                var xhttp=new XMLHttpRequest();
                xhttp.open( 'POST', "../ajax/mensagens.php", false );
                xhttp.onload=function()
                {
                    postMessage( xhttp.responseText );
                }
                xhttp.send( dados);
                setTimeout( ler_valores,2000 );
            }
            else
            {
                postMessage('');
                setTimeout( ler_valores,2000 );
            }
        });

    }
    ler_valores();

and I call it on main php

function ativar_worker1 ( lista_destinatarios )
{
    var coisas = JSON.parse( '{"lista":"' + lista_destinatarios + '"}' );

    var worker = new Worker( '../worker/worker1_mensagens.js' );
    worker.postMessage( coisas );
    setTimeout(function() worker.postMessage( coisas );,2000);
    worker.onmessage = function( event )
    {
        $('ul.list-unstyled').append(event.data );
        console.log(event.data);
    };
}

With both ways, seting timeout I cant get a refresh data on ul.list-unstyled
How can I pass every 2 seconds the var coisas (things in english) to thw worker?
Many thanks!


text:
Q: What is a class monitor in D? D2.0 classes have a __monitor class property that "gives access to the class object's monitor" (documentation). I searched around a bit and did not find any information except for this bit of detail. So: what is a monitor? Why is one monitor used for all synchronized member functions? Is it a  synchronization primitive used for synchronizing member functions similar to Java? And why is the __monitor property in the language def if you are not supposed to use it / what are the use-cases?

A: The monitor is a lazily initialized object that all synchronized methods synchronize on, just like in Java.  Unlike Java, D is a systems programming language and exposes lower level details of how things work just in case you need to hack them, even if doing so is usually a bad idea.  This allows you to customize behavior.  For example, it is possible to customize the monitor object of a class, or to use a core.sync.mutex that shares a monitor with the class that owns it.


text:
Q: Is there any difference between giving GL15.glBufferData() a float array or a FloatBuffer in LWJGL 3.0? I was recently watching a tutorial on writing an OpenGL game in Java with LWJGL. In it, the narrator/author first converts the float array from float[] to a FloatBuffer before giving it toGL15.glBufferData(). Initially I didn't think much of this, but I accidentally gave GL15.glBufferData() the float array directly instead of converting it to a FloatBuffer, and the code ended up working anyway. I looked up the documentation and it only says "Array version of: BufferData" as comment, which still leaves me uncertain.
This leads me to wonder, is there any point of going through the effort to convert float[] to a FloatBuffer when calling GL15.glBufferData() in LWJGL 3.0 with Java 15, assuming the FloatBuffer was given its value by using FloatBuffer::put() and thus contains the same data?

A: The difference between a direct NIO Buffer and a float array is that when you hand a float array to LWJGL, it will first need to pin the array using a JNI call into the Java runtime, which will give LWJGL's native code a virtual memory address it can hand over to the actual called native function. Then, the float array needs to be unpinned again, making it eligible again for garbage collection.
With a direct NIO Buffer, this does not need to happen, because direct NIO Buffers are already backed by a native virtual memory address. So using direct NIO Buffers is considerably faster (performance-wise). Of course, all this performance is somewhat lost when you first create a float array and then copy it into the NIO Buffer.
You are expected to simply not use a float array to being with, but only ever populate your direct NIO Buffer.

A: I would recommend using a float[] instead of a FloatBuffer because a float[] seems to work more, and it's exactly what you expect: an array of bytes on the stack. Also, behind the scenes, a FloatBuffer is really just a float[] so it doesnt matter TOO much at the end of the day. To continue off my point, converting a float[] to a FloatBuffer seems unnecessary and overly complicated.


text:
Q: How to interpret Monte Carlo samples of the ratio of two variables? My aim is to find the 95% confidence interval of the ratio of two variables for which I have summary statistics. More specifically, I have the prevalence of mothers drinking during their pregnancy (assumed to follow a normal distribution) and I have the prevalence of children born with foetal alcohol syndrome (FAS, supposed to follow a binomial distribution for which I know all parameters).
By dividing the former by the latter I obtain the number of pregnant women that drink per 1 birth with FAS.
I thought the easiest way would be to sample both distributions N times, therefore generate N samples of this ratio and the 2.5% and 97.5% quantiles should give me the right CIs. The mean of this ratio is very far from the ratio of the means of the initial distribution though. This is a known thing and arises from Jensen's inequality (I assume this comes simply from the nonlinearity of the function f(x)=1/x).
How do I interpret my Monte Carlo samples? Are they representative of the error?
The literature now proposes to use Taylor series approximations to estimate the variance of the ratio mean of 2 normally distributed variables. This would generate a variance around the ratio of the means and make it all nice and symmetrical. Given that these approaches will not give the same results at all, one giving you symmetric CIs, the other one giving you asymmetric results, which one is correct?

A: Here is an analytic solution:
Let $$\bar{x} \sim N(\mu, \sigma^2 / n_1)$$ and $$y \sim Binomial(n_2, \pi)$$ and assume that $\bar{x}$ and $y$ are independent. Let $p = y/n_2$, whose large-sample distribution is $N\left(\pi, \frac{\pi(1-\pi)}{n_2}\right)$. You want a 95% CI for $\mu / \pi$. Then based on the delta method, we can show that $log(\bar{x} / p)$ has a large-sample distribution that is normal with expected value $log(\mu / \pi)$ and variance $\frac{\sigma^2}{n_1 \mu^2} + \frac{(1-\pi)}{n_2 \pi}$. The variance can be estimated by substituting the sample estimates, so let $$Var[log(\bar{x} / p)] = \frac{s^2}{n_1 \bar{x}^2} + \frac{(1-p)}{n_2 p}.$$ Now compute an approximate 95% CI for $log(\mu / \pi)$ with $$log(\bar{x} / p) \pm 1.96 \sqrt{Var[log(\bar{x} / p)]}$$ and then exponentiate the bounds to obtain an approximate 95% CI for $\mu / \pi$.
How well this works in your case depends on how large $n_1$ and $n_2$ are, that is, whether you can actually appeal to the large-sample behavior of the distribution of $log(\bar{x} / p)$.


text:
Q: A problem on verification of a topological space and its convergent sequences Show that $(X,T)$  is a topological space where $X=\mathbb{R}$ and $T$ consists of all the sets of the form $A\cup B$ where $A$ is an open subset of $\mathbb{R}$ and $B$ is a subset of irrational numbers.
Show that no sequence can converge to an irrational number except an eventually constant sequence.

I have no clue how to solve this problem.please help.

A: HINT: Show that if $x$ is irrational, then $\{x\}\in T$. Thus, if $\langle x_n:n\in\Bbb N\rangle$ converges to $x$, there must be an $m\in\Bbb N$ such that $x_n\in\text{what?}$ for all $n\ge m$.


text:
Q: SQL Server Management Studio server roles I dont know if im doing something completely wrong or im just missing the point of SQL Server security.
Here's what I'm trying to do using SSMS, a simple two-level access (network\DomainUsers, network\SQLAdmins).

*

*Domain users would not be unable to view any tables within SSMS but can access data via applications.

*SQLAdmins see all

To start with I thought I had it cracked by setting up a new server role for domain users and assigning view and database/definition permisions then removing these from the public role - no joy!
Staying with the same settings I then branches down to the table to grant permissions but again no joy.
I've setup several roles / users and applied all forms of permissions but as soon as database/definition is altered in public it overrides everything. I thought public was a default setting which then became redundant when other roles became active?
Can someone please point me in the correct direction before either my head pops or the machine learns to fly :-)

*

*SSMS: v17.8.1

*SQL Server: 2012

A: Depending on how you actually defined your roles (which isn't clear from your question) it can simply be that you DENY view any database on the public role. This will in turn make it so everyone is denied. Because everyone is always a part of the public role. (This is why messing with the public role is a bad idea).
Deny's trump Grants. So no matter what you grant them later on, the deny overrides it. So if you denied it at the top level, it will stay like that no matter what you specify later on.
The exception to this is, that you can always see the objects that you own. And members of the sysadmin server role can't be denied since they always jump in as the owner. So you can technically hide all databases by revoking view permissions on the public database. But then you need to make a shared login and assign ownership to the databases that you want to be viewable.
Of note is that in this case, it means they can do whatever they want in said databases. Since you can't 'deny' them rights in something they own (which is why they can view it in the first place).
In overall, you're better off finetuning roles on the DB level, or making some custom server roles depending on what you want to accomplish.
Note, unless you messed with the public role. Logins with no user mapping in a database can't see the tables within a database, they can only see the existance of the database itself.


text:
Q: Iterating through one variable in a vector of struct with lower/upper bound I have 2 structs, one simply has 2 values:
struct combo {
int output;
int input;
};

And another that sorts the input element based on the index of the output element:
struct organize {
bool operator()(combo const &a, combo const &b)
  {
    return a.input < b.input;
  }
};

Using this:
sort(myVector.begin(), myVector.end(), organize());

What I'm trying to do with this, is iterate through the input varlable, and check if each element is equal to another input 'in'.
If it is equal, I want to insert the value at the same index it was found to be equal at for input, but from output into another temp vector.
I originally went with a more simple solution (when I wasn't using a structs and simply had 2 vectors, one input and one output) and had this in a function called copy:
for(int i = 0; i < input.size(); ++i){

   if(input == in){

       temp.push_back(output[i]);

   }
}

Now this code did work exactly how I needed it, the only issue is it is simply too slow. It can handle 10 integer inputs, or 100 inputs but around 1000 it begins to slow down taking an extra 5 seconds or so, then at 10,000 it takes minutes, and you can forget about 100,000 or 1,000,000+ inputs.
So, I asked how to speed it up on here (just the function iterator) and somebody suggested sorting the input vector which I did, implemented their suggestion of using upper/lower bound, changing my iterator to this:
std::vector<int>::iterator it = input.begin();
auto lowerIt = std::lower_bound(input.begin(), input.end(), in);
auto upperIt = std::upper_bound(input.begin(), input.end(), in);

 for (auto it = lowerIt; it != upperIt; ++it)
 {
     temp.push_back(output[it - input.begin()]);
 }

And it worked, it made it much faster, I still would like it to be able to handle 1,000,000+ inputs in seconds but I'm not sure how to do that yet.
I then realized that I can't have the input vector sorted, what if the inputs are something like:
input.push_back(10);
input.push_back(-1);

output.push_back(1);
output.push_back(2);

Well then we have 10 in input corresponding to 1 in output, and -1 corresponding to 2. Obviously 10 doesn't come before -1 so sorting it smallest to largest doesn't really work here.
So I found a way to sort the input based on the output. So no matter how you organize input, the indexes match each other based on what order they were added.
My issue is, I have no clue how to iterate through just input with the same upper/lower bound iterator above. I can't seem to call upon just the input variable of myVector, I've tried something like:
std::vector<combo>::iterator it = myVector.input.begin();

But I get an error saying there is no member 'input'.
How can I iterate through just input so I can apply the upper/lower bound iterator to this new way with the structs?
Also I explained everything so everyone could get the best idea of what I have and what I'm trying to do, also maybe somebody could point me in a completely different direction that is fast enough to handle those millions of inputs. Keep in mind I'd prefer to stick with vectors because not doing so would involve me changing 2 other files to work with things that aren't vectors or lists.
Thank you!

A: I think that if you sort it in smallest to largest (x is an integer after all)  that you should be able to use std::adjacent_find to find duplicates in the array, and process them properly.   For the performance issues, you might consider using reserve to preallocate space for your large vector, so that your push back operations don't have to reallocate memory as often.


text:
Q: match 2 column elements based on a differece within a range I want to match the elements of two unequal columns from two different data frames if they fall within the range: 1 to 3 (2+/-1)
My data frames:
dat1:
Number  status
10023   T
10324   F
12277   F
12888   T
12000   T

dat2:
Number  status
10020   T
10002   F
12279   F
12888   T

Required ouput:
10023   10020   T
12277   12279   F

My attempt (below) did not work:
diff <- 2
allow <- 1

NewData <- dat1$Number %in% (dat2$Number<=diff+allow | dat2$Number>=diff+allow)

Help will be appreciated.

A: This looks like a must case for data.table::foverlaps to me.
The workflow is to create start and end columns within both data sets, while we will create the range within the second data set. Then, we will key both and simply run foverlaps
library(data.table)
diff <- 2
allow <- 1
setDT(dat1)[, `:=`(start = Number, end = Number)]
setkey(dat1, status, start, end)
setDT(dat2)[, `:=`(start = Number - (diff + allow), end = Number + diff + allow)]
setkey(dat2, status, start, end)
foverlaps(dat2, dat1, nomatch = 0L)[, .(Numdf1 = Number, Numdf2 = i.Number, status)]

#    Numdf1 Numdf2 status
# 1:  12277  12279  FALSE
# 2:  10023  10020   TRUE
# 3:  12888  12888   TRUE ### <- I'm assuming you had an error in the desirred output


text:
Q: The part of the view after an `extend` statement is not rendered I'm trying to use the extend keyword to add a comment-box (a view placed under default/comment_box.html) across several of my views, by:
...

{{extend "default/comment_box.html"}}

...

But, when this executes, all the part of the view after the extend statement is not being rendered and all I'm getting is:
...

As you can see, the part after the extend statement, i.e.  has gone missing. The Web2Py examples seem to be doing it the same way. Am I missing something here? Why is it truncating abruptly after the extend statement?

A: I think you want:
{{include 'default/comment_box.html'}}

If you use {{extend 'default/comment_box.html'}}, the comment_box.html view must contain an {{include}} directive somewhere, in which case, the content of the extending view gets included in place of that {{include}} directive. On the other hand, if you simply want to include the contents of comment_box.html within your view, you need to use {{include 'default/comment_box.html'}}.
See here for more on extend and include.


text:
Q: File upload using HTML file type I want to upload a file on my aspx page.
I am using
<form id="frmId" method="post" enctype="Multipart/form-data">
<input type="file" id="file1"/>
<input type="submit" id="btnsubmit"/>
</form>

and in code behind I am trying to get this file. Its not letting me to get the file until I use server side input file control. I don't want to use runat="server" attribute with my file control.
Do anyone know how to do this.

A: Have you tried the Request.Files collection?

A: You can not access control on server side code with out runat="server" attribute.


text:
Q: Is the matrix $A − 2I$ invertible?
Let $A$ be a $4 \times 4$ matrix with eigenvalues $1, 2, 3,$ and $4$. Is matrix $A − 2I_4$ invertible?

I tried to tackle this by constructing a matrix with eigenvalues $1, 2, 3,$ and $4$:
$$
\begin{bmatrix}
1 & 0 & 0 & 0\\
0 & 2 & 0 & 0\\
0 & 0 & 3 & 0 \\
0 & 0 & 0 & 4 \\
\end{bmatrix}
\quad
$$
Now,
$$A − 2I_4 =
\begin{bmatrix}
-1 & 0 & 0 & 0\\
0 & 0 & 0 & 0\\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 2 \\
\end{bmatrix}$$
Since the determinant of this matrix is $0$, it is not invertible. But this is a very specific case. How can I generalize it to all $4 \times 4$ matrices with eigenvalues $1, 2, 3,$ and $4$?
Any help is greatly appreciated!

A: A scalar $\lambda$ is an eigenvalue of the $n\times n$ matrix $A$ if and only if there exists a nonzero vector $\mathbf{v}$ such that $A\mathbf{v}=\lambda\mathbf{v}$. That means that $(A-\lambda I_n)\mathbf{v}= A\mathbf{v}-\lambda\mathbf{v}=\mathbf{0}$.
That, in turn, means that the matrix $A-\lambda I_n$ has nontrivial nullspace.
So $\lambda$ is an eigenvalue of $A$ if and only if $A-\lambda I_n$ has nontrivial nullspace.
What do you know about the connection between the nullspace of a matrix and its invertibility?


text:
Q: How to extract values from a Python request I am using a Python request to search for a specific item.
page = requests.get('https://utas.s2.fut.ea.com/ut/game/fifa16/transfermarket?maxb=900&start=0&type=player&maskedDefId=177604&num=16', headers=headers, cookies=cookies)
print page.json

The code above outputs in json (see below) which I would like to extract just the the tradeId and print it to my terminal.
{u'sellerEstablished': 0, u'itemData': {u'rating': 80, u'itemType': u'player', u'resourceId': -2147306044, u'cardsubtypeid': 1, u'morale': 50, u'lifetimeAssists': 0, u'id': 242123805234, u'statsList': [{u'index': 0, u'value': 45}, {u'index': 1, u'value': 0}, {u'index': 2, u'value': 0}, {u'index': 3, u'value': 1}, {u'index': 4, u'value': 0}], u'assetId': 177604, u'teamid': 1, u'pile': 5, u'suspension': 0, u'rareflag': 1, u'playStyle': 250, u'attributeList': [{u'index': 0, u'value': 77}, {u'index': 1, u'value': 53}, {u'index': 2, u'value': 72}, {u'index': 3, u'value': 75}, {u'index': 4, u'value': 81}, {u'index': 5, u'value': 72}], u'loyaltyBonus': 1, u'timestamp': 1443853245, u'training': 0, u'nation': 45, u'assists': 0, u'formation': u'f442', u'lifetimeStats': [{u'index': 0, u'value': 45}, {u'index': 1, u'value': 0}, {u'index': 2, u'value': 0}, {u'index': 3, u'value': 1}, {u'index': 4, u'value': 1}], u'leagueId': 13, u'untradeable': False, u'discardValue': 640, u'owners': 2, u'injuryGames': 0, u'contract': 3, u'injuryType': u'none', u'lastSalePrice': 1500, u'fitness': 99, u'itemState': u'forSale', u'preferredPosition': u'LB'}, u'tradeId': 159804881070, u'confidenceValue': 100, u'sellerName': u'FIFA UT', u'expires': 1745, u'buyNowPrice': 900, u'tradeOwner': False, u'offers': 0, u'startingBid': 650, u'watched': None, u'currentBid': 700, u'tradeState': u'active', u'bidState': u'none', u'sellerId': 0}

A: Use it as a dictionary.
a = page.json()
print a['tradeId']


text:
Q: T-SQL While Infinite Loop The goal of the below script is to delete all records in a table for all the distinct users on it except the two first records for each user.
The thing is that the script goes into an infinite loop between these two lines
WHILE @@FETCH_STATUS = 0
SET @Event = 0;

The complete script is
DECLARE @Event int, @User int;

DECLARE cUsers CURSOR STATIC LOCAL FOR SELECT DISTINCT(UserID) FROM Identifications;

OPEN cUsers

FETCH NEXT FROM cUsers INTO @User;

WHILE @@FETCH_STATUS = 0
SET @Event = 0;

BEGIN
    DECLARE cRows CURSOR STATIC LOCAL FOR
    SELECT EventIdentificacionId FROM Identifications WHERE UserId = @User AND EventIdentificacionId NOT IN
     (SELECT TOP 2 EventIdentificacionId FROM Identifications WHERE UserId = @User ORDER BY EventIdentificacionId);

    OPEN cRows
    FETCH NEXT FROM cRows INTO @Event;

    WHILE @@FETCH_STATUS = 0
    BEGIN
      DELETE FROM Identifications WHERE EventIdentificacionId = @Event;
      FETCH NEXT FROM cRows INTO @Event;
    END

    CLOSE cRows;
    DEALLOCATE cRows;

    FETCH NEXT FROM cUsers INTO @User;
END

CLOSE cUsers;
DEALLOCATE cUsers;

Can anybody give me some solution/explanation please?

A: As I wrote in my comment, There are far better ways to do such a thing than using a cursor, let alone a couple of nested cursors.
One such better option is to use a common table expression and row_number, and then delete the rows directly from the common table expression.
I'm not entirely sure this code is correct because I have no real way to test it as you didn't provide sample data or desired results, but I came up with that based on the code in the question:
;WITH CTE AS
(
    SELECT  UserId,
            EventIdentificacionId,
            ROW_NUMBER() OVER(PARTITION BY UserId ORDER BY EventIdentificacionId) As Rn
    FROM Identifications
)

DELETE
FROM CTE
WHERE Rn > 2 -- Delete all but the first two rows

A: Change this line as shown:
DECLARE @Event int = 0, @User int = 0;

And remove this line
SET @Event = 0;

The reason you have an infinite loop is that this code:
WHILE @@FETCH_STATUS = 0
SET @Event = 0;
BEGIN

Is actually this:
-- A loop of a single instruction, with no exit criteria
WHILE @@FETCH_STATUS = 0 SET @Event = 0;

-- begin a new code block, with no condition or loop
BEGIN


text:
Q: UITableView reloaddata problem when having a MKMapview in a tableview cell I am writing an app can load data from from web, then put the data in a grouped uitableview, where I put data in the first section, and meantime, I want to plot these data on a mapview in the second section of table.
I managed to implement these in the tableview, and it works fine. Then I add a refresh button on the navigation bar, so if someone press the refresh button, the app will fetch data from web again and reload the tableview with the new data.
Here comes the problem, when I refresh the data and call the method reloaddata, all table cells in both section get refreshed, I mean, the map is re-loaded and animated zoom in from world map to the interest region every time I press the refresh button. But I only want re-plot the annotations based on the refreshed data, not the map.
I think the problem come from the call of
    [self.tableView reloadData]
method. Is there a way just to reload data for the first section rather than all sections in a grouped tableview?
Any suggestion or comment is appreciated! Thanks!

A: You can use - reloadRowsAtIndexPaths:withRowAnimation: (in the UITableView Class Reference) to do just that.  You will just need to create an NSArray of the index path/paths of the row/rows you want to update and it will reload just those


text:
Q: Discriminator Java Jpa Class which extends can be type inherenced class I have one table in a db, and I want to know which type is that instance. I have two entites which are different types. I am having problems.
My first entity is :
@Entity
@Table(name = "lekarfizo")
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("lekar")

And the second:
@Entity
@Table(name = "lekarfizo")
@DiscriminatorValue("fizio")

public class Fizioterapeut extends Lekarfizo

The problem is the first entity can be an instance of the second. The second works fine and second can only be instance second entity. I want to know how I can fix that and to make the difference between these two entities.

A: Use an entity type expression with the TYPE operator
List<Lekarfizo> rm = em.createQuery("select l from Lekarfizo l where type(l) = Lekarfizo", Lekarfizo.class).getResultList();
System.out.println(rm);

Reference: How do I query for only superclass entities in a jpql query?


text:
Q: retrieve parameter from executeQueryAsync, javascript I'm trying to retrieve a parameter from a success method that is called within and executeQueryAsync using Javascript ECMA scripting.
I get tried follwing the suggestion here
http://www.learningsharepoint.com/2013/08/07/passing-parameters-to-success-method-in-executequeryasync-sharepoint/
but I get the following error in the MicrosfotAjax.js file:
"The Collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested." in the alert(_returnParam); command, I get an undefined value when instead it should say "hello". I want to demonstrate a simple variable return before I get the success function to return listItemInfo array.
Thank you for your consideration
function Tblsrch(camlstr){
var siteUrl = '/sites/SIandT%20Project%20Intelligence';
var hello;
var clientContext = new SP.ClientContext(siteUrl);
var oWebsite = clientContext.get_web();
var oList = oWebsite.get_lists().getByTitle('ISATestdata');
var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml(camlstr);

    this.collListItem = oList.getItems(camlQuery);
    var _returnParam;

clientContext.executeQueryAsync(Function.createDelegate(this, function(){_returnParam = onQuerySucceeded();}), Function.createDelegate(this, this.onQueryFailed));

alert(_returnParam);

}

    function onQuerySucceeded(sender, args){
       var listItemInfo = new Array();
       var rowInd = 0;
        var hello;
                    var listItemEnumerator = collListItem.getEnumerator();

            while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
           // listItemInfo += '\nType:' + oListItem.get_item('Name2') + ' | ' + oListItem.get_item('Plan') + ' | ' + oListItem.get_item('Type1');

            listItemInfo[rowInd] = new Array(10);
            listItemInfo[rowInd][0] =oListItem.get_item('Name2');
            listItemInfo[rowInd][1] =oListItem.get_item('Type1');
            listItemInfo[rowInd][2] = oListItem.get_item('Plan');
            listItemInfo[rowInd][3] = oListItem.get_item('Analyse');
            listItemInfo[rowInd][4] = oListItem.get_item('Design');
            listItemInfo[rowInd][5] = oListItem.get_item('Build');
            listItemInfo[rowInd][6] = oListItem.get_item('Test');
            listItemInfo[rowInd][7] = oListItem.get_item('Run');
            listItemInfo[rowInd][8] = oListItem.get_item('SupportMaintenance');
            listItemInfo[rowInd][9] = oListItem.get_item('Link1');
            listItemInfo[rowInd][10] = oListItem.get_item('Link2');

            rowInd++;
        }
        alert(listItemInfo[0][0] + " " + listItemInfo[0][1] + " " +listItemInfo[0][2] + " " + listItemInfo[0][3] + " " +listItemInfo[0][4] + " " );
    var _returnParam = "hello";
return _returnParam;
    }

function onQueryFailed(sender, args){
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

A: clientContext.executeQueryAsync(Function.createDelegate(this, function(){_returnParam = onQuerySucceeded();}), Function.createDelegate(this, this.onQueryFailed));

alert(_returnParam);

It's normal. executeQueryAsync is asynchrone, so executeQueryAsync is called (= an AJAX request is done), and immediately after, without waiting for the AJAX to be completed, you call alert(_returnParam) with _returnParam that is still void.
You need to call another function at the end of onQuerySucceeded if you want another action to be done.
By the way, I always thought that the Microsoft way is really difficult to use. I've created a library to deal with Sharepoint, if you are interested (it's called SharepointPlus). For what you want to achieve, the code would be something like that (I've also review your code with the array):
$SP().list("ISATestdata", "/sites/SIandT%20Project%20Intelligence").get({fields:"Name2,Type1,Plan,Analyse,Design,Build,Test,Run,SupportMaintenance,Link1,Link2",where:"Name2 = 'Something'"}, function(data) {
  var listItemInfo = [];
  for (var i=0, len=data.length; i<len; i++) {
    listItemInfo[i] = [];
    listItemInfo[i].push(data[i].getAttribute("Name2"));
    listItemInfo[i].push(data[i].getAttribute("Type1"));
    listItemInfo[i].push(data[i].getAttribute("Plan"));
    listItemInfo[i].push(data[i].getAttribute("Analyse"));
    listItemInfo[i].push(data[i].getAttribute("Design"));
    listItemInfo[i].push(data[i].getAttribute("Build"));
    listItemInfo[i].push(data[i].getAttribute("Test"));
    listItemInfo[i].push(data[i].getAttribute("Run"));
    listItemInfo[i].push(data[i].getAttribute("SupportMaintenance"));
    listItemInfo[i].push(data[i].getAttribute("Link1"));
    listItemInfo[i].push(data[i].getAttribute("Link2"));
  }

  alert(listItemInfo[0][0] + " " + listItemInfo[0][1] + " " +listItemInfo[0][2] + " " + listItemInfo[0][3] + " " +listItemInfo[0][4] + " " );
})


text:
Q: Use a particular drive if path exists in a batch script I have a batch file that sometimes people run and since batch files don't allow UNC mapping, they need specific drive mappings.
The problem is that some people who run this file will have the server mapped to different letters, specifically M or P.
So what I want to do is make a variable to score the drive so I can concatenate it into other path commands where possible because sometimes they will have:
M:\Path\to\stuff\on\server

or
P:\Path\to\stuff\on\server

So what I want to do is say if M:\Path\to\stuff\on\server" exists then use drive M, if "P:\Path\to\stuff\on\server" exists then use drive P.
Is there a way to do this in batch script?

A: Seeing as you specifically only have M: and P: in this example:
@for %%i in (m: p:) do @if exist %%i cd /d %%i
echo %cd%

It can be extended to more drives. Additionally please note that if the user has both M:\ and P:\ drives, it will cd to both and end up in the last one in the list. Therefore using a known directory is a better solution on the mapping.
@for %%i in (m: p:) do @if exist "%%i\Path\to\stuff\on\server" cd /d "%%I\Path\to\stuff\on\server"
echo %cd%

if you want to set it as a variable to use it anywhere else in the script, then simply assign the drive letter to a variable like so:
@for %%i in (m: p:) do @if exist %%i set "mydrive=%%i\"
echo %mydrive%

Alternatively, without needing to use variables, you can use the already assigned metavariable %%i to use the drive letter as you please:
@for %%i in (m: p:) do @if exist %%i (
    echo my drive letter is %%i
    dir %%i
    cd /d %%i
 )

A: One approach you could utilise is to create a temporary mapping using pushD.
pushd \\Server\Share\path

When you are done with that temporary mapping just use popd to destroy it.
Where \Server\Share\path is the network resource to which you want to map a drive letter.
As soon as you use it, the PushD command will instantly map a drive letter to the network resource and then change to that drive right in the Command Prompt window.
Keep in mind that the PushD command allocates drive letters from Z: on down and will use the first unused drive letter that it finds.


text:
Q: Intersection of a dataframe with a list of columns I need to intersect the dataframe columns with the database columns (defined in a list) before I execute a query.
My current code looks like this:
db_columns_list = ['col1', 'col2', 'col3']
dataframe = dataframe[dataframe.columns & db_columns_list]

This works well, but I am getting the warning:
*FutureWarning: Index.__and__ operating as a set operation is deprecated, in the future this will be a logical operation matching Series.__and__.  Use index.intersection(other) instead
  dataframe = dataframe[dataframe.columns & db_columns_list]*

So I would like to convert it into something like:
dataframe = dataframe[dataframe.columns.intersection(db_columns_list)]

but with that I get the error:
*Unresolved attribute reference 'intersection' for class 'Iterator'*

Please note that the database may contain more columns than the dataframe.
Therefore I believe the intersection is the correct way to approach this.
Thank you

A: intersection function can be applied as below.
Toy example,
db_columns_list = ['col1', 'col2', 'col3']
df=DataFrame({
    'col1':[1,2],
    'col3':[3,4]
})

## Solution
df[set(df.columns).intersection(set(db_columns_list))]

# Improved version with the help of `Mustafa Aydın`
df[df.columns.intersection(db_columns_list)]

Output
    col3    col1
0   3       1
1   4       2

A: Hope the below code will fix your issue.Intersection works only for sets
common_cols = list(set(dataframe.columns).intersection(set(db_columns_list)))

dataframe = dataframe[common_cols]


text:
Q: ActiveRecord no longer finding duplicate IDs in array and saving for has-and-belongs-to-many relationship, Rails 4.2.8 I upgraded from rails 4.2.0 to rails 4.2.8 this evening. The only major pain has been figuring out why my array of item_ids can no longer have a duplicate when saving in my items_payments HABTM relationship.
This works just fine in 4.2.0... but now, for instance, if  I assign @payment.item_ids = [14,14] before saving the payment, rails and activerecord throw this error: Couldn't find all Items with 'id': (14, 14) [WHERE "items"."id" IN (14, 14)] (found 1 results, but was looking for 2)
If the array of ids does not have a duplicate, then it saves just fine. I need the same item_id to appear more than once, though, in the case that a user buys more than one instance of an item. How do I make it so that this is ok again? I know this may have everything to do with deprecated finders... but how do I do this the right way in 4.2.8 and eventually rails 5.0?
Edit: Here is the code in my controller, model, and schema. I didn't change any of this when upgrading rails... and when saving an array of item ids such as [14,12,5] it will work just fine. It just won't allow me to save with a duplicate item id anymore, like [14,14]
Controller:
items_array = []
items.each do |item|
    quantity = params[:payment][:item_quantity]["#{item.id}"][:quantity]
    quantity = quantity.to_i
    quantity.times do
        items_array.push(item.id)
    end
end

@payment.item_ids = items_array

Schema:
create_table "items_payments", id: false, force: :cascade do |t|
  t.integer "item_id"
  t.integer "payment_id"
end

Payment Model:
has_and_belongs_to_many :items

Item Model:
has_and_belongs_to_many :payments

Lastly, my console output:
(0.2ms)  SELECT COUNT(*) FROM "items" WHERE "items"."id" IN (14, 14)
  CACHE (0.0ms)  SELECT COUNT(*) FROM "items" WHERE "items"."id" IN (14, 14)
Completed 404 Not Found in 133ms (ActiveRecord: 8.6ms)

ActiveRecord::RecordNotFound (Couldn't find all Items with 'id': (14, 14) [WHERE "items"."id" IN (14, 14)] (found 1 results, but was looking for 2)):
  app/controllers/payments_controller.rb:196:in `block in create'
  app/controllers/payments_controller.rb:172:in `create'

A: I think this is just an underlying bug in ActiveRecord for Rails 4.2.8. If you are slowly upgrading to Rails 5, just upgrade on up to Rails 4.2.9 and this issue completely goes away...


text:
Q: How do I make the html select options work in Meteor? I am having trouble getting an HTML Select Options to work the way I think it should work in Meteor.
Here is an example of how it would work with buttons for a collection called Countries.
Template
{{#each get_countries}}
  <button class="btn btnCountryTest">{{iso3}} - {{name}} </button><br />
{{/each}}

Client event handler
'click .btnCountryTest': function(event){
   console.log('clicked .btnCountryTest this._id: ' + this._id);
}

Produces the correct output such as.
clicked .btnCountryTest this._id: 39cd432c-66fa-48de-908b-93a874323e2e

Now, what I want to be able to do is trigger other on page activity when an item is selected from an HTML Select Options drop down.  I know I could put the ID in the options value and then use Jquery etc...  I thought it would "just work" with Meteor but I can't figure out how to do it.
Here is what I am trying and it is not working.
Template
<select class="input-xlarge country" id="country" name="country">
  {{#each get_countries}}
    <option value="{{iso3}}">{{name}}</option>
  {{/each}}
</select>

Handler
'click #country': function (event) {
  console.log('Template.users_insert.events click .country this._id: ' + this._id);
 }

Which produces
Template.users_insert.events click .country this._id: undefined

Clearly not what I had expected.  Any ideas anyone before I resort to Jquery form processing?
Thanks
Steeve

A: In Meteor, each helper calls Meteor.ui.listChunk (please take a look at packages/templating/deftemplate.js), which treats the current variable as this context.
In other words, it's the global context in click #country, and you can only access this._id under each block, like in the click #country option event.
I think you can put the data in HTML data attribute, and access it using jQuery. Just like this -
Template
<select class="input-xlarge country" id="country" name="country">
  {{#each get_countries}}
    <option value="{{iso3}}" data-id={{_id}}>{{name}}</option>
  {{/each}}
</select>

Handle
'click #country': function (event) {
  console.log('Template.users_insert.events click .country this._id: ' + $(event.currentTarget).find(':selected').data("id"));
 }

A: If you're trying to get to the data context, you need to give your event handler access to the template argument, and use it's data object. That is the top level data context.
'click #country': function (event, template) {
    console.log('Template.users_insert.events click .country _id: ' + template.data._id);
}

should work. Here's the best documentation I can find on this: http://docs.meteor.com/#template_data

A: @StevenCannon, I had a similar issue and found a solution here - http://www.tutorialspoint.com/meteor/meteor_forms.htm. @DenisBrat is correct, listen for the change event instead of the click event.
Here's the solution modified for you:
'change select'(event) {
    // Prevent default browser form submit
    event.preventDefault();

    var selectedCountry = event.target.value;

    console.log('Template.users_insert.events change select iso3: ' + selectedCountry);
}

A: You're listening for the 'click' event of the select. You'd really like to subscribe to the 'change' event. 'Click' occurs when you click on a html element. On the other hand, 'change' event gets triggered after you select a value from the list.

A: Maybe you can also take a look at 'packages/liveui/liveui.js'. There is a findEventData function, which give the callback this object.


text:
Q: When reading an image from my Player.java class, I get a strange syntax error     import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.io.*;

    import javax.imageio.ImageIO;

    public class Player {
        int x,y;
        Game game;

        try {
            BufferedImage img = ImageIO.read(new File("Cam.png"));
        } catch (IOException e) {

        }

        public Player(Game game){
            this.game = game;
        }

        public void tick(Game game){
            this.game = game;

            x = (game.getWidth() / 2) - 16;
            y = (game.getHeight() / 2) - 16;
        }

        public void render(Graphics g){
            g.drawImage(img, x, y, 50, 50, null);
        }

After the line "Game game;" I get a "Syntax error on token ";", { expected after this token" error.
Also after the try catch I get a "Syntax error, insert "}" to complete Block"
I'm sure all my syntax is correct yet I still get these strange errors. Any suggestions will help, thank you. :)

A: After some playing around with methods I found out the odd syntax errors are due to the try catch not being inside of a method.


text:
Q: How do you change the cursor image? I am coding a game in Java and I am wondering how one can change the appearence of the cursor to another design.
I am also using LWJGL and slick if that is any help for the people answering this question.

A: Custom and other system cursors
You can create your own cursors (Toolkit.createCustomCursor()) or use cursors from the local system (Cursor.getSystemCustomCursor(String)).
You can change cursor type by setting the cusor property.Here are some types
Cursor.DEFAULT_CURSOR     default cursor
Cursor.CROSSHAIR_CURSOR  crosshair cursor
Cursor.HAND_CURSOR   hand cursor
Cursor.MOVE_CURSOR   move cursor
Cursor.WAIT_CURSOR   wait cursor
Cursor.TEXT_CURSOR   text cursor
Cursor.E_RESIZE_CURSOR   east-resize cursor
Cursor.N_RESIZE_CURSOR   north-resize cursor
Cursor.NE_RESIZE_CURSOR north-east-resize cursor
Cursor.NW_RESIZE_CURSOR north-west-resize cursor
Cursor.S_RESIZE_CURSOR  south-resize cursor
Cursor.SE_RESIZE_CURSOR south-east-resize cursor
Cursor.SW_RESIZE_CURSOR south-west-resize cursor
Cursor.W_RESIZE_CURSOR  west-resize cursor
http://www.leepoint.net/notes-java/GUI/misc/30cursor.html


text:
Q: Swift: difference in the way to unwrapp an option variable Can some explain what is the difference between this two ways of unwrapping a variable:
version 1 :
let myVariable : String? = "my name"

let myNameVariable : String = myVariable!

version 2:
let myVariable : String? = "my name"

let myNameVariable : String! = myVariable

I'll really appreciate if some one explain the difference between those two ways of unwrapping a variable

A: About version 1
let myVariable : String? = "my name"

let myNameVariable : String = myVariable!

This is called unwrapping, unwrap from optional type.
So here type of myNameVariable is String
About version 2
let myVariable : String? = "my name"

let myNameVariable : String! = myVariable

I do not think this is unwrapping, it is about type conversion,
So here type of myNameVariable is String!
It is same as
 let myNameVariable = myVariable as String!

Update:
Main difference
Example 1
let myVariable : String? = "my name"

var myNameVariable = myVariable!

//myNameVariable = nil //Error

var implUnwrapVar:String! = myVariable

implUnwrapVar = nil//OK

Example 2
let myVariable : String? = nil

//var myNameVariable = myVariable! //error

var implUnwrapVar:String! = myVariable // ok


text:
Q: Using pointers with functions, classes, and stacks #include "InventoryBin.h"
#include "Stack.h"
#include <string>
#include <iostream>
using namespace std;

// Constants for the menu choices
const int ENTER_ITEM = 1,
  REMOVE_ITEM = 2,
  QUIT = 3;

int choice;      // To hold menu choice

// Function prototypes
void popItem(Stack<InventoryBin> *);
void pushItem(Stack<InventoryBin> *);
int menu();

void main()
{
  // Create a stack object
  Stack<InventoryBin> stack;

  // Use a loop to ask user for input
  do
  {
    menu();
    if (choice != QUIT)
    {
      switch (choice)
      {
        case ENTER_ITEM:
          pushItem(&stack);
          break;
        case REMOVE_ITEM:
          popItem(&stack);
      }
    }
  } while (choice != QUIT);
}
int menu()
{
  // Display menu
  cout << "Please Select\n"
     << ENTER_ITEM << " - Enter an item.\n"
     << REMOVE_ITEM << " - Remove an item.\n"
     << QUIT << " - Quit.\n";
  cin >> choice;

  // Validate
  while (choice < ENTER_ITEM || choice > QUIT)
  {
    cout << "Enter a valid choice: ";
    cin >> choice;
  }
  return choice;
}
void pushItem(Stack<InventoryBin> *stack)
{
  cout << "Enter serial number: ";
  cin >> stack;
  stack->push(stack);
  cin.ignore();
  cout << "Enter manufacture date: ";
  getline(cin, stack);
  stack->push(stack);
  cout << "Enter lot number: ";
  cin >> stack;
  stack->push(stack);
}

I'm trying to make pushItem and popItem work. The program creates a stack with a data type of InventoryBin... Without posting InventoryBin do you know what I'm doing wrong? My pushItem function has error codes.
No suitable constructor exist to convert from StackInventoryBin *to InventoryBin

A: stack->push(stack); is wrong. Look up stack::push. You should be pushing an ITEM on the stack, not a whole stack. The error code says it all: push() expects a single InventoryBin, but you're passing the whole stack.
And further, I don't know what you would expect to happen if you push a whole stack onto itself....


text:
Q: igraph module of python produces more vertices I am trying to use igraph module of python. When i type
g = Graph()
g.add_vertices(3)
print(g)

The output is as follows
Undirected graph (|V| = 4, |E| = 0)

which means one more than what I asked for.
The tutorial here says different
python igraph tutorial


text:
Q: Family over a set such that the union is the set I'm new to combinatorics, so this may be a common scenario with which I'm unfamiliar.
I'm trying to define a family of set $\mathbb{F}$ over a set $\mathcal{S}$, where the size of each member of $\mathbb{F}$ is not fixed and the empty set is excluded, such that the union of all members of $\mathbb{F}$ is equal to $\mathcal{S}$ itself.
First question is - what is the standard set notation for that? My guess is along the lines of
$$
\mathbb{F} := \left\{f \in \mathfrak{p}(\mathcal{S}) \mid \bigcup f = \mathcal{S} \right\}
$$
Second question - what if $\mathcal{S}$ is a multiset? In my particular case, it would be the sum of the multiplicities from each member of $\mathbb{F}$ rather than the maximum of the multiplicities.
Lastly - where can I find out more about these types of cases? I expect this is a common application.

A: { f $\subseteq$ P(S) - {empty set} : $\cup$f = S }
is what you want.


text:
Q: Prove that two normed linear spaces are equivalent as metric spaces if and only if the norms are equivalent? We have the two norms $\|\cdot\|_a$ and $\|\cdot\|_b$ on the vectorspace V. They're equivalent if there exists a $k>0$ and $K>0$ so that  $k\|\cdot\|_a\le\|\cdot\|_b\le$ K$\|\cdot\|_a$ for all $v\in V$.
I've proved this is an equivalence relation on the set of norms. I now have to prove, that $d_{\|\cdot\|_a}$ is equivalent to $d_{\|\cdot\|_b}$ if and only if $\|\cdot\|_a$ is equivalent to $\|\cdot\|_b$.
I've already proven the "if"-statement, I just have to prove the "only if"-statement now, and I don't really have any ideas how to do it. I would appreciate a little help very much.

A: The definition of equivalent metrics is not given in the Question, and so let's work from a pretty basic notion of that, meaning the identity map on $V$ is a homeomorphism when metric $d_{||\cdot ||_a}$ is supplied for $V$ as the domain and metric $d_{||\cdot ||_b}$ for $V$ as the range.
For arbitrary metrics this notion of equivalence is too weak to conclude a "mutual coercivity" as desired here, so our argument will hinge on the fact that these two particular metrics are norm-derived.  To illustrate the point, consider the metric $d_e$ derived from the Euclidean norm on $\mathbb{R}^n$ and as alternative "truncated" metric:
$$ d_f(x,y) = \min \{ d_e(x,y), 1 \} $$
Even though the two metrics are equivalent in the sense of the identity map being a homeomorphism (or equivalently, in giving the same topology) on $\mathbb{R}^n$, there does not exist a constant $K$ not depending on $x,y$ such that $\forall x,y \in \mathbb{R}^n$:
$$ d_e(x,y) \le K\; d_f(x,y) $$
Let's cite this previous MSE question for the proposition that two metric topologies are equivalent if and only if they have the same convergent sequences.  Also let's simplify notation slightly, calling our norm-derived metrics:
$$ d_a(x,y) = ||x - y||_a $$
$$ d_b(x,y) = ||x - y||_b $$
Easy direction:  Assume norms $||\cdot ||_a$ and $||\cdot ||_b$ are equivalent on vector space $V$, i.e. there exist positive constants $k,K$ as described in the Question.  Then:
$$ k\; d_a(x,y) \le d_b(x,y) \le K\; d_a(x,y) \;\; \forall x,y \in V $$
From this pair of inequalities it is readily seen that a sequence $\{x_i\}$ converges with respect to one metric if and only if does so with respect to the other metric.  Given $\epsilon \gt 0$, if $d_b(x_i,y) \lt k\epsilon$ for all $i \gt M$, then $d_a(x_i,y) \lt \epsilon$ for the same $i \gt M$.  Similarly one shows the implication of convergence after exchanging metrics by replacing $k$ with $1/K$.
Less easy direction:  Assume the metric topologies induced by $d_a,d_b$ are equivalent.  We will show (by contradiction) that there exists $K \gt 0$ such that:
$$ d_b(x,y) \le K\; d_a(x,y) $$
and leave the existence of the constant $k$ in the other inequality as an exercise.  If no such constant $K$ exists, then for each integer $i \gt 0$ we can find $x_i$ such that $d_a(x_i,0) < 2^{-i}$ and $d_b(x_i,0) = 2^i$, using the translation invariance and scaling properties of any norm-derived metric.  Clearly ${x_i}$ converges to zero in the metric $d_a$, but the distances between points grow too rapidly for the same sequence to converge in the metric $d_b$, contradicting the equivalence of topologies.  That is, by the "reverse triangle inequality":
$$ d_b(x_i,x_{i+1}) \ge | d_b(x_{i+1},0) - d_b(x_i,0) | = 2^{i+1} - 2^i = 2^i $$
whereas in a convergent sequence the distances between consecutive terms must tend to zero.


text:
Q: Any issues setting MVC 3 rc1 Razor cshtml file Build Action to Compile? The default build action has been changed from "None" to "Content", as I understand to support Visual Studio publish/deploy.
For a particular project, I do not use the Visual Studio publish/deploy method, nor need to compile from the command line.
Setting build action to "Compile" still seems to compile, with the added benefit of compile-time errors and warnings being generated for any coding mistakes in the cshtml.
This seems like a huge benefit over the usual runtime-only errors.
If I change the build action to "Compile", does anyone know what issues I will run into later?
Many thanks..
edit: I am not sure what future issues I might run into, other than VS deployment, or commandline compilation, but for safety, I went for the precompile option marcind mentions in his comment. I marked that as the closest answer.

A: Setting your Razor files to "Compile" should not work (and I'm surprised that you say it does for you) because files that are marked as "Compile" are passed to the language compiler appropriate to your project types. And most Razor files are not valid C# or VB source files and they will produce compiler errors.
It does look like VS is doing something strange and does not always show the error when you compile from the IDE. However, it does always fail when you compile the project directly from the command line.
So to answer your questions

*

*Because it does not work

*It won't work (now, or later). In fact, when you publish/deploy your site your Razor files will not be copied.

And to be technical, the "Build Action" needs to be "Content" because that's how asp.net publishing/deployment works (and in earlier previews it was "None" because VS did not actually know anything about Razor files and that's the default behavior; the purpose of the "change" was to make things work at all).


text:
Q: Array vs List in recursive F# function I have this function:
let calculate (candles: CandleData list) : decimal list =
    let inline range (q: CandleData) = q.High - q.Low
    let inline price (q: CandleData) = range q / 2m + q.Low

    let rec update (candles: CandleData list) (output: decimal list) lastPrice priceTracker rangeTracker stateTracker lambda =
        match candles with
        | [] -> output
        | h::t ->
            let priceTracker' = 0.2m * (price h - lastPrice) + 0.8m * priceTracker
            let rangeTracker' = 0.1m * (range h) + 0.8m * rangeTracker
            let lambda        = if rangeTracker <> 0m then abs(priceTracker / rangeTracker) else lambda
            let sqr           = decimal (sqrt (double (lambda * lambda * lambda * lambda + 16m * lambda * lambda)))
            let alpha         = (-lambda * lambda + sqr) / 8m
            let stateTracker' = alpha * price h + (1m - alpha) * stateTracker
            update t (output @ [decimal stateTracker']) (price h) priceTracker' rangeTracker' stateTracker' lambda

    update candles [] (price candles.Head) 0m (range candles.Head) (price candles.Head) 0.01m

It operates on lists, but I was wondering if it wouldn't make sense to use an array instead since the data originally comes as an array so I have to convert it to a list to then walk through it sequentially, like an array.
But if I convert it to an array, wouldn't the head / tail part recreate the array every time? so then should I keep the array whole and just iterate with the index?

A: An alternative is to use mapFold:
let calculate3 (candles : _[]) =
    let inline range (q: CandleData) = q.High - q.Low
    let inline price (q: CandleData) = range q / 2m + q.Low

    let init = price candles.[0], 0m, range candles.[0], price candles.[0], 0.01m
    (init, candles)
    ||> Array.mapFold (fun (lastPrice, priceTracker, rangeTracker, stateTracker, lambda) candle ->
            let priceTracker' = 0.2m * (price candle - lastPrice) + 0.8m * priceTracker
            let rangeTracker' = 0.1m * (range candle) + 0.8m * rangeTracker
            let lambda        = if rangeTracker <> 0m then abs(priceTracker / rangeTracker) else lambda
            let sqr           = decimal (sqrt (double (lambda * lambda * lambda * lambda + 16m * lambda * lambda)))
            let alpha         = (-lambda * lambda + sqr) / 8m
            let stateTracker' = alpha * price candle + (1m - alpha) * stateTracker
            stateTracker, (price candle, priceTracker', rangeTracker', stateTracker', lambda) )
    |> fst

It works similar to scan but produces an Array simultaneously.

A: If you want to avoid the cost of converting to list and still keep this as idiomatic F#, you can scan the original array instead of recursing:
let calculate (candles : _[]) =
    let inline range (q: CandleData) = q.High - q.Low
    let inline price (q: CandleData) = range q / 2m + q.Low

    let init = price candles.[0], 0m, range candles.[0], price candles.[0], 0.01m
    (init, candles)
        ||> Seq.scan (fun (lastPrice, priceTracker, rangeTracker, stateTracker, lambda) candle ->
            let priceTracker' = 0.2m * (price candle - lastPrice) + 0.8m * priceTracker
            let rangeTracker' = 0.1m * (range candle) + 0.8m * rangeTracker
            let lambda        = if rangeTracker <> 0m then abs(priceTracker / rangeTracker) else lambda
            let sqr           = decimal (sqrt (double (lambda * lambda * lambda * lambda + 16m * lambda * lambda)))
            let alpha         = (-lambda * lambda + sqr) / 8m
            let stateTracker' = alpha * price candle + (1m - alpha) * stateTracker
            price candle, priceTracker', rangeTracker', stateTracker', lambda)
        |> Seq.map (fun (lastPrice, priceTracker, rangeTracker, stateTracker, lambda) ->
            stateTracker)
        |> Seq.skip 1
        |> Seq.toArray