text:
Q: Google Prediction API with Google App Engine I'm following this example, and at the bottom it has some code
https://cloud.google.com/prediction/docs/developer-guide
I'm using Flask instead of webapp2 and my code looks like this:
# [START app]
import logging
from oauth2client.appengine import AppAssertionCredentials
from flask import Flask
import httplib2, webapp2
from oauth2client.appengine import AppAssertionCredentials
from apiclient.discovery import build

http = AppAssertionCredentials('https://www.googleapis.com/auth/prediction').authorize(httplib2.Http())
service = build('prediction', 'v1.6', http=http)

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World1!'

@app.route('/add')
def something():
    class MakePrediction():
      def get(self):
        result = service.hostedmodels().predict(project=PROJECT-NAME, hostedModelName=PROJECT-ID, body={'input' {'csvInstance': ['hello']}}).execute()
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Result: ' + repr(result))

@app.errorhandler(500)
def server_error(e):
    # Log the error and stacktrace.
    logging.exception('An error occurred during a request.')
    return 'An internal error occurred.', 500
# [END app]

I keep getting the error:
  File "/Users/morganallen/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/Users/morganallen/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/Users/morganallen/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "/Users/morganallen/Desktop/project/flask_app_engine/main.py", line 24
    result = service.hostedmodels().predict(project='linear-yen-140912', hostedModelName='language-identifier', body={'input' {'csvInstance': ['hello']}}).execute()
                                                                                ^
SyntaxError: invalid syntax

What am I doing wrong?

A: You are missing a colon on line 24, where the little carrot is pointing to in the stack trace:
  File "/Users/morganallen/Desktop/project/flask_app_engine/main.py", line 24
result = service.hostedmodels().predict(project='linear-yen-140912', hostedModelName='language-identifier', body={'input' {'csvInstance': ['hello']}}).execute()
                                                                                ^

So the solution here is change this:
body={'input' {'csvInstance': ['hello']}}).execute()
              ^

To this:
body={'input' : {'csvInstance': ['hello']}}).execute()
              ^

That should solve the syntax error.
SyntaxError: invalid syntax

Whenever you get an error, don't ignore all the lines that the compiler spits out. It will often tell you the exact line of a problem, especially in the case of a simple syntax error like this one.


text:
Q: Use BlackBerry JRE 5.0.0 or previous on MacOS I have my Windows work computer set up with JDE 5, but the plugin for the Mac OSX Eclipse on my home computer is JDE 6 and I can't seem to find a source to download it from.
I found a blog post about MacOS BlackBerry development, but it is from before the official MacOS plugin was released.  Anything new on this front?

A: Just in case it saves anyone else wasting half a day, "FYI: Blackberry JDE 4.6 setup on Mac" on the BlackBerry support forums explains how to use the older Blackberry JREs with Eclipse on the Mac.

A: RIM has only released an Eclipse Plugin on OS X.  The JDE is Windows-only and probably will always be Windows-only (RIM is trying to phase out the JDE and is encouraging all developers to move to the Eclipse platform).
Keep in mind that the Eclipse plugin for OS X is still VERY new and still has some rough edges - I tried it out and it crashed on more than one occasion!  Also, there is no simulator available on OS X yet so you'll need a physical device to deploy and test on (I think it has to be a 9800 but I could be wrong).  RIM has promised a simulator on OS X but probably not for another 6 months or so.

A: Were you still looking for an answer to this question? RIM has released the update for the Mac Eclipse v 1.1.2 Plugin. You have to go to "Help > Install New Software ..." and type the url: http://www.blackberry.com/go/eclipseUpdate/3.5/java . It should come up with options for the BlackBerry Java Plug-in Category. Clicking the arrow will reveal the other OS component packs (4.5 - 6.0). Install these (will take a while).
After this, go to the folder where your Eclipse plugins are located. You'll see the folders for the component packs (e.g. "net.rim.ejde.componentpack"). Copy the net.../components/bin folder from the 6.0 component pack to the other versions' components folder (backup the old one first).
In the components folder, there will be a BlackBerry.ee file. Copy the one from the 6.0 component pack into the other versions' components folder (again, backup the original). Open the new .ee file in a WYSIWYG text editor and change the version information to be accurate to the current component pack's version (e.g. 6.0.0.29 changes to 5.0.0.25).
In Eclipse, you need to add a system library. Open the Preferences and go to the Java > Installed JREs menu and click "Add...". When the window pops up, click "BlackBerry Execution Environment VM." For definition file, this is the BlackBerry.ee file for the version of the JRE you are adding. Name the JRE appropriately (e.g. BlackBerry 5.0). Next, click "Add External JARs..." and navigate to the net.../components/lib folder. Select the net_rim_api.jar file. Click finish and you should be good to go. (Repeat for other versions as necessary).
All that's left to do is to specify the correct JRE in your project properties (Java Compiler > {Click} Installed JREs link). Then, make sure the correct version is selected. Also, make sure there is only one JRE listed in the Project Explorer (newbie lesson learned).
Hope that helps if you still needed it to.
I should also add that I'm running my simulators on Windows via Parallels.

A: For Eclipse 3.6 you must use this url: http://www.blackberry.com/developers/jar/3.6/java/
If after downloading have error because too much authentication error, i'm suggesting you must re-create bb developer zone account & login using it (Kind of annoying, coz at my country bandwidth is limited & after waiting 3 hour, the installation is failed).
Also, in copying file don't forget copy fledge from net.rim.ejde.componentpack6.0.0_6.0.0.30/components/. If not when i try to add the definition file JRE i got this kind of error
"Execution Environment File Property-Dee.executable must point to a valid copy offledge.exe"
Hope this is can help.

A: Ahh. Seems like Apple removed java 5 and below from Snow Leopard (10.6). Leopard (10.5) still supports 1.4.2 and 5.0 and 6.0. You can find them in "/Applications/Utilities/Java Preferences.app".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fedora 21 with clang, without gcc Can you (reasonably) get Fedora 21 to where it only has llvm/clang/libc++/libc++abi?  (I found some things suggesting no, but they were all about 3 years old, and llvm/clang has come a long way since then.)
With a fresh install, I tried
yum install gcc gcc-c++
(downloaded, built, installed llvm/cfe(clang)/compiler-rt/libcxx/libcxxabi from svn)
yum remove gcc gcc-c++
added to /etc/profile: export CC=/usr/local/bin/clang \ export CXX=/usr/local/bin/clang++
(in case of hard wiring)
ln -s /usr/local/bin/clang /usr/local/bin/gcc
ln -s /usr/local/bin/clang /usr/local/bin/cc
ln -s /usr/local/bin/clang++ /usr/local/bin/g++
ln -s /usr/local/bin/clang++ /usr/local/bin/c++
ldconfig

I was all happy, then went to build something, and I got:
ld: cannot find crtbegin.o
ld: cannot find -lgcc
ld: cannot find -lgcc_s

clang -v includes
Found candidate GCC installation: /usr/lib/gcc/x86_64-redhat-linux/4.9.2

ldconfig && ldconfig -p | grep libgcc does show
libgcc_s.so.1 (libc6,x86-64) => /lib64/libgcc_s.so.1

And /lib64 is a symlink to /usr/lib64.  And, /usr/lib64/libgcc_s.so.1 is a symlink to /usr/lib64/libgcc_s-4.9.2-20150212.so.1, which exists as a real file (92816 bytes.)
So, I don't get what ld's problem is on -lgcc_s.  crtbegin is nowhere to be found, and gcc (no _s) is nowhere to be found.
yum install libgcc says it's already installed and latest version, nothing to do.
Since I have an installed clang source build, can I re-build clang, this time using clang rather than gcc, to get rid of the dependency?  (Maybe then the "candidate GCC installation" bit goes away.)
Can I force -stdlib=c++ and -lc++abi to be default, or at least have libc++ and libc++abi installed without gcc?

A: Having spent some time trying to get clang to work with libc++ and libc++abi without GCC, I have found that it is indeed possible, even if a bit problematic given the current state of LLVM/clang.  In addition to small test programs, I've been able to build CMake and some other software packages written in C++ with no GCC installed, and with the resulting binaries being independent of libstdc++; they only depend on libc++/libc++abi according to ldd output. Unfortunately, I haven't been able to build clang itself with clang that was build using GCC.  I've been experimenting on different Linux platforms (Fedora 21 32-bit, Amazon Linux release 2015.3 (RPM-based) 64-bit, CentOS 7.1 64-bit, and Ubuntu 14.04 64-bit).
Even though one can build software with clang using libc++/libc++abi without dependency on libstdc++ and without GCC compiler present, a typical Linux installation is so tied to libgcc and libstdc++ that getting rid of these is not practical.  Try removing these two packages and you will see how much of the system depends on them.  Even on FreeBSD 10.1, with clang being the default compiler and no GCC installed, libgcc.a, libgcc_s.so, and a few crt*.o files are used when building a program as revealed by the -v option.  Also, on FreeBSD 10.1, resulting binaries depend on libgcc according to ldd. On Ubuntu, which has dpkg as the package manager, the files
   libgcc.a
   libgcc_s.so
   crtbegin.o
   crtbeginT.o
   crtbeginS.o
   crtendS.o
   crtend.o

are in the libgcc-devel package, while on an RPM-based system, such as Fedora, these are in the gcc package.  In addition, you might possibly need these files, even though I didn't need them for the code I tried building:
   crtfastmath.o
   crtprec32.o
   crtprec80.o
   crtprec64.o

Thus one might argue that the aforementioned files better belong in libgcc, rather than in gcc.  As far as I can tell, the following needs to be done on an RPM-based system before removing the gcc package:
1) Create the symlink
libgcc_s.so -> libgcc_s.so.1

in whatever directory libgcc_s.so.1 is located.
2) Copy the crt*.o files listed above to that directory.
3) In the same directory create the symlink (libstdc++.so.x should already be there; x is a number):
libstdc++.so -> libstdc++.so.x

You only need this if you are going to use libstdc++; this isn't needed if you only plan to use libc++.  On some
systems libstdc++.so, which is a symlink to libstdc++.so.x belonging to the libstdc++ package, is placed by the libstdc++-devel package into the GCC library directory, so you can remove that directory after uninstalling GCC and just create the symlink in the same directory where libstdc++.so.x lives.
Now you should be able to do the following:
1) Build a C program:
clang progname.c

2) Build a C++ program using libstdc++ headers/libs:
clang++ -I<location of headers> progname.cpp

On RPM-based systems I've looked at, the libstdc++ headers are part of the libstdc++-devel package and their location can be found from rpm -ql on the package.
3) Build a C++ program using libc++ headers/libs:
clang++ -I/<location of headers> progname.cpp -nodefaultlibs -lc++ -lc++abi -lm -lc -lgcc -lgcc_s

The location of the headers is wherever they were installed when you built LLVM+clang etc.
Please see http://libcxx.llvm.org/ for additional information.  When building C++ code using libc++/libc++abi, you may use -stdlib=libc++ instead of the -I flag, but in my testing that only worked with clang built from source, not with clang installed from a repository (you can install clang from repo and use it to build libc++/libc++abi; or you can use gcc to build libc++(abi), then remove gcc and use the libs with the repo-provided clang).
When configuring a software package to build it using clang + libc++, you might need to set the following:
LIBS="-nodefaultlibs -lc++ -lc++abi -lm -lc -lgcc_s -lgcc"
CXX=clang++
CXXFLAGS="-stdlib=libc++"
CC=clang

Please note that to configure CMake source in order to build it I had to use a wrapper script like this:
#!/bin/bash

MYLFLAGS="-nodefaultlibs -lc++ -lc++abi -lm -lc -lgcc_s -lgcc"

# Catch the case when we only want to compile; this helps us avoid some warnings:
if echo "$@" | egrep "(^-c | -c | -c$)" >/dev/null 2>&1; then
MYLFLAGS=""
fi

/usr/local/bin/clang++ -stdlib=libc++ "$@" $MYLFLAGS

It might be useful for other purposes as well.
For more information please see my article at http://www.omniprog.info/clang_no_gcc.html


text:
Q: Strange behavior of urllib2.HTTPHTTPBasicAuthHandler when handling 401 Authorization? The server I'm trying to logon and download a file from  is using Basic Auth as I can confirm from Chrome Dev Tools and some tests. So I write code like below, bad example of OOP perhaps, but should make sense.
class Utils(object):
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.top_level_url = 'http://test.com/'
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
        password_mgr.add_password(None, self.top_level_url, self.username, self.password)
        basic_auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
        opener = urllib2.build_opener(basi_auth_handler)
        urllib2.install_opener(opener)

    def download(self, filename):
        url = self.top_level_url + filename
        req = urllib2.Request(url)
        try:
            response = urllib2.urlopen(req)
            return response
        except urllib2.HTTPError as e:
            print e.headers
            raise

Strange things happen, when I initialize a Utils object and download the file repeatedly:
u = Utils('username', 'password')
index = 0
while 1:
    resp = u.download('file.txt')
    index += 1
    time.sleep(1)

The scripts works for the first 5 times of download, but at the 6th time, it would raise HTTPError 401. But if  I change the code, add the post header to include 'Authorization: Basic ***' instead of using HTTPBasicAuthHandler, it works every time... So is this something wrong with my code or the server part setup?


text:
Q: Converting a String to Json Object with validation in java I am having a string like ,
name = " {
        "Name" : "MyName"
      }"

and having a Model class like ,
 @Valid
    Class Model {
        @JsonProperty("Name")
        @Size(min = 1)
        @NotNull
        private String name;
    }

Now I am converting the string to Java Object by following code,
   Model name = objectMapper.readValue(name, Model.class);

So the validation(min = 1 and not null) is not happening with this.
How can I validate when I am converting a string to java object?

A: i will try to help u.
I have an idea and it´s that u divide the process in 2 parts:
First, u take the json and put in on a JSONObject:
import org.json.JSONObject;
...
JSONObject json= new JSONObject(name);

Then, u can call, for example, a function passing a json that validate the values of json an if is correct return a model object:
public Model functionExample(JSONObject json){
     try{
          if(json.has("Name") && json.getString("Name")!=null){
               return new Model(json.getString("Name"));
          }
     }catch(Exception ex){
          return new Model();
     }
}

This check if the field "Name" exists and it´s not null.
I don´t know if it is what u want.
I hope it help u.


text:
Q: Factoring Constants out of Matrix Products This seems like a rather trivial question, but I just want to know first if I am correct that this step is valid and, if so, if there's a name to it. It surely isn't linearity, unless I am mistaken.
Suppose we have matrices A and B. Further, B is a scalar multiple of some other matrix, so perhaps we have $B = 3C$. My question is, would it be valid in multiplying $A$ and $B$ to pull out the constant $3$ and then multiply it by the product of $A$ and $B$? In  other words:
$$AB = A(3C) = 3(AC)$$
In other words, it is necessarily the case that the above must hold? Is there a name for such a property?
Thanks. I apologize for how elementary this surely is.

A: Yes, constants commute in and out of the matrix multiplication order. In other words, if $x$ is a constant, $A$ is an $n \times k$ matrix and $B$ is $k \times m$ matrix for positive integers $k,m,n$, then
$$
x(AB) = (Ax)B = A(xB) = (AB)x.
$$

A: Yes, it does. In fact, this is actually essential by definition of the matrix as a linear operation. A linear operation adheres to two conditions given as follows.
\begin{equation}
f(x + y) = f(x) + f(y) \\
f(c \cdot x) = c \cdot f(x)
\end{equation}
Every matrix is a linear operation, but not every linear operation is necessarily a matrix.

A: The answer is yes.
When a matrix is multiplied by a constant each row is multiplied by the same constant.
When you multiply matrices you find dot product of the rows of the first one and columns of the second one so the constant could be factored out.


text:
Q: ReferenceError: "$" is not defined Getting error ReferenceError: "$" is not defined.  when below function is run. I have enabled Sheets API in both Google API console & Advanced Google Services
function createTriggers2() {
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>;

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://api.msg91.com/api/v2/sendsms",
  "method": "POST",
  "headers": {
    "authkey": "My_auth_key",
    "content-type": "application/json"
  },
  "processData": false,
  "data": "{ \"sender\": \"SOCKET\", \"route\": \"4\", \"country\": \"91\", \"sms\": [ { \"message\": \"Message1\", \"to\": [ \"96xxxxx\", \"70xxxxx\" ] }, { \"message\": \"Message2\", \"to\": [ \"98260XXXXX\", \"98261XXXXX\" ] } ] }"
};

$.ajax(settings).done(function (response) {
  console.log(response);
})
}

A: jQuery is not being loaded because you have an HTML tag in your javascript.  Move this line out into the HTML, above where you call jQuery:
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>;


text:
Q: C++ SMTP that allows file attachments I am looking to create an SMTP that allows for file attachments, however, I am finding it difficult to locate a tutorial. I have found one close thing, which is https://stackoverflow.com/questions/58210/c-smtp-example , however, this fails to compile in VS2005/2010 because of the include files that are used.
I would like to roll my own and not adapt to some library such as Curl or Boost. Does anyone have any suggestions on how to do this, or some small sample code with good documentation that will compile in Visual Studio?

A: Building on my answer to a previous question, using the Microsoft ATL classes which are included in the paid versions of Visual Studio.
CSMTPConnection smtp;
if (!smtp.Connect(m_strEmailServer))
    return false;
// start generating the email message; remember to call CoInitialize somewhere in the app before this
CMimeMessage msg;
msg.SetSubject(m_strSubject);
msg.SetSender(m_strSender);
// repeat the following as necessary
msg.AddRecipient(strSingleRecipient);
msg.AddText(m_strBody);

// add an attachment
msg.AttachFile(m_strAttachmentPath, m_strAttachmentName, _T("application/octet-stream"));

if (!smtp.SendMessage(msg))
    return false;
return true;

The MIME type supplied in the AttachFile call will depend on the type of attachment.

A: There are a couple of ways to do attachments. You can use UUEncoded or MIME formatting. The UUEncoded is much simpler if you want to roll your own.


text:
Q: Android Background Image: How to Support All Resolutions? I read the document:
Supporting Multiple Screens
But still can't figure out how to support all screen resolutions in Table 2 in the document. Even if I create three versions for LDPI, MDPI and HDPI, there are more than screen resolutions in that table, if there is no matching image, it will scale my image and may not retain the aspect ratio.
Is there any standard way to deal with this?
Thanks!

A: See this question: How to scale an Image in ImageView to keep the aspect ratio answered by Steve H

*

*Yes, by default Android will scale your image down to fit the  ImageView, maintaining the aspect ratio. However, make sure you're
  setting the image to the ImageView using android:src="..." rather than
  android:background="...". src= makes it scale the image maintaining
  aspect ratio, but background= makes it scale and distort the image to
  make it fit exactly to the size of the ImageView. (You can use a
  background and a source at the same time though, which can be useful
  for things like displaying a frame around the main image, using just
  one ImageView.)

*There isn't "white space", it's filled with transparent pixels. If you don't want even those, you could simply put your
  layout_width="fill_parent" and layout_height="wrap_content".
Then as Samuh wrote, you can change the way it default scales images
  using the android:scaleType parameter. By the way, the easiest way to
  discover how this works would simply have been to experiment a bit
  yourself! Just remember to look at the layouts in the emulator itself
  (or an actual phone) as the preview in Eclipse is usually wrong.

A: <supports-screens android:normalScreens="true"
    android:largeScreens="true" android:anyDensity="true">
</supports-screens>

put the above code in your android manifest file using it your application is support all the screen size.
I hope this is help.


text:
Q: If $f$ is open and surjective, can i say that $f$ is continuous? my try was, take $U$ open in $Y$ then we take $V$ in $X$ such that $V = f^{-1}(U)$, so as $f$ is surjective $f(V) = U$ and if $V$ is not open then $U$ shoudn't be as $f$ is open.
is that correct?

A: No that's not. Take any set X with at least two elements, and consider the identity of this set, viewed as a map of X endowed with the trivial topology to X endowed with the discrete topology.

A: $1_X(x) = x$ (clearly even a bijcction, not merely a surjection) from $(X,\mathcal{T}_1)$ to $(X, \mathcal{T}_2)$ is open iff $\mathcal{T}_1 \subseteq \mathcal{T}_2$ and continuous iff $\mathcal{T}_2 \subseteq \mathcal{T}_1$. This follows from the definitions and $1_X[O] = 1_X^{-1}[O] = O$ for all $O \subseteq X$.
So choosing appropriate topologies on the same set we get easy examples of continuous non-open maps and open non-continuous maps. As $1_X$ is a bijection, $1_X$ is open iff $1_X$ is closed, giving us examples of non-closed continuous maps as well, etc.

A: Let $\{0,1\}$ be a topological space with trivial topology and $\{0,1\}^{\delta}$ a topological space with discrete topology. Let $f:\{0,1\} \to \{0,1\}^{\delta}$, $0\mapsto 0$ and $1\mapsto 1$. Then $f$ is open and surjective but $f^{-1}(\{1\}) = \{1\}$ is not open in $\{0,1\}$ and open in $\{0,1\}^{\delta}$.


text:
Q: Java Collections not recognized I'm new in Java and trying the following code on collections.
I'm getting on Eclipse the warnings i commented as WARNING: in the below code.
import java.util.*;

public class A {

    public static void main(String[] args) {
        LinkedHashMap map = new LinkedHashMap();

        // add some values in the map
        map.put("One", "1");
        // WARNING:
        //      - Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap<K,V> should be parameterized
        //      - The method put(String, String) is undefined for the type LinkedHashMap

        map.put("Two", "2");
        System.out.println("Map:" + map);

        // get key "Three"
        System.out.println("" + map.get("Two"));  // WARNING:  he method get(String) is undefined for the type LinkedHashMap

        // get key "Five"
        System.out.println("" + map.get("Five"));
    }
}

This is a code sample from a site, and supposedly a simple one.
How come am i getting errors? how can i fix them?
i'm new to Java. bear w/me pls.

A: Fix all the warnings at once by properly declaring your map with generics. If you're using Java >=7:
Map<String, String> map = new LinkedHashMap<>();

otherwise:
Map<String, String> map = new LinkedHashMap<String, String>();

A: First of all you should use.Its better to use Interface always
Map map = new LinkedHashMap();

Typesafety In simple I can explain as  If you have a basket of fruit do  you want to store flowers there?
So you should declare as
Map<String,String> map = new LinkedHashMap<String,String>(); which says my map key is of string type and value if of string type


text:
Q: How to find canny edge detected pixels in a Mat object? I do this:
Imgproc.Canny(mGraySubmat, mIntermediateMat, 50, 100);

Stop me when I´m wrong:
1. Now the edges should be in mIntermediateMat.
2. All pixels in mIntermediateMat should have a color value of 0 OR 255. (I fetch the values with mIntermediateMat.get(x,y)).
3. mIntermediateMat.type()=> Mat [ 480*640*CV_8UC1, isCont=true, isSubmat=false, nativeObj=0x139ec0, dataAddr=0x4453d010 ]
and
mGraySubmat.type()=> Mat [ 480*640*CV_8UC1, isCont=true, isSubmat=true, nativeObj=0x1e8308, dataAddr=0x450b4010 ]
Now lets say Canny has detected edges similar to a rectangle. Now I start from a seedpoint inside this rectangle and walk to the north, south, east, west and check every pixel value until I reach the edges.
See the results:
Picture can be found here http://i.stack.imgur.com/JWVJW.png
Walking to the north seems to work. Pixel with value 255 found at coordinates: x,y = 239,346 ->right
South: Pixel with value 255 found at x,y = 239,488 (actually 488 cant be, because 480 is maximum)->wrong
East: Pixel with value 255 found at x,y = 342,388 ->wrong
West: No pixel found, out of screen... -> wrong
Question: Whats wrong? Why is an edge-pixel not detected when I walk over it.
IMPORTANT: At the top and the left of the picture there is a scale with size of 100 pixels. The origin is at the top left and a coordinate of x,y = 100,350 would be 100 pixels to the right and 350 pixels DOWN.

A: I fetched the pixel color value with mIntermediateMat.get(x,y). Thats just wrong. As function is defined as Mat.get(rows,cols) it would be mIntermediateMat.get(y,x). See the difference? I didn´t. Lots of lost time and another dumbness award for me.


text:
Q: speeding up redirection in laravel middleware code
namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class isAdmin
{

    public function __construct(Guard $auth) {
        $this->auth = $auth;
    }

    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        $user = auth()->user();

        if (auth()->check() && $user->isAdmin()){
            return $next($request);
        }

        abort(403, 'You do not have permission to perform this action.');

    }

this is in my user.php model
protected function roleId(){
    return auth()->user()->role_id;
}

public function isAdmin()
{
    if (  $this->roleId() === 4 || $this->roleId() === 6 ) {
        return true ;
    }
    else {
        return false ;
    }
}

this is in my routes/web.php file
Route::group([
    'namespace' => 'Admin',
    'middleware' => 'isAdmin',
    'prefix' => 'admin'
], function () {

    Route::get('/', 'DashboardController@index')->name('admin.dashboard');

});

But it's slow as hell, can I improve it's speed, I a definitely redirected but it's slow asf, and I want to improve its speed, maybe some optimization can do. Any tips from you guys..
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;

ini_set('max_execution_time', 180);
class DashboardController extends Controller {

    public function index()
    {
        return view('app.admin.dashboard');
    }
}

edited the code to see what's in the dashboard view

A: I would say there are some scopes for improvement in your current code as well.
Your User model seems to have nested functions. e.g. middleware is calling isAdmin() and its then calling roleId() then that is doing auth()->user()->role_id and not $this->role_id.
Instead of having middleware, use policy may be e.g. DashboardPolicy.
Your policy can have the method :
public function index(User $user)
{
   return in_array($user->role_id, [4, 6]);
}

Then Register it inside app/Providers/AuthServiceProvider.php:
protected $policies = [
.
.
.
Document::class => DocumentPolicy::class,
]

and then in your controller you will do
public function index(){

    $this->authorize('index', Dashboard::class);
    return view('app.admin.dashboard');

}

This will be cleaner.
Now to debug the time issue, you can comment all custom middlewares and just keep it simple returning view. If it is fast then one of  your custom middleware was causing this. If you implement the policy approach, isAdmin middleware can be removed directly.


text:
Q: Picasso загрузка изображения byte[] Я имею ссылку типа myapi/image?image_id={1} при переходе на которую я получаю изображение в виде byte[]. Как с помощью Picasso я могу загрузить ее в ImageView?
UPD:
В консоли, при загрузке можно наблюдать:
..../com.example.myapplication D/skia: —- SkAndroidCodec::NewFromStream returned null
..../com.example.myapplication D/Picasso: Dispatcher batched [R0]+2839ms for error
..../com.example.myapplication D/Picasso: Main errored [R0]+3054ms Failed to decode stream.
UPD2:
Может быть стоит посмотреть в сторону объекта Target?
UPD3: Формат ответа сервера:

UPD4:
Картинка хранится на sql server в формате varbinary(max), ниже скрин из бд.
Чтобы получить картинку по id можно перейти по ссылке (https://vy5trnewne.execute-api.eu-central-1.amazonaws.com/Prod/api/images/getimage?imageId=2)


text:
Q: how to convert scanned jpg files to pbm format losslessly? Using ImageMagick's convert utility to convert some scanned jpg files to pbm files.
However, even if the option -quality 100 is used, the pbm's resolution still looks worse than the original scanned jpg file.
Worse, the scanned jpg file is a colored one, while the converted pbm is black and white.
Info of original jpg:
image size: 2256 × 1568 pixels
dpi: 300 pixels/inch
color model: RGB
info of the converted pbm:
image size: 2256 × 1568 pixels
dpi: 72 pixels/inch
color model: Gray
Currently, here is what I did to convert the format:
qiang@bonjour:~/scan$ convert scan000.jpg scan000.pbm

Am I missing any option to use with convert? As I mentioned earlier, -quality 100 had been tried, but to no avail.

A: Using ImageMagick, I think you want to output to PPM not PBM. Try
convert image.jpg image.ppm

or try the ascii version by using
convert image.jpg -compress none image.ppm

PBM is binary (black/white) and PGM is grayscale. If you want to keep color, then you need to use PPM.
Unfortunately, I believe that ImageMagick can only read DJVU format images. So you cannot write to it directly from ImageMagick.


text:
Q: Realloc existing data is getting lost I am learning c programming language. The program below takes the output of a command to variable and prints it. But when reallocate the memory to extend the memory I am losing the old data.
Can you please telling what I am missing here?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(){

FILE *fp;

char r[1024];
fp=popen("/bin/ls /etc/","r");

if(fp==NULL){
    perror("Failed to run the command");
    exit(-1);
}

int totallengthread=0,alloc_size=1024;
char *buffer = (char*) malloc(alloc_size*sizeof(char));
memset(buffer,0,sizeof(buffer));
int lenofbuff=0;
while(fgets(r,1023,fp)!=NULL){
 concat(buffer,r);
 lenofbuff=strlen(buffer);
 totallengthread+=lenofbuff;
 if(totallengthread>=alloc_size){
     alloc_size+=1024;
     realloc(buffer,alloc_size);
 }

}
pclose(fp);
printf("this is the out put =>%s",buffer);
free(buffer);
 return 0;
}
void concat(char *dest, const char *source){
    char *d=dest;
    char *s=source;
    while (*d != '\0') {
              d++;
           }
     while(*s!='\0')
        {
            *d++=*s++;
        }
    *d='\0';
}

A: realloc() is a building block  for a general purpose memory reallocation.
Code needs to use the return value from realloc() as that is the pointer, on success, to the reallocated data.
void * tptr = realloc(buffer, alloc_size);
// Detect out-of-memory
if (tptr == NULL && alloc_size > 0) {
  // Handle it in some way
  fprintf(stderr, "Memory allocation failure\n");
  exit(EXIT_FAILURE);
}

buffer = tptr;

Note: Various other non-allocation code issues exist.

A: I think this is a bit closer to what you want. Please see the comments in the code.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void concat(char *dest, const char *source){
    char *d=dest;
    char *s=source;
    while (*d != '\0'){
        d++;
    }
    while(*s!='\0'){
        *d++=*s++;
    }
    *d='\0';
}

int main(){
    FILE *fp;
    char r[1024];
    fp=popen("/bin/ls /etc/","r");
    if(fp==NULL){
        perror("Failed to run the command");
        exit(-1);
    }
    int totallengthread=0,alloc_size=1024;
    char *buffer = malloc(alloc_size*sizeof*buffer); //This is nicer because is type independent
    memset(buffer,'\0',sizeof*buffer); //I believe this is what you wanted.
    int lenofbuff=0;
    while(fgets(r,sizeof r,fp)){ // as @chux said this avoids hardcoding 1024-1. You also don't need to compare to NULL.
        concat(buffer,r);
        lenofbuff=strlen(buffer);
        totallengthread+=lenofbuff;
        if(totallengthread>=alloc_size){
            alloc_size+=1024;
            buffer = realloc(buffer,alloc_size); //you need to use the return of realloc
        }
    }
    pclose(fp);
    printf("this is the out put =>%s",buffer);
    free(buffer);
    return 0;
}

As @chux mentioned, as in any memory allocation you should check whether the returned pointers are NULL, that would mean the allocation failed.
Also, please note that
memset(buffer,'\0',sizeof*buffer);

is equivalent to
memset(buffer,0,sizeof*buffer);

and as @thebusybee mentioned this is only setting the first element of the array to the NULL character, if you were intended to fill the whole array you should do
    memset(buffer,0,alloc_sizesizeofbuffer);
or just replacing
char *buffer = malloc(alloc_size*sizeof*buffer);
memset(buffer,0,alloc_size*sizeof*buffer);

for
char *buffer = calloc(alloc_size,sizeof*buffer);


text:
Q: Unit testing remote EJB bean with security This question is similar to Java EE declarative security, acquiring reference to a secured bean from application client but is more specific.
I can unit test my local beans with the Glassfish embedded container. For the remote beans I have written application clients. This was a viable solution until security was applied at the remote beans. Now I encountered the problem of authenticating an application client towards Glassfish 3.1.1.
The phenomenon:

*

*Testing the remote bean without security with an application client is all right.

*The approach to use security with the application of ProgrammaticLogin does not work and I am not sure it is the correct way to solve the issue in unit tests. (See the attached link at the beginning.)

Question:

*

*How do you think unit testing with security with remote beans should be done?

*Where does one need to place the glassfish-ejb-jar.xml? (Maybe this is erronous in my case and this is the reason that the ProgrammaticLogin does not work.)

A: I continued to search for more information on the internet and I encountered the following blog: http://www-02.imixs.com/roller/ralphsjavablog/entry/junit_and_glassfish_3_1.

*

*It answers how to test EJB 3.1 on Glassfish 3.1.1 without any third party tool. It is a little tricky.

*The security settings I have not yet tried but there is also an example with regard to this.


text:
Q: Asynctask wait function causes error im trying to run this code
protected String doInBackground(String... params) {
    InetAddress client = null;
    boolean run = true;
    String data = "";
    DatagramPacket packet = null;
    while( run )
    {
        if( data.equalsIgnoreCase( "" ) )
        {

        }

        //Send some data
        if( data.equalsIgnoreCase( "connect" ) )
        {

        }

        //Log.d(TAG, "Data received was :" + data);

        try
        {
            this.wait( 25 );
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            Log.d(TAG, "Error with trying to sleep");
            e.printStackTrace();
        }
    }
    Log.d(TAG, "Error with while run value");
    return "finished";
}

and once it reachs the this.wait( 25 ); I get this error
04-02 18:49:25.070: D/gameObject(9065): New game object
04-02 18:49:25.085: W/dalvikvm(9065): threadid=12: thread exiting with uncaught exception (group=0x40015560)
04-02 18:49:25.089: E/AndroidRuntime(9065): FATAL EXCEPTION: AsyncTask #2
04-02 18:49:25.089: E/AndroidRuntime(9065): java.lang.RuntimeException: An error occured while executing doInBackground()
04-02 18:49:25.089: E/AndroidRuntime(9065):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at java.lang.Thread.run(Thread.java:1019)
04-02 18:49:25.089: E/AndroidRuntime(9065): Caused by: java.lang.IllegalMonitorStateException: object not locked by thread before wait()
04-02 18:49:25.089: E/AndroidRuntime(9065):     at java.lang.Object.wait(Native Method)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at java.lang.Object.wait(Object.java:395)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at com.example.gelorph_v1.gameServer.doInBackground(gameServer.java:116)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at com.example.gelorph_v1.gameServer.doInBackground(gameServer.java:1)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
04-02 18:49:25.089: E/AndroidRuntime(9065):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
04-02 18:49:25.089: E/AndroidRuntime(9065):     ... 4 more

Any reason why this is happening?
Canvas

A: I don't think wait is what you want. This tells it to wait to be notified by another thread through calling notify(). Try
Thread.sleep(25);  // 25 is time in millis to sleep
instead. This will make the thread sleep (obviously) for the amount of time you have declared before proceeding
Thread
Wait

A: Are you sure you want to wait and not sleep?  If you want it to always pause for 25 ms, use sleep.  If you do want to use wait, you need to do so in a synchronized block for the object you're waiting on.


text:
Q: Initializing classes from saved file In Objective-C++, I want my application to be able to save and load files that express the existence of certain C++ objects. For example, a user is running the application and has created objects a, b, and c of classes A, B, and C. The user hits save to create a file that lists these objects in some format. The application should then be able to load from this file and initialize new objects x, y, and z of classes A, B, and C by calling constructors A(), B(), and C(). (This is obviously a heavy simplification of the process.)
What do you think is the best strategy for doing this? Is there any more elegant solution than a big switch statement mapping text to constructors or something along those lines? Would function pointers help me out? I could imagine doing something like having A, B, and C register themselves with the object that owns them, and it stores their constructors with a key somewhere, but I'm wondering if there's something simple that I'm missing.
The big issue here is that there are dozens of classes that must be saved so I want the lightest solution possible.

A: Following up on the comment I just put on your post, that article states the following regarding Objective-C:
"In the Objective-C programming language, serialization (more commonly known as archiving) is achieved by overriding the write: and read: methods in the Object root class."
I'm only new to Objective-C myself, but I'm familiar with the concept of serialization. In this case, by overriding those methods, you are making an object of a given type capable of writing itself to a file in a format you specify, and also you are allowing it to set its state by reading its state from a file.
I'm sure Google will reveal a lot of tutorials on this.


text:
Q: Cargar datos en datatable mediante una consulta select WHERE con $_GET pasado a traves de un formulario Tengo un formulario que envia por GET un valor
 - localhost/test/testlist.php?codov=2222
Intento coger el valor por GET desde test.php para rellenar la tabla pero algo debo estar haciendo mal, o mal planteado. Porfavor si alguien me puede ayudar estaría eternamente agradecido.
Despues de poner en el form del index un numero y darle a enter aparezco en localhost/test/testlist.php?codov=2222 y necesito que el "2222" pase a test.php para realizar la consulta y poder mostrar el contenido de 2222 en la datatable
Esto es testlist.php

                Código
                Nombre

y esto seria test.php pero con consigo que por GET me coja el valor que le dio en el primer form.
<?php
include_once("DbConnect.php");

$sql = "SELECT
            req.id as IdArt,
            req.item as CodArt,
            req.qty_req as Requerido,
            req.sales_order as Ov,
            concat_ws(' ',stk.itm_name_1,' ',stk.itm_name_2, ' ',stk.itm_name_3) as NombreArt,
            ifnull(SUM(iss.quantity),0)  as Consumido,
            ifnull((select sum(soh.quantity) from mapubli.soh soh where soh.item=req.item),0) as StockActual
            FROM
                mapubli.so sales
            INNER JOIN
                mapubli.req req ON sales.num = req.sales_order
            INNER JOIN
                mapubli.stkitm stk ON stk.itm_code = req.item
            LEFT JOIN
                mapubli_proy.mpl_web_iss iss ON req.id = iss.req_id
            where sales.num = 1909612
                group by req.id
                order by req.item";

            $result = mysqli_query($link, $sql);
            echo $sql;

            if ( !$result ){
                die("ERROR");
            }else{
                while ($data = mysqli_fetch_assoc($result)) {
                    $arreglo["data"][] = $data;
                }
                echo json_encode($arreglo);

            }

mysqli_free_result($result);
mysqli_close($link);

?>

A: Tu inconveniente es que realizas el envío por POST y no por GET
"ajax":{
    "method":"POST",
    "url":"test.php"
},

Para obtener el parámetro codov de la URL, utilice URLSearchParams tomándolo de esta respuesta
Una solución seria enviar el dato necesario vía data en el Ajax.
Mas detalles de Data

Y en tu archivo test.php recibes vía POST la variable
<?php
include_once("DbConnect.php");

$codov = $_POST['codov'];

//Sugiero que valides si $codov es un código permitido

//Lo utilizas en el select
$sql = "SELECT ...


text:
Q: iOS 7: Delete button color of calendar app, how to get it? I've created a similar screen as the edit screen of a calendar event. Now I have the same button for deletion but in blue at the bottom of my screen. How can I get this orange/red programmatically for this button?
Thx!

A: It is the color [UIColor colorWithRed:0.945 green:0.231 blue:0.129 alpha:1.0]. I got it with the help of a screencolor picker.


text:
Q: Dynamic routing getting undefined The API I'm using receives a phone number as a parameter to return data from a user. So in the UI, I receive this number and through console.log I can see the data. But I also want, when clicking the button the user is taken to a link containing only data related to them and to do that I believe that I have to redirect the user to a dynamic link eg: '/user/john'. I'm always getting undefined in the link and I have no idea why. It feels like the state itself is not storing the API data
const Login =()=> {
  const history = useHistory()
  const location = useLocation()
  const [state, setState] = useState('')
  const [data, setData] = useState({});
  const phone = state
...
  let headers = new Headers();
  headers.set("Authorization", "Basic " + btoa(username + ":" + password));

    const handleClick=() => {
    getData();
  };

  const getData = async () => {
    const a = await fetch(url, { method: "GET", headers: headers });
    const response = await a.json();
    setData(response.user[0].attributes[0]);
    history.push(`/user/${data.name}`)
  };

   const onTextChange = event => {
        setState(event.target.value);
      }
<input onChange={onTextChange}>
 <Button  onClick={handleClick} >
    login
 </Button>

A: State always sets asynchronously (more details). setData(response.user[0].attributes[0]) will take some and since js is asynchronous next line will be executed i.e
history.push('/user/${data.name}'). Since there is no data yet so data.name will be undefined.
Instead you must directly use history.push(/user/${(response.user[0].attributes[0]).name})
Here is the updated code:
    const Login = () => {
    const history = useHistory()
    const location = useLocation()
    const [state, setState] = useState('')
    const [data, setData] = useState({});
    const phone = state
    ...
    let headers = new Headers();
    headers.set("Authorization", "Basic " + btoa(username + ":" + password));

    const handleClick = () => {
    getData();
    };

    const getData = async () => {
    const a = await fetch(url, { method: "GET", headers: headers });
    const response = await a.json();
    const respData = response.user[0].attributes[0]
    setData(respData);
    history.push(`/user/${respData.name}`)
    };

    const onTextChange = event => {
    setState(event.target.value);
    }
    <input onChange={onTextChange}>
    <Button onClick={handleClick} >
      login
    </Button>


text:
Q: Access codeigniter controller from command line I'm playing around with CI around PHP CLI.
I'm now able to access the whole CI structure via a Global variable $CI (followed the tutorial here http://codeigniter.com/wiki/dip_into_CI/)
$CI = new $class();
$CI -> load->view ('header');

Now works good, but I don't know how to access a controller thru the $CI variable.
Let's say I have a controller called main(); i'd like to be able to do something like :
$CI->main->myfunction($params);

Must be real simple but can't figure out

A: That's all possible but a little crazy. Just use CodeIgniter Reactor. Controllers can respond to command line perfectly.
https://bitbucket.org/ellislab/codeigniter-reactor
php index.php controller method param1 param2
Works with routing and everything.

A: Yes.. It works with MX and the "regular" CI that you download from codeigniter.com.


text:
Q: Effect of "new" in JavaScript I have written some code I found in a video, and it looks something like this:
var clientX = clientX || {} ;
clientX.MyClass = function(initialValue){
  var var1 = initialValue;
  var publicMembers = {
    get_var1 : function(){
      return var1;
    }
  };
  return publicMembers;
}

var result = new clientX.MyClass("val1");
alert(result.get_var1());

clientX.instance = new  clientX.MyClass("val2");
alert(clientX.instance.get_var1());

clientX.instance2= new clientX.MyClass("val3");
alert(clientX.instance2.get_var1());

The thing is, after deleting the "new" keyword when I use : var result = new clientX.MyClass("val1"); Nothing is changed, so why the author chose to use it? What's the effect?

A: The MyClass function makes no use of this and has an explicit return value, so the use of new has no practical effect whatsoever.

A: the new keyword is used as a piece of pseudoclassical instantiation, wherein a constructor object has properties attached to the keyword "this" but no return value is ever written.
var Car = function(){

  this.color = 'blue';
  this.make = 'toyota';
  this.model = 'camry';

}

now, writing var x = new Car() will add the following lines to the interpretation:
var Car = function(){
  var this = {}; //added by new
  this.color = 'blue';
  this.make = 'toyota';
  this.model = 'camry';
  return this; //added by new
}


text:
Q: Kendo Multi-select in cascading scenario unable to populate initial values I'm using Telerik for MVC and trying to get the multi-select to populate with the initial values in an Edit scenario.

                    @Html.LabelFor(m => m.ManufacturerList, "Manufacturer", htmlAttributes: new { @class = "control-label col-md-2" })

            @(Html.Kendo().DropDownListFor(m => m.ServiceBulletinItem.ManufacturerId)
                                     .HtmlAttributes(new { @class = "col-md-6 form-control" })
                                     .Filter("contains")
                                     .DataValueField("Value")
                                     .DataTextField("Text")
                                     .BindTo((IEnumerable<SelectListItem>)Model.ManufacturerSelectList)
                                     .HtmlAttributes(new { style = "width:70%;" }).Events(e =>
                                     {
                                         e.Change("onManufacturerChange");
                                     })
                                     )

                    @Html.LabelFor(m => m.ProductList, "Product", htmlAttributes: new { @class = "control-label col-md-2" })

                        @(Html.Kendo().MultiSelectFor(m => m.ServiceBulletinItem.ApplicableProducts)
                              .AutoClose(false)
                              .DataTextField("ProductName")
                              .DataValueField("ProductId")
                              .Placeholder("Select products...")

                        )

I'm trying to populate the manufacturer drop down and the Product multiSelect.     The ApplicableProducts item is an IEnumerable representing the ProductId's of all those previously selected and I know that when I select the manufacturer and it calls the GetCascadeProducts controller method it will return back a collection of ProductId and ProductName for all the manufacturers products of which those productId is the ApplicableProducts property should exist.
On document.ready I can call the InitialPopulate method with the manufacturerID which will populate the multiSelect items but can't seem to populate the initial values.

A: I couldnt get the binding working correctly so ended up using
                    @(Html.Kendo().MultiSelect()
                              .Name("ServiceBulletinItem_ApplicableProducts")
                              .AutoClose(false)
                              .DataTextField("ProductName")
                              .DataValueField("ProductId")
                              .Placeholder("Select products 2...")
                              .AutoBind(false)
                            )

and then on the using the following code on document ready to make an ajax call to populate the manufacturer and product controls
function PopulateProductsInitial(manId) {
                    $.post("@Url.Action("GetCascadeProducts", "Components")", { manufacturerId: manId }, function (result) {

                        var grid = $("#ServiceBulletinItem_ApplicableProducts").data("kendoMultiSelect")
                        grid.setDataSource(result);

                        var s = $("#ServiceBulletinItem_Id").val();

                        $.post("@Url.Action("GetSBProducts", "ServiceBulletins")", { Id: s}, function (result) {
                            var arr = [];
                            result.forEach(function (element) {
                                arr.push(element.ProductId);
                            });

                            var grid = $("#ServiceBulletinItem_ApplicableProducts").data("kendoMultiSelect")
                            grid.value(arr);
                        });

                });
                }
                }

                $(document).ready(function () {

                    //Populate Initial Values
                    PopulateProductsInitial($("#ServiceBulletinItem_ManufacturerId").val());
                    $('#YourButton').click(SendForm);

                });

The problem then became sending the selected items back to the controller when the edit was complete which again seemed convoluted because the control was not bound and therefore I had to make an Ajax call to submit the data.
function SendForm() {
                    var items = $("#ServiceBulletinItem_ApplicableProducts").data("kendoMultiSelect").value();

                    //Manipulate into ServiceBulletinViewModel for the save
                    var data = {
                                 Id: $("#ServiceBulletinItem_Id").val(),
                                 ServiceBulletinItem: {
                                     Id: $("#ServiceBulletinItem_Id").val(),
                                     ManufacturerId: $("#ServiceBulletinItem_ManufacturerId").val(),
                                     IssueDate: $('#ServiceBulletinItem_IssueDate').val(),
                                     Heading: $('#ServiceBulletinItem_Heading').val(),
                                     Details: $('#ServiceBulletinItem_Details').val(),
                                     Url: $('#ServiceBulletinItem_Url').val(),
                                     SelectedProducts: items
                                 }
                                }

                    $.ajax({
                        type: 'POST',
                        url: '/ServiceBulletins/Edit',
                        contentType: 'application/json',
                        data: JSON.stringify(data),
                        success: function (result) {
                            //Your success code here..
                            if (result.redirectUrl != null) {
                                window.location = result.redirectUrl;
                            }
                        },
                        error: function (jqXHR) {
                            if (jqXHR.status === 200) {
                                alert("Value Not found");
                            }
                        }
                    });
                }

It all seemed a lot more convoluted than any of the demo's that teleriks and I couldnt find any good examples of binding from remote sources which looked similar.
As the binding is convention based I'm wondering if its possible to simplify the ajax calling for the post functionality with the correct naming of the controls so that I can simply get the selected items on the multiselect control or if the ajax post is the way to go.


text:
Q: Error during playing with keras example pretrained_word_embeddings I'am trying to modify the keras example pretrained_word_embeddings that is available here and I faced the following issue : if I decreased MAX_SEQUENCE_LENGTH varibae for example to 95 value I would get the following error:

Traceback (most recent call last):   File "C:\Program
  Files\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py",
  line 670, in _call_cpp_shape_fn_impl
      status)   File "C:\Program Files\Anaconda3\lib\contextlib.py", line 66, in exit
      next(self.gen)   File "C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\framework\errors_impl.py",
  line 469, in raise_exception_on_not_ok_status
      pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: Negative
  dimension size caused by subtracting 5 from 2 for 'Conv2D_2' (op:
  'Conv2D') with input shapes: [?,2,1,128], [5,1,128,128].

I need to change it in case when I for example need to work with small messages like tweets. I use a Tensorflow backend.
Please, help me to clarify
1) What is the problem with MAX_SEQUENCE_LENGTH?
2) What is the reason that Conv2D_2 is in trace instead of Conv1D that I'am using in the model.

A: Let's go through network definition and analyse the shapes of layer outputs when MAX_SEQUENCE_LENGTH=95:
sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')
embedded_sequences = embedding_layer(sequence_input)
# Output shape: (95, EMBEDDING_DIM)
x = Conv1D(128, 5, activation='relu')(embedded_sequences)
# Output shape: (91, 128) (because of valid border mode)
x = MaxPooling1D(5)(x)
# Output shape: (18, 128)
x = Conv1D(128, 5, activation='relu')(x)
# Output shape: (14, 128)
x = MaxPooling1D(5)(x)
# Output shape: (2, 128)
x = Conv1D(128, 5, activation='relu')(x)
# Output shape: (2 - 4??, 128) - PROBLEM!!
x = MaxPooling1D(35)(x) # In the easiest way - change 35 to 2.
x = Flatten()(x)
x = Dense(128, activation='relu')(x)
preds = Dense(100, activation='softmax')(x)

As you may see the problem lies in the last Conv1D layer where there is not enough dimension to apply convolution with a valid border mode. There are many ways how you could solve that. The easiest one is to crop the last Conv-MaxPool duo and change the network definition to:
sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')
embedded_sequences = embedding_layer(sequence_input)
# Output shape: (95, EMBEDDING_DIM)
x = Conv1D(128, 5, activation='relu')(embedded_sequences)
# Output shape: (91, 128) (because of valid border mode)
x = MaxPooling1D(5)(x)
# Output shape: (18, 128)
x = Conv1D(128, 5, activation='relu')(x)
# Output shape: (14, 128)
x = MaxPooling1D(5)(x)
# Output shape: (2, 128)
x = Flatten()(x) # Here - everything is ok.
x = Dense(128, activation='relu')(x)
preds = Dense(100, activation='softmax')(x)

Of course - there are more way to do this (like playing with pooling size, etc.).
The reason behind using Conv2D comes from the fact that in case of TensorFlow backend a Conv1D are implemented by a two dimensional convolutions with one dimension squeezed to have a size of 1.


text: Q: This changes when called by different functions? Javascript closure I'm only started to understand closures when suddenly it throws me another curveball, making my understanding of the scoping in closures even worse. I have a relatively simple closure just so I can get jQuery working inside of an object, which is then called by event handlers outside.


text:
Q: Get Values Line By Line in File_GET_CONTENT Let Suuppoe i am getting Text from another site is as follow
EXCHANGE DATA
INSTA_OPEN_MINUTE=595
INSTA_CLOSE_MINUTE=930
INSTA=86400
COLUMNS=DATE,CLOSE,HIGH,LOW,OPEN,VOLUME
DATA=
TIMEZONE_OFFSET=330
a1517911200,34195.94,34521.01,33482.81,33753.78,0
1,34082.71,34666.33,34008.42,34563.3,0
2,34413.16,34634.35,34108.76,34208.11,0
3,34005.76,34070.73,33849.65,34002.45,0
6,34300.47,34351.34,34115.12,34203.34,0
8,34155.95,34473.43,34028.68,34436.98,0

I am getting text by
$googleFile = file_get_contents("https://www.somewebsite.com/data/getdata?q=PRODUCTDATA");

So now i Want to Store Each line in New php Variable So How can i achive this. i find it on google but not valid resource found so how can i seperate all data?


text:
Q: row labels are missing on new page RDLC reports I have RDLC report on which I have multiple rows for every employee, I hides employee names after 1st row, right!
Now I have a issue when same employee's rows goes to next page it shows widowed records (without employee name).
To hide employee name on next rows I am using this code:

=IIF(Fields!Name.Value <> Previous(Fields!Name.Value), Fields!Name.Value, nothing)

I also tried adding new group, and got rank from stored procedure, but nothing helps.
Is there any way to get that if the row is 1st row of page?
Or any other way to achieve the same?
Thanks in advance

A: Finally I Resolved this issue by 1st adding group on top level with this formula
=CEILING(RowNumber(Nothing)/50)
and in the text box this group returns me row number according to each page, So,I updated my formula for text box to:
=IIF(Fields!Name.Value <> Previous(Fields!Name.Value) OR RowNumber("PageRowGroup")=1, Fields!Name.Value, nothing)


text:
Q: Using withTracker() for Google Analytics on render() - React I am having a hard time figuring out how to implement the react-ga withTracker() HOC with my RegisterContainer setup. I need a RegisterContainer to prevent an alert from triggering on registration and I definitely want to be tracking the register page for analytics, but I cannot get both parts working together. Here is the post I followed on needing a container. How do I track the register page while also using the RegisterContainer?
routes.js:
import React from 'react'
import { Route, Switch, withRouter, Redirect } from "react-router-dom";
import { toast } from "react-toastify"
import withTracker from './components/WithTracker';

// Routes
import Home from "./components/pages/Home";
import SignIn from "./components/pages/SignIn";
import SigningIn from './components/pages/SigningIn';
import RegisterContainer from './components/RegisterContainer'

export class Routes extends React.PureComponent {
    render() {
        return (
            <Switch>
                {/* Visitor */}
                <Route path="/" exact component={withTracker(() => <Home user={this.props.user} />)} />
                <VisitorRoute
                    path="/sign-in"
                    loggedIn={this.props.user}
                    component={withTracker(SignIn)} />
                {/* ** Currently not tracking Register page because of the container */}
                <Route path="/register/:email?" render={() => <RegisterContainer user={this.props.user} />} />
                <Route path="/signing-in" component={withTracker(() => <SigningIn user={this.props.user} loading={this.props.loading} />) } />
            </Switch>
        );
    }
}

  // Must be signed out to view
  const VisitorRoute = ({ component: Comp, loggedIn, path, ...rest }) => {
    return (
      <Route
        path={path}
        {...rest}
        render={props => {
          return loggedIn ? (
            <Route
              render={() => (
                <>
                  {toast.warn("You must be signed out to visit that page.")}
                  <Redirect to="/profile" />
                </>
              )}
            />
          ) : (
            <Comp {...props} />
          );
        }}
      />
    );
  };

export default withRouter(Routes);

RegisterContainer.js:
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom';
import Register from "./pages/Register";
import { toast } from "react-toastify";

class RegisterContainer extends Component {
    constructor(props) {
        super(props)

        if (props.user) {
          toast.warn("You must be signed out to visit that page.")
          props.history.push('/profile')
        }
      }

      render() {
        return <Register />;
      }
}

export default withRouter(RegisterContainer)


text:
Q: Unable to set top margin NSLayout Constraint programatically in iOS? I am trying to set the top margin constraint but it does not work.I have custom cell in which i have two labels.I want to give top spacing dynamic at run time between labels so I have set a constraint of top margin & i have also made outlet of it & using below code to update the top margin.
 self.view.translatesAutoresizingMaskIntoConstraints = NO;
            self.customCell.nslc_first_comment_margin.constant=-21;
            [self.customCell.first_comment layoutIfNeeded];

Please tell how to solve this problem?
EDIT:
This code works if write the code inside the cellForRowAtIndexPath but this does not work under heightForRowAtIndexPath?Can anyone please tell the exact reason for this behaviour.


text:
Q: I select multiple Elements when I click, now I want only one of them (click function similar to the inspector from the browser) I have currently a jquery selector on $("body *") so that I get the clicked elements of the page when I click somewhere. And I am also aware why I get more than 1 Element returned. (For example: If I click on a Button, also all parent Elements have the Click Event and are getting fired).
My Problem: I want a click function like the Inspector has. I only want the Element that I meant to click on. And when I watched the log, where I output all clicked elements, I noticed that the element, I wanted to click, is always the first that gets written in the console. So my first idea is now to just get rid of all elements except the first one but I don't know how to separate these. How can I access and edit/delete all clicked elements from $(this)?
Or is there another and better way to get the clicked element?
Code and Image:
$("body *").click(function (e) {
    console.log($(this));
});

Now all Elements from the image up the tree get written in the console.

A: I just found the solution. In my click function I can just say e.stopPropagation to prevent jquery to walk up the tree/dom and fire also on the parents.
full solution:
$("body *").click(function (e) {
    e.stopPropagation();
    console.log($(this));
});

Edit: Another Solution showed Pango. Instead of giving every Element on the page an EventListener you can give just the body Element an EventListener and then look after the target of the event. This will return you the correct clicked element.
$('body').on('click', function(e) {
    console.log(e.target); // target
    console.log($(this)); // body
});

This is a much cleaner solution because of only one EventListener. This is really important when you want to remove these without affecting eventListeners from other scripts. In my case, I have a toggle button that will activate an element-highlighter (like the from the inspector) with wich I can click on an element and then compare it to another one. So I need to deactivate/delete those listeners when I am done with selecting 2 elements. With this solution, it is much easier.

A: I think you are looking for event.target which is the element that was actually clicked.
Edit:
$('body').on('click', function(e) {
    console.log(e.target); // target
    console.log($(this)); // body
});

That code will attach a click event handler to the body. The event will only fire once, rather than once per parent as was happening with the 'body *' selector. Then, you can use $(e.target) to get what was actually clicked on and $(this) will be the body and no extra parent elements will need to be dealt with.


text:
Q: vb.net Read Craigslist Data Hello I was reading a few articles on how to get data from websites reading the websites source code. With that said I created a Routine to get Craigslist Data for computer gigs for New York and Pittsburgh as shown below. For some reason(could be my lack of knowledge in this area) I only receive 25 records each for both Pittsburgh and NewYork. Is it possible to get the whole listing for today or maybe  even a data range
Friend Shared Function GetCraigslist() As DataTable

    Dim dt As New DataTable
    dt.Columns.Add("description")
    dt.Columns.Add("Title")
    dt.Columns.Add("link")

    Dim XMLDoc As System.Xml.XmlDocument = New System.Xml.XmlDocument
    Dim list As New List(Of String)
    list.Add("https://pittsburgh.craigslist.org/cpg/index.rss")
    list.Add("http://newyork.craigslist.org/cpg/index.rss")

    For Each link In list

        XMLDoc.Load(link)
        Dim nTable As NameTable = XMLDoc.NameTable
        Dim nsManager As XmlNamespaceManager = New XmlNamespaceManager(nTable)

        nsManager.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
        nsManager.AddNamespace("item", "http://purl.org/rss/1.0/")
        nsManager.AddNamespace("dc", "http://purl.org/dc/elements/1.1/")
        Dim XMLItems As System.Xml.XmlNodeList = XMLDoc.DocumentElement.SelectNodes("//rdf:RDF/item:item", nsManager)

        XMLDoc.Save("C:\development\data.xml")
        For Each currentItem As Xml.XmlNode In XMLItems
            Dim R As DataRow = dt.NewRow
            R("Title") &= currentItem.SelectSingleNode("item:title", nsManager).InnerText
            R("description") &= currentItem.SelectSingleNode("item:description", nsManager).InnerText
            R("link") &= currentItem.SelectSingleNode("item:link", nsManager).InnerText
            dt.Rows.Add(R)
        Next
    Next

    Return dt

End Function


text:
Q: Assigning story points to the hypothesis in the backlog We have been using Scrum as our project management platform for a while, now we are moving toward Lean UX and hypothesis driven development practices. We are using Poker planning to determine the effort needed to deliver the outcome.
We have decided to use Barry O'reily's proposition of including both user stories and hypothesis in our backlog and based on Lean UX proposed approach by Jeff Gothelf all the efforts are going to be handled through the development team effort. In order to do that we need to be able to assign a story point to hypothesis as well.
Given that Poker planning is a comparison based measurement, what would be the right approach to assign story points to the hypothesis effort?
P.S. Based on what we learned from Lean concepts we are determined to move all the development efforts into our sprints, moreover, we are open to any ideas related to "#NoEstimates" movement.

A: There is nothing about story points or scrum that makes assigning story points to something impossible or even difficult, unless you have massively altered the definitions within your own process. Story points are an estimate based on complexity, with only a vague relation to time. In most times story points eventually become more time based which makes assigning them to any arbitrary story or issue easier. Second, there is the misunderstanding of what is meant by a sprint being able to deliver a shippable product at the end of every sprint. Stories and sprints are intended to deliver units of value to the product owner, this is commonly misinterpreted as working code for every story. In the case of hypothesis driven development the yes or no is the valuable part, stories should work towards how to get that yes/no, and what to do with a yes/no. There isn't a need to write or estimate stories to fully develop and implement a hypothesis until you've tested it, and at that point you should have sufficient insight to deliver reasonable estimates. It's even possible and useful to have stories that have an output of other stories.
It sounds like you are in a common pitfall of having a separate requirements gathering, getting a bunch of things written up, and now trying to throw it over the wall to the development team. This is a waterfall mentality that is hard to break, a preferable alternative is to have stories that involve parts of your development team to help take the idea and turn it into stories and requirements. If you already have a lot of things the best solution is to write it up in a logical story breakdown (as a first pass) and use some backlog grooming time to restructure and flesh out the initial stories.
As for how a product owner would prioritize these items, it becomes straightforward once they get written up as features/epics/stories. It becomes a simple question of is knowing  if hypothesis A is worth pursuing is more or less important than new feature B or bug fix C. If hypothesis D is a complete unknown on how hard designing an following a test will be, then make a story to find out and prioritize that. Adding "what do I want to know" to sprint planning processes can be a helpful way to get a lot of valuable user stories that aren't really development work, but are often more useful.

A: I am not an expert on hypothesis-driven development, but have some knowledge of it. Here are a few things I would consider:

*

*The full realization of a hypothesis may take varying amounts of time. This may be problematic in a timebox of sprints where the work may be done but the experiment needs time to prove out. Of course, we can mitigate this with small experiments and with truly continuous deployment cycles, but it's at least a risk to acknowledge.

*The process is inherently open-ended. You don't know you are done with the work until the condition is met. Let's say you have an item that "We believe that reducing the complexity of the sign-in form will make it less daunting and increase the rate of sign-up completion. We will know it succeeded if the completion rate of started signups increases from 10% to 30%." Now you do the work and over the next period it increases to 23%. You made positive progress, but you didn't quite get there. Do you call it good enough? Do you go back and simplify the process more to see if you can get that last 7%? This is a conversation that your teams and organizations will have to get very good at.

*As with any open-ended item, there is a risk that you keep pouring work into it without getting benefit. Practices like Spikes in XP have this same problem and they address it with task-based timeboxes instead of points. A task-based timebox really just defines how long we're willing to spend on a particular problem before we should regroup and decide if it's really worth spending more time. So, if you use the example I gave above, we might decide that we are definitely ok spending 16 hours simplifying the page. After that, we want to look at the results and see if it's worth spending more time.

*A final thought: don't over-commit yourself to just one way of framing work. The idea of hypothesis-driven development is really powerful. So are user stories. So are many other ways of working. Every team I worked with was better off for choosing the framing that best fit that particular effort rather than sticking to only one approach.


text:
Q: Generate file with dynamic content with Terragrunt I'm really new to Terragrunt.
I was wondering if there is a way to dynamically generate the content of a file?
For example, consider the following piece of code:
generate "provider" {
    path      = "provider.tf"
    if_exists = "overwrite"
    contents = <<EOF
terraform {
 required_providers {
    azurerm = {
      source = "azurerm"
      version = "=2.49.0"
    }
  }
}

provider "azurerm" {
  features {}
  subscription_id = "xxxxxxxxxxxxxxxxx"
}
EOF
}

Is there a way to set values such as subscription_id dynamically? I've tried using something like ${local.providers.subscription_id} but it doesn't work:
provider "azurerm" {
  features {}
  subscription_id = "${local.providers.subscription_id}"
}

A: What you have there should work exactly as is, so long as you define the local in the same scope. Just tested the following with Terragrunt v0.28.24.
In common.hcl, a file located in some parent directory (but still in the same Git repo):
locals {
  providers = {
    subscription_id = "foo"
  }
}

In your terragrunt.hcl:
locals {
  common_vars = read_terragrunt_config(find_in_parent_folders("common.hcl"))
}

generate "provider" {
  path      = "provider.tf"
  if_exists = "overwrite"
  contents  = <<EOF
terraform {
 required_providers {
    azurerm = {
      source = "azurerm"
      version = "=2.49.0"
    }
  }
}

provider "azurerm" {
  features {}
  subscription_id = "${local.common_vars.locals.providers.subscription_id}"
}
EOF
}

After I run terragrunt init, the provider.tf is generated with the expected contents:
provider "azurerm" {
  features {}
  subscription_id = "foo"
}


text:
Q: Is there an effective way to see why a batch file crashes? Every time there is an error with my code and I want to better understand what I did wrong, I turn @echo on. When your batch file crashes though, it obviously isn't able to display the issues since the command prompt screen crashes. Is there a way to view why it crashed, or at least showing there was a undefined variable or something along those lines?

A: If you open the command prompt manually (win-R and type cmd) and cd over to the .bat file location and run it there instead of double clicking from the file explorer, the command prompt window wont close when .bat finishes and you can see the error message


text:
Q: Is there some way a user with an asterisk as password in /etc/shadow but a correct login shell in /etc/passwd would be able to login via SSH? Let's assume the following. We have a server which is accessible via SSH. There is an user in /etc/passwd who has a valid login shell (so for example /bin/bash, instead of an invalid one like /bin/false).
This user has an asterisk (*) in the second (password) field of /etc/shadow. Is there some way that this user could login via SSH if he doesn't have a ssh key in his ~/.ssh/ folder?
Or, to rephrase the question somewhat: What would be the reason for many online guides to recommend to disable the login shell, when there is a * in the password field of /etc/shadow?

A: A * in the location of the hashed password in /etc/shadow effectively disables all password based logins as no user input will ever result in a hash value of *. But the user can still login with his/her ssh keys.
The difference of using * instead of using an exclamation mark ! is that the latter indicates a locked account in PAM, which, depending on your sshd configuration, will disable key based logins too.
The reason to set an invalid shell is simply to prevent interactive login sessions from working (regardless of whether of not a password for the account is set) and will block sudo su - user and similar from working.


text:
Q: $\int_{0}^{\infty}\frac{x}{x^3+1}dx$ =? So guys I have this improper integral $\int_{0}^{\infty}\frac{x}{x^3+1}dx$. I checked that it converges by $ \int_{0}^{1}\frac{x}{x^3+1}dx + \int_{1}^{\infty}\frac{x}{x^3+1}dx $ and using the $\frac{c}{(x-a)^\lambda}  $ and $\frac{1}{x^\lambda} $ criteria. But for finding the value I have trouble.I tried $ \int_{0}^{\infty}\frac{x}{(x+1)(x^2-x+1)}dx$ and $\int_{0}^{\frac{\pi}{2}}\frac{tg\alpha}{tg\alpha^3+1}dx$ but it gets me nowhere. Any ideas on solving it?

A: One thing that simplifies the computation is splitting the integral and substituting $y = x^{-1}$ in one part:
$$\begin{align}
\int_0^\infty \frac{x}{x^3+1}\,dx &= \int_0^1\frac{x}{x^3+1}\,dx + \int_1^\infty \frac{x}{x^3+1}\,dx\\
&= \int_0^1 \frac{x}{x^3+1}\,dx + \int_1^0 \frac{y^{-1}}{y^{-3}+1}\,d(y^{-1})\\
&= \int_0^1 \frac{x}{x^3+1}\,dx + \int_0^1 \frac{1}{y^3+1}\,dy\\
&= \int_0^1 \frac{dx}{x^2 -x+1}.
\end{align}$$
This can be seen to be related to an $\arctan$.

A: Continuing Daniel Fischer's answer, we have:
$$\int_{0}^{1}\frac{dx}{x^2-x+1}=\int_{-1/2}^{1/2}\frac{dx}{x^2+3/4}=\frac{\sqrt{3}}{2}\cdot\frac{4}{3}\int_{-1/\sqrt{3}}^{1/\sqrt{3}}\frac{dx}{x^2+1}=\frac{4\sqrt{3}}{3}\arctan\frac{1}{\sqrt{3}}=\frac{2\pi}{3\sqrt{3}}.$$

A: If $I=\int_{0}^{\infty}\frac{x}{x^3+1}dx$ then $2I=\int_{0}^{\infty}\frac{2x-x^2+x^2}{x^3+1}dx$=$\int_{0}^{\infty}\frac{2x-x^2}{x^3+1}dx$+$\int_{0}^{\infty}\frac{x^2}{x^3+1}dx.$
 The secod itegral is easy and can be solved by substituting $u=x^3+1$. For the first write  $$\int_{0}^{\infty}\frac{2x-x^2}{x^3+1}dx=\int_{0}^{\infty}\frac{(x+1)-(x^2-x+1)}{(x+1)(x^2-x+1)}dx=\int_{0}^{\infty}\frac{1}{x^2-x+1}dx-\int_{0}^{\infty}\frac{1}{x+1}dx$$
but for the $\int_{0}^{\infty}\frac{1}{x^2-x+1}dx$=$\int_{0}^{\infty}\frac{1}{(x-\frac{1}{2})^2+\frac{3}{4}}dx$ which is of the form $\int \frac{1}{u^2+a^2}du=\frac{1}{a}\arctan(\frac{u}{a})+c.$

A: The other answers have already shown elementary methods, so I will just add that we actually have $$ \int_0^{\infty} \frac{x^a \, dx}{1+x^b} = \frac{\pi}{b\sin\left(\frac{\pi(a+1)}{b}\right)}$$ for all $a, b$ such that the integral converges. Unfortunately this is not easy to show without complex analysis. It requires knowledge of the Beta function.


text:
Q: LightInject GetInstance returning that cannot be used with type arguments I'm new to dependency injection and I find LightInject to start.
So I created 2 interfaces and implemented those interfaces into 2 classes. Now, I want to get a instance of Payment but compiler keeps saying that non-generic method 'ServiceContainer.GetInstance(Type) cannot be used with type arguments.
My interfaces are implemented in different files. I tried the way this guys says (Getting Started with LightInject) and works fine. But I think, somehow, as my interfaces and classes are in different files, it's not working i dont know why.
My codes are like this. IContract
namespace ConsoleApp1.Interfaces
{
    public interface IContract
    {
        int Discount();
    }
}

IPayment:
namespace ConsoleApp1.Interfaces
{
    public interface IPayment
    {
        void Pay();
    }
}

CrazyContract:
namespace ConsoleApp1.Classes
{
    public class CrazyContract: IContract
    {
        public int Discount()
        {
            return 3;
        }
    }
}

Payment and more important classe:
namespace ConsoleApp1.Classes
{
    public class Payment: IPayment
    {
        private readonly IContract _contract;

        public Payment(IContract contract)
        {
            _contract = contract;
        }

        public void Pay()
        {
            Console.WriteLine("Discount {0}", _contract.Discount());
        }
    }
}

and my main which returns the error:
using ConsoleApp1.Classes;
using ConsoleApp1.Interfaces;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var container = new LightInject.ServiceContainer();

            container.Register<IPayment, Payment>();
            container.Register<IContract, CrazyContract>();

            var p = container.GetInstance<IPayment>(); // the error is here

        }
    }
}

and the error:
error CS0308: The non-generic method 'ServiceContainer.GetInstance(Type)' cannot be used with type arguments

As you guys can see, I'm using Constructor Injection and I'd be very happy if any of you could explain what I'm doing wrong. Thank you!

A: I find a way to fix the problem.
We should explicitly that we need the package LightInject.
So, just put this code
using LightInject;

I dont really know why but this works


text:
Q: Need query to select min cost and max date I have a table and values like this
create table minmaxtest
(
id int,
mfg varchar(100),
mfgid varchar(100),
[Desc] varchar(100),
po_date date,
cost money
)

insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (1,'abc','123','catheter','09/30/15',9)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (2,'abc','123','catheter','09/30/15',10)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (3,'abc','123','catheter','09/28/15',8)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (4,'abc','123','catheter','09/28/15',20)

insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (5,'xyz','666','stent','09/30/15',9)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (6,'xyz','666','stent','09/30/15',10)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (7,'xyz','666','stent','09/28/15',8)
insert into minmaxtest(id,mfg,mfgid,[Desc],po_date,cost) Values (8,'xyz','666','stent','09/28/15',20)

I need to get the max po_date and min cost as shown in the figure
i tried like this but not getting proper value , Any help would be greatly appreciated.
My code :
*select * from minmaxtest where po_date in(select max(po_date) from minmaxtest)
and cost in (select min(cost) from minmaxtest)*

A: Try this
;with cte
as
(
SELECT
    SequenceId = ROW_NUMBER() OVER(PARTITION BY mfg ORDER BY id),
    id,
    mfg,
    mfgid,
    [Desc],
    po_date = MAX(PO_Date) OVER(PARTITION BY mfgid),
    cost = MIN(cost) OVER(PARTITION BY mfgid,po_date)
FROM minmaxtest
)
select
    *
    from cte
       where SequenceId = 1

My Result

A:
;with cte
as
(
SELECT
    ROW_NUMBER() OVER(partition by mfg ORDER BY po_date desc, cost asc) as RN,
    id,
    mfg,
    mfgid,
    [Desc],
    po_date ,
    cost
FROM minmaxtest
)
select
    id,
    mfg as Productmanufacturer,
    mfgid,
    [Desc] as ProductDescription,
    po_date ,
    cost
    from cte
       where RN = 1

Output:


text:
Q: unwanted margin appearing out of nowhere, despite being set to 0

If I hover over the element in the dev panel, it shows an orange highlight over the margin making up the difference between the field above and the field below.  I can't capture that in a screenshot because of the way the VM I am developing on is set up, but please trust me that it is there.  However, on the 2nd image, you can see margin is set at 0 and the rule is being used, and to the right it shows the right margin as being - (meaning none).  How can I get rid of this margin?  It is driving me crazy, I've been playing around with the rules on the input and the element containing it for hours, with no luck.
I can't use the style from the 2nd input to help, because that one actually extends beyond what you can see, having the last 30% of its width covered up, which is what I am trying to get rid of on all my inputs.
The CSS of the input:
border: 2px solid #c7d9e7;
border-bottom: none;
border-radius: 2px;
color: $text-black;
display: flex;
flex-grow: 1;
font-family: 'open_sansregular', sans-serif;
font-size: 1em;
font-weight: normal;
margin: 0;
order: 2;
padding: 2px 5px;
width: auto;

The CSS of the parent element (a span, whose only child element is the input field):
display: block;
overflow: hidden;
position: relative;
text-align: center;

EDIT: My goal is to have the input fill the parent width, which extends as far as the visible edge of the bottom field.

A: tl;dr  Use
input {
   width: 100%;
   box-sizing:border-box;
}

Below, should you be interested, is a full answer of what's happening and why the above solution works.
There's various rules being applied from multiple specifications which we need to bring together.
First of all, let's establish what we're discussing. We have a span, inside of which is a input control.

input {
  border: 2px solid #c7d9e7;
  border-bottom: none;
  border-radius: 2px;
  color: black;
  display: flex;
  flex-grow: 1;
  font-family: 'open_sansregular', sans-serif;
  font-size: 1em;
  font-weight: normal;
  margin: 0;
  order: 2;
  padding: 2px 5px;
  width: auto;
}
span {
  display: block;
  overflow: hidden;
  position: relative;
  text-align: center;
}

  <input type="text">

And I believe that it's the orange box to the right of the input control that you are asking about. You want to know (a) why the orange box has a large width when the box model values shown say it should be 0. And (b) how to reduce this width and use the space available for the input control instead.
The first step is to understand that there are several different value stages for each property. From CSS 2.2, Section 6.1 Specified, computed, and actual values we have the Specified, value, the Computed value, the Used value and the Actual value; and from the CSSOM specification we also have the Resolved Value
What you write in the stylesheet is the Specified value. input { margin-right:0; } means that the specified value of margin-right property of the input element is zero.
The value you see in the box model depiction is the Computed value. In this case, that's also zero.
The orange box is showing you the width of the Used value - or the Resolved value which for margin properties on visible elements is the same as the Used value.
So part (a) of the question becomes: why is the Used value different from the Computed value?
You have made the input element display:flex. This makes the element block-level.

'flex'
   This value causes an element to generate a block-level flex container box.

Also in the HTML5 spec, Rendering section Section 10.5.4. The input element as a text entry widget. it says:

If an input element whose type attribute is in one of the above states
  does not have a size attribute, then the user agent is expected to act
  as if it had a user-agent-level style sheet rule setting the width
  property on the element to the value obtained from applying the
  converting a character width to pixels algorithm to the number 20.

So an intrinsic width of about 20 characters is assigned to the input element.
In the CSS 2.2 spec, we can now see how the widths of and around the input element are calculated. First section 10.3.4 Block-level, replaced elements in normal flow applies:

The used value of 'width' is determined as for inline replaced
  elements ...

The used value rule for inline replaced elements is from section 10.3.2 Inline, replaced elements

If 'height' and 'width' both have computed values of 'auto' and the
  element also has an intrinsic width, then that intrinsic width is the
  used value of 'width'.

and we've already established that the intrinsic width is 20 characters.
Section 10.3.4 Block-level, replaced elements in normal flow goes on to say:

.. Then the rules for non-replaced block-level elements are applied to determine the margins.

Which is section 10.3.3 Block-level, non-replaced elements in normal flow and importantly says that for the Used values, this equality MUST hold:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

You've made the span element display:block, so the span element is the containing block element.
None of the Used values within that equality are "auto", so the values are said to be "over-constrained". That means that to make the equality hold, at least one of Used values must be different from the Computed value. The section goes on to say that:

... the specified value of 'margin-right' is ignored and the [Used] value is calculated so as to make the equality true ...

So that calculated margin-right value is what you see depicted as the Orange box.
Now we can see how to fix it. All we have to do is to stop the equality from adjusting the Used margin-right value by setting the content-box width of the input box to the full width of the span, less the padding and borders. Then the Used values of the margins will be 0. For that we use
input {
   width: 100%;
   box-sizing:border-box;
}

or
input {
   width: calc(100% - 14px);
}

input {
  border: 2px solid #c7d9e7;
  border-bottom: none;
  border-radius: 2px;
  color: black;
  display: flex;
  flex-grow: 1;
  font-family: 'open_sansregular', sans-serif;
  font-size: 1em;
  font-weight: normal;
  margin: 0;
  order: 2;
  padding: 2px 5px;
  width: 100%;
  box-sizing:border-box;
}
span {
  display: block;
  overflow: hidden;
  position: relative;
  text-align: center;
}

  <input type="text">

A: For me it was something much much simpler:
I had a max-width attribute specified on the inner element somewhere above in the CSS tree that I forgot to check.
So make sure your child element, in the asker's case the <input> element doesn't inherit a max-width from somewhere else.


text:
Q: Concatenate the rows based on number (Google Refine, Excel/Google Spreadsheet) I have large amount of rows on a csv file, which look like:
name a,1
name b,1
name c,1
name d,2
name e,2

I need to concatenate the rows based on number. Result should be:
name a|name b|name c
name d|name e

How can I do it in Google Refine or in Excel/Google Spreadsheet?
I am thinking of it, but with no solution.
Thank you a lot!

A: If you can use Python it would be pretty easy to do this manipulation. In the the code below, the name and group are read from "input.csv", and the grouped names (along with the group) are written to "output.csv". A defaultdict is used to create empty lists to store the group members.
import collections
import csv

grouped = collections.defaultdict(list)
with open('input.csv') as fp:
    reader = csv.reader(fp)
    for row in reader:
        name, group = row
        grouped[group].append(name)

with open('output.csv', 'w', newline='') as fp:
    writer = csv.writer(fp, delimiter='|')
    for key in sorted(grouped.keys()):
        writer.writerow([key] + grouped[key])

A: Here is a proposal with Open refine. The only Grel formula i used is:
row.record.cells['myColumn'].value.join('|')

screencast
And here is the JSOn, assuming that your first column is named "myColumn" and the second "number" :
[
  {
    "op": "core/column-addition",
    "description": "Create column test at index 2 based on column number using expression grel:value",
    "engineConfig": {
      "mode": "row-based",
      "facets": [
        {
          "omitError": false,
          "expression": "isBlank(value)",
          "selectBlank": false,
          "selection": [
            {
              "v": {
                "v": false,
                "l": "false"
              }
            }
          ],
          "selectError": false,
          "invert": false,
          "name": "ee",
          "omitBlank": false,
          "type": "list",
          "columnName": "ee"
        }
      ]
    },
    "newColumnName": "test",
    "columnInsertIndex": 2,
    "baseColumnName": "number",
    "expression": "grel:value",
    "onError": "set-to-blank"
  },
  {
    "op": "core/column-move",
    "description": "Move column test to position 0",
    "columnName": "test",
    "index": 0
  },
  {
    "op": "core/blank-down",
    "description": "Blank down cells in column test",
    "engineConfig": {
      "mode": "row-based",
      "facets": [
        {
          "omitError": false,
          "expression": "isBlank(value)",
          "selectBlank": false,
          "selection": [
            {
              "v": {
                "v": false,
                "l": "false"
              }
            }
          ],
          "selectError": false,
          "invert": false,
          "name": "ee",
          "omitBlank": false,
          "type": "list",
          "columnName": "ee"
        }
      ]
    },
    "columnName": "test"
  },
  {
    "op": "core/column-addition",
    "description": "Create column concatenation at index 2 based on column myColumn using expression grel:row.record.cells['myColumn'].value.join('|')",
    "engineConfig": {
      "mode": "row-based",
      "facets": [
        {
          "omitError": false,
          "expression": "isBlank(value)",
          "selectBlank": false,
          "selection": [
            {
              "v": {
                "v": false,
                "l": "false"
              }
            }
          ],
          "selectError": false,
          "invert": false,
          "name": "ee",
          "omitBlank": false,
          "type": "list",
          "columnName": "ee"
        }
      ]
    },
    "newColumnName": "concatenation",
    "columnInsertIndex": 2,
    "baseColumnName": "myColumn",
    "expression": "grel:row.record.cells['myColumn'].value.join('|')",
    "onError": "set-to-blank"
  }
]


text:
Q: Is there a way to run a selenium web scraper on a synology nas server I built a web scraper with Selenium using Geckodriver for Linux64. The program clicks on a download link for an Excel file and downloads this file (automatically, without asking to save). This works fine on my 64-bit Ubuntu laptop.
My goal is to run this program on my Synology NAS server:
>uname -a
Linux name_of_nas 4.4.59+ #25556 SMP Thu Mar 4 17:52:53 CST 2021 aarch64 GNU/Linux synology_rtd1296_ds218play

The problem I encountered is that Geckodriver acts as a link between Selenium and the Firefox webbrowser. This would mean that I have to have the Firefox webbrowser installed on my NAS. I don't see how this can be achieved. The Geckodriver I installed on my NAS can be found here. This Geckodriver seems to be working, because the error I get when running my program is:
RuntimeError: Could not find firefox in your system PATH. Please specify the firefox binary location or install firefox

Other versions of the Geckodriver would give me the error:
OSError: [Errno 8] Exec format error: 'geckodriver'

Is there a way to download Firefox on my NAS to get this working? Or perhaps there is another way to achieve my goal?
Code of my test web scraper:
url = 'https://file-examples.com/index.php/sample-documents-download/sample-xls-download/'

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
options = Options()
options.add_argument('--headless')
profile = FirefoxProfile()

profile.set_preference("browser.download.dir", "/volume1/NAS storage/Jens/NAS_programs/qteam_scraper/data/")
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.helperApps.alwaysAsk.force", False)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.ms-excel")

cap = DesiredCapabilities().FIREFOX
cap["marionette"] = False

# Problem: geckodriver is a link between selenium and your firefox browser -> I need to have firefox installed on NAS server
driver = webdriver.Firefox(firefox_profile=profile, options=options, capabilities=cap) # Automatically uses geckodriver in /usr/local/bin/
driver.get(url)

driver.find_element_by_xpath('/html/body/div[1]/main/section/div/div[2]/div/div/table/tbody/tr[1]/td[5]/a[1]').click()

driver.quit()


text:
Q: vue with parcel does not render correctly The simple process below does not work, though I do not understand why ...
using :
npm
vue
parcel
mkdir samat
cd samat
npm init -y
npm install vue --save

package.json
{
  "name": "samat",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "vue": "^2.6.12"
  }
}

Then I create index.html and index.js:
<!DOCTYPE html>

        {{ message }}

import Vue from 'vue'

var app = new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue!'
    }
  })

Finally, I run parcel index.html, and then look at localhost:1234 but see only this in the browser:
{{message}}

A: To use in-DOM templates (i.e., the
{{ message }}
), import the full build of Vue that includes the runtime template compiler:
// import Vue from 'vue'
import Vue from 'vue/dist/vue.esm.browser' // full build