text:
Q: How to create this Neural Network in jupyter notebook and fix the error Getting The Data:
Read all the data in from the candyBar.txt that is included in your download. Store your data in regular python lists named:
x1 which represents if the candy was fruity flavored (1st column), 1 = fruity, 0 = not fruity
x2 which represents if the candy had caramel in it (2nd column) 1 = carmel, 0 = no caramel
x3 which represents if the candy had peanuts/almonds in it (3rd column) 1 = peanuts, 0 = no peanuts
x4 which represents if the candy was in the shape of a bar (4th column) 1 = bar, 0 = no bar
y which respresents if the candy was chocolate or not. 1 = had chocolate, 0 = did not have chocolate (5th Column)

#Get the Training Data from a file
import os
path = os.getcwd() + '\candyBar.txt'

x1=[]
x2=[]
x3=[]
x4=[]
y=[]
file = open(path,"r")
while True:
line = file.readline()
if not line:
    break
else:
    values = line.split(",")
    x1.append(float(values[0]))
    x2.append(float(values[1]))
    x3.append(float(values[2]))
    x4.append(float(values[3]))
    y.append(float(values[4].rstrip("\n")))
    file.close()

Get the size of the data set using the len(listName) function
  m = len(x1)

Convert the x1, x2, x3, x4 data to a np array using np.array(listName)
 #---------------FILL IN THE MISSING CODE----------------------
 x1 =  np.array(x1)
 x2 =  np.array(x2)
 x3 =  np.array(x3)
 x4 =  np.array(x4)

Combine them together using np.column_stack((col1Name, col2Name, col3Name, col4Name)). The ones are first, then x1, then x2, then x3, then x4
   #---------------FILL IN THE MISSING CODE----------------------
   x = np.column_stack((x1,x2,x3,x4))
   print(x)

Convert the y data to the transpose of a np array (Needed for the matrix multiplication that the functions do)
Use np.array([listName]).T
#---------------FILL IN THE MISSING CODE----------------------

y = np.array([y]).T
print(y)

Split the data set into a training data set and a test data set.
Use the first 60 values (0->60) from the data set to train, and the remainder to test on (60 ->m)
Use listName[startValue:EndValue]
#---------------FILL IN THE MISSING CODE----------------------

xTrain = x[0:60]
yTrain = y[0:60]
xTest =  x[60:m]
yTest =  y[60:m]

Set the parameters of the neural network
We need to specify how many input nodes, output nodes exist and how many nodes we wish to use in the hidden layer.
In the data set there are 4 inputs
In the data set there is 1 output
Let's use 3 nodes in hidden layer (You can pick anything, but beware of over and underfitting)
#---------------FILL IN THE MISSING CODE----------------------
inputNeurons = model.add(Dense(4,input_dim=3, init='uniform', activation='relu'))
hiddenNeurons = model.add(Dense(3,init='uniform', activation='relu'))
outputNeurons = model.add(Dense(1,init='uniform', activation='sigmoid'))

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1712/1009970142.py in
1 #---------------FILL IN THE MISSING CODE----------------------
----> 2 inputNeurons = model.add(Dense(4,input_dim=3, init='uniform', activation='relu'))
3 hiddenNeurons = model.add(Dense(3,init='uniform', activation='relu'))
4 outputNeurons = model.add(Dense(1,init='uniform', activation='sigmoid'))
NameError: name 'model' is not defined


text:
Q: Using Office 365 for work collaboration on a Chromebook Has anyone tried using Office 365 (Outlook, Word, Excel, Ppt) on a Chromebook?
I do not own a Chromebook. This link shows that I can install and run Office mobile app on a Chromebook. However, OneDrive support is not available.
Here is my guess of a workaround. From Chrome browser, I can download a file from OneDrive to local drive. Then I can edit the file using Office mobile app. Then I can upload the changed file back to OneDrive. This should be doable but very inconvenient.
Or I can just open a file in OneDrve inside the Chrome browser and view/edit with "Office for web". "Office for web" is not a full office so its features are limited.
A similar question was asked eight years ago. Does Office 365 work properly on Ubuntu & Chrome OS?.
I hope the situation has changed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I keep getting segmentation errors when I pass the capitol H flag through the command line, can anyone spot the segmentation error? this is my main class that accepts a h or H command line parsing and should print the contents of a hexidecmal header
#include "p1-check.h"

int main (int argc, char **argv)
{
FILE *file;

elf_hdr_t h;
int c;

while ((c = getopt (argc, argv, ":if:hH")) != -1)
{
switch (c)
{
case 'h':
usage_p1(argv);
break;
case 'H':

file = fopen(optarg, "rb");
read_header(file, &h);
dump_header(h);
fclose(file);
break;
default:
return EXIT_SUCCESS;
break;
}
}
}

I have a program that takes in command line arguments and a path to an elf file and displays the content of them using a struct. The elf header file is set up to have 16 bytes. Of those bytes, every two bytes describes something else about the header (version, entry point, etc) and the last four bytes hold a magic number that tells you it's the end of the file. The bytes are all in hex.
bool read_header (FILE *file, elf_hdr_t *hdr)
{
    if (hdr != NULL && file != NULL && fread(hdr, sizeof(*hdr), 1, file) == 1)
    {
      fread(hdr, sizeof(*hdr), 1, file);
      if (hdr->magic == 0x00464C45)
      {
        return true;
      }
    }
    return false;
}

A: H option isn't followed by : so it doesn't accept an argument.
So optarg is not the elf filename you're expecting but rather a NULL or invalid pointer.
From the man page:

optstring is a string containing the legitimate option characters.
If such a character is followed by a colon, the option requires an
argument, so getopt() places a pointer to the following text in the
same argv-element

And since you're not checking the return value of fopen for NULL (which is probably is, as the file could not be opened), you're invoking undefined behaviour, when you're opening the file or when you're reading a null handle
To enable an argument for H option add a colon:
getopt (argc, argv, ":if:hH:"))

I'd also check how you're reading your elf header, as there are 2 fread calls, one in the test and one inside the condition.


text:
Q: Unable to start Resin application server I have two resin web servers(41,47) in same folder. Actually am changing server version from 47 to 41 when I deployed and started project in 41 its hitting some error like below,
[admin@localhost bin]$ ./resin.sh start;
 Resin/4.0.41 can't start -server 'app-0' for watchdog at 127.0.0.1:6600.
 Unexpected resin.home mismatch:
 CLI resin.home: /home/admin/resin-pro-4.0.41/
 watchdog resin.home: /home/admin/resin-4.0.46/

can anyone help me out this?

A: After hard struggle I got answer for this, moving resin to some other directory will disappear this issue. simple! :)

A: Try to fix resix.xml

<server-multi id-prefix="app-" address-list="${app_servers}" port="6800" watchdog-port="6601"/>


text:
Q: In-depth understanding of binary files I am learning C++ specially about binary file structure/manipulation, and since I am totally new to the subject of binary files, bits, bites  & hexadecimal numbers, I decided to take one step backward and establish a solid understanding on the subjects.
In the picture I have included below, I wrote two words (blue thief) in a .txt file.

The reason for this, is when I decode the file using a hexeditor, I wanted to understand how the information is really stored in hex format. Now, don't get me wrong, I am not trying to make a living out of reading hex formats all day, but only to have a minimum  level of understanding the basics of a binary file's composition. I also, know all files have different structures, but just for the sake of understanding, I wanted to know, how exactly the words "blue thief" and a single ' ' (space) were converted into those characters.
One more thing, is that, I have heard that binary files contain three types of information:
header, ftm & and the data! is that only concerned with multimedia files like audios, videos? because, I can't seem to see anything, other than what it looks like a the data chunk in this file only.

A: The characters in your text file are encoded in a Windows extension of ASCII--one byte for each character that you see in Notepad.  What you see is what you get.
Generally, a hard distinction is made between text and binary files on Windows systems.  On Unix/Linux systems, the distinction is fuzzier... you could argue that there is no distinction, in fact.
On Windows systems, the distinction is enforced by file extensions.  All files with the extension ".TXT" are assumed to be text files (i.e., to contain only hex codes that represent visible onscreen characters, where "visible" includes whitespace).
Binary files are a whole different kettle of fish.  Most, as you mention, include some sort of header describing how the data that follows is encoded.  These headers can vary tremendously in size depending on the type of data (again, assumed to be indicated by the extension on Windows systems as well as Unix).  A simple example is the WAV format for uncompressed audio.  If you open a WAV file in your hex editing program, you'll see that the first four bytes are "RIFF"--this is a marker, often called a "magic number" even though it is readable as text, indicating that the contents are an audio file.  Newer versions of the WAV specification have complicated this somewhat, but originally the WAV header was just the "RIFF" tag plus a dozen or so bytes indicating the sample rate of the following data.  (You can see this by comparing the raw data in a track on an audio CD to the WAV file created by ripping an uncompressed copy of that track at 44.1 KHz--the data should be the same, with just a header section added at the start of the WAV file.)
Executable files (compiled programs) are a special type of binary file, but they follow roughly the same scheme of a header followed by data in a prescribed format.  In this case, though, the "data" is executable machine code, and the header indicates, among other things, what operating system the file runs on.   (For example, most Linux executables begin with the characters "ELF".)


text:
Q: Как получить разность из значений input типа datetime-local в днях и часах? У меня есть две переменные со значениями "2022-03-15T10:39" и "2022-03-12T10:43" нужно получить разность их значений в днях и часах, подскажите как ?

A:

const date1 = dayjs("2022-03-15T10:39");
const date2 = dayjs("2022-03-12T10:43");

const getHumanizedValue = (diffInHours) => {
  const HOURS_IN_DAY = 24;

  const days = Math.floor(diffInHours / HOURS_IN_DAY);
  const hours = diffInHours % HOURS_IN_DAY;

  return `${days} days and ${hours} hours`;
};

console.log(getHumanizedValue(date1.diff(date2, "hour")));
<script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>

Предлагаю воспользоваться библиотекой dayjs. В dayjs можно легко высчитать разницу между датами с помощью метода diff (ссылка на нужный раздел библиотеки: https://day.js.org/docs/en/display/difference)
Так как для вопроса есть метка react, я создал песочницу на react, в которой можно посмотреть на решение изнутри: https://codesandbox.io/s/headless-frost-h87g48?file=/src/App.js


text:
Q: Truncating Environment variable in ubuntu I'm trying to truncate an environment variable in an ubuntu instance using a docker image and its failing. Below I will provide example.
buildNum="$(git rev-parse HEAD)" // this command returns commit hash
build= ${buildNum:0:10} //truncates commit hash to only first 20 chars
export myvar = "${build}"
error: bad substitution ???

The above example works on my regular OSX terminal but when trying to run the same thing in an ubuntu instance I get bad substitution error.

A: Issue is with spaces around = sign
Try removing them.
export myvar="${build}"


text:
Q: CreateProcess() in a client server application in windows I am working on a UDP client-server application where one server is supposed to handle 40 clients which could all be logged on at once.
Now in UNIX, such issues are resolved by using the fork function which basically creates a child process to deal with the client and leaves the server to accept new connections.
I searched on the internet and found out that fork is not available in windows, however CreateProcess could be used.
My previous research also introduced me to thread pools. So now I've two questions:

*

*Could I acheive the functionality of fork() by using CreateProcess() in Windows?

*If this is possible, what should I go for: thread pools or creating multiple processes?

A: 1. Short answer is no, there is nothing like fork() in the Win32 API, but it should be possible to implement it since CygWin provide a fully featured fork() on Windows. But you don't seem to actually need fork()for your application.
2. Actually your options are :

*

*Create at least one thread/process for each client/connexion

*Create only one thread/process for all client/connexion (using an event-driven approach as instance)

*Mix the two above

The best approach depends on your application but for handling a maximum of only 40 simultaneous client, you can very well have one thread per client.
You could use the POSIX standard thread library pthread to create and manipulate threads. This` library is standard in all POSIX-conformant OS (GNU/Linux, Mac OS X, BSD,  etc.) and has been ported to Windows. So this approach would allow you to have a very nice portability.
Although if you want to use the Win32 API, you should take a look at CreateThread.

A: In linux fork function is used to create new process. Also for each process, there are different virtual memory space. For threads, only one common virtual memory is there. Also the the fork API can simulate in Windows (upto some extent) using the native API RtlCloneUserProcess.


text:
Q: Abstract servlet - how to prevent instantiation I want two Java servlets share common init() and destroy() methods as well as initialization parameters. So naturally I delcared abstract servlet public abstract class CommonConnectionServlet extends HttpServlet, implementing mentioned methods. I also added to it a few initialization parameters in web.xml file. The I delcared two servlets extending my abstract servlet. However it doesn't work - glassfish server tries to create CommonConnectionServlet instance what raises an exception and servlets aren't starting.
Can I somehow prevent instantiation of an abstract servlet? Or, is it a bad idea to declare abstract servlet in general?

A: Abstract servlets are fine, you can do that if you like. The problem seems to be that you declared it in the web.xml. Everything declared there (or annotated) as 'servlet' will be instantiated.
First, remove it from the web.xml. Then, if I understand correctly, you want to share some parameters through web.xml. The easiest way would be to create "context parameters" instead of "init-parameters", like this:
<web-app>
    <context-param>
        <param-name>name</param-name>
        <param-value>value</param-value>
    </context-param>
    ...
</web-app>

Then, you'll have to rewrite your abstract servlet to first try GenericServlet.getInitParameter(), but if that returns nothing, then retry ServletContext.getInitParameter().
This way subclassed servlets may override parameters if they need it, but the common shared parameters are used if not.


text:
Q: What is wrong with this concrete example for drawing on a separate thread? The following program draws a little cloud

at the location the user touches.
If you replace /*A*/ with ///*A*/, it runs fine.
But it is sluggish. Hence (without commenting out the /*A*/s) the drawing is done on a separate thread. To maintain a smooth interaction, the thread is interrupted when the user moves the pointer.
How would you modify this code to properly draw on a separate thread?
public class MyView extends View {
/*A*/ protected MyDrawThread myDrawThread;
    protected float x, y;
    protected Paint paint = new Paint();

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint.setAntiAlias(true);
/*A*/   myDrawThread = new MyDrawThread();
    }

    @Override protected void onDraw(Canvas canvas)
    {
/*A*/        if( myDrawThread.isAlive() )
/*A*/            myDrawThread.interrupt();
/*A*/
/*A*/        myDrawThread.setCanvas( canvas );
/*A*/        myDrawThread.start();
/*A*/    }
/*A*/
/*A*/    class MyDrawThread extends Thread {
/*A*/        private Canvas canvas;
/*A*/
/*A*/        public MyDrawThread() {
/*A*/            super();
/*A*/        }
/*A*/        public void setCanvas( Canvas cnvs ) {
/*A*/            canvas = cnvs;
/*A*/        }
/*A*/        public void run()
/*A*/        {
            for(int i=0;i<10000;++i) {
                double angle = (double) (Math.random() * 2.0 * Math.PI);
                float distance = (float) (Math.random() * getWidth()/25.0f);
                float dx = (float) (distance*Math.cos(angle));
                float dy = (float) (distance*Math.sin(angle));
                canvas.drawCircle(x+dx, y+dy, 0.1f, paint);
            }
/*A*/   }
    }
    @Override public boolean onTouchEvent(MotionEvent event) {
        x = event.getX();
        y = event.getY();
        invalidate();
        return true;
    }
}

The layout activity_main consists of just
<.MyView
    android:id="@+id/myView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

and the activity sets the View through
setContentView(R.layout.activity_main);

A: You can't. The Canvas passed to View.onDraw() must only be used from the main thread (UI thread.) You should either use a SurfaceView (which lets you use a Canvas from an arbitrary thread), a TextureView (same thing) or render into an intermediate bitmap.

A: Drawing has to be done on the UI thread in this case. Another thing is I'm pretty sure the drawing can only be safely done inside of onDraw().  Your code is sluggish because you go through a long loop.
So, instead, you will create a separate thread that will generate that image into a Bitmap.  Then sharing that bitmap with the UI thread, you can actually draw that bitmap onto the canvas.  You may need a set of wait() and notify() calls to get the job in a lockstep fashion, however, this might still be too slow being done on another thread. If you really want to make this image that dynamic, I would either
1) Only update the bitmap on the UI every several frames, but you can still generate the image with the other thread
2) Use another method for generating the image that would not have to loop so many times
In best practice, your onDraw() should really be as fast as possible, not doing any intensive work.


text:
Q: C++: incomplete type named in nested name specifier I am trying to resolve a circular dependency in my c++ project and based on other answers here on StackOverflow, I followed the same methodology. However, I am still seeing an issue:
This is my code snippet below:
// In ip6.hh
namespace net
{
    class Inet4;

      /** IP6 layer */
      class IP6
      {
         using Stack = class Inet4;

         void set_packet_forwarding(Stack::Forward_delg fwd)
         { forward_packet_ = fwd; }

         Stack& stack_;
     }
}

// In Inet4.hpp
#include "ip6/ip6.hpp"
namespace net {

  class Inet4 : public Inet<IP4>{

  IP6& ip_obj()
  { return ip6_; }

   IP6    ip6_;
  }
}

In main.cpp, I am including it as follows:
#include <net/ip6/ip6.hpp>
#include <net/inet4.hpp>

> /home/nikhil/projects/ipv6/IncludeOS/api/net/ip6/ip6.hpp:84:32: error:
> incomplete type 'net::Inet4' named in nested name specifier
>     void set_packet_forwarding(Stack::Forward_delg fwd)
>                                ^~~~~~~ /home/nikhil/projects/ipv6/IncludeOS/api/net/ip6/ip6.hpp:35:9: note:
> forward declaration of 'net::Inet4'   class Inet4;

A: there is only Inet decalaration (not definition). Compiler does not know definition of Inet4 (hence Stack which is alaised to Inet4).


text:
Q: How can I read all files and directory in a device? Is it possible to develop a Java application that can read all files and directories in the device's memory?
I think it's not possible (for security reasons), but I need another opinion.

A: You can do it like this.
I will take path is the device storage.
If you are using Android Studio or a likewise tool, put the debug point next to:
 File[] dir = new File(path).listFiles();

And you will see the file/folder hierarchy.
path = Environment.getExternalStorageDirectory().toString()

public static ArrayList<String> listFoldersAndFilesFromSDCard(String path) {
    ArrayList<String> arrayListFolders = new ArrayList<String>();

    try {
        File[] dir = new File(path).listFiles();
        // Here 'dir' will give you a list of folder/files in the hierarchy

        if (null != dir && dir.length > 0) {
            for (int i = 0; i < dir.length; i++) {
                if (dir[i].isDirectory()) {
                    arrayListFolders.add(new File(dir[i].toString()).getName());
                    // Here you can call recursively this
                    // function for file/folder hierarchy
                }
                else {
                    // Do whatever you want with the files
                }
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return arrayListFolders;
}


text:
Q: OpenGL ES source files I am trying to build the OpenGL SO lib from android sources (libGLESv2.so) and i would like a little bit more understanding of the internal mechanism of Android OpenGL ES and the flow.
Please correct me where i am  wrong:
I know that in windows a developer includes gl.h and static link to OpenGL32(64).lib (which in turn dynamically link to OpenGL32.dll (probably there is a way to dynamic linke to OpenGL32.dll by the developer but that's not important).
The developer is exposed to the declaration of OpenGL API's but the implementation which i assume to be HW dependent.
The same scenario, Android: assuming developer import .opengl.GLES20 and calls the following method: GLES20.glTexEnvf(....
I would like to know what's going on behind the scenes in android (maybe Linux is better for an Android beginner).
the implementation which reside in opengl/java/android/opengl/GLES20.java source calls the native C function glTexEnvf which unlike windows we have it's implementation which reside in opengl/libagl.
Is it true?
In any case what is the GLES2_dbg library  in /libs/GLES20_dbg? i can see there some kind of debug implementation with python scripts... are they to compile OpenGL debug version?
What are the .in files and gl2.cpp file in /libs/GLES20?
Where are the HW calls? does each GPU vendor sends his libGLESv2 implementation for HW calls as i saw the libGLESv2_adreno200.so in my xperia arc?
Please help me understand the flow. If you have a link which explain this structure even in Linux it will be great.

A: In Windows opengl32.dll contains both a software rasterizer fallback and so called trampolines into the OpenGL-ICD shipping with the GPU driver.
The opengl32.lib ist not really a library but a cross reference for the linker to add entries into the executable that make the OS dynamically link the program against the DLL at runtime.
On Linux in the current implementation the libGL.so ships with the graphics driver and contains the vendor specific implementations. The linkers used in *nix systems don't rely on an extra crossreferencing .lib but can take the information directly from the .so
On Android the libGLES you see is only a kind of placeholder to make linking possible. But ultimately the GPU vendor provides the proper library, which drops into the place where the phony libGLES resided.
The .in files are nothing special in particular. They are input files used by configure and build systems to build source files from a template (the .in file) with fields filled in by configuration values.

A: thanks for the quick answer, i did a little more digging and as i saw here:
Missing OpenGL drivers on Android emulator,
further explanation.
What i understand now is the libagl is pure SW implementation.
In that case the libhgl is actually the GPU vendor implementation.
I also understood that libEGL opens (found it in the code - Loader.cpp) the libGLESv2....
So i will ask 2 more question:

*

*libGLESv2 only dynamically link to the HW lib or the libEGL does that? (found something on EGL - loader.cpp which seems like dynamically link OpenGL API's)

2.So when i call an OpenGL API i goes trough libEGL (since there is the dynamic binding)? and from there to libGLESv2 ?
thanks a lot for your help
it starting to make sense now


text:
Q: Lifetimes in HashMap where key refers to value I'm relatively new to Rust.  I want to write a function that will create a HashMap from a collection given a closure that generates a key from a value, e.g.
[derive(Debug)]
struct Foo {
    id: u32,
    name: String,
}
let foos = vec![
    Foo { id: 1, name: "Bill".to_string() },
    Foo { id: 2, name: "Mary".to_string() },
];
println!("{:?}", foos);
println!("{:?}", map_by(foos.iter(), |f|  f.id));  // borrow  the Foos
println!("{:?}", map_by(foos.iter(), |f| &f.name));          // borrow
println!("{:?}", map_by(foos.iter(), |f|  f.name.as_str())); // borrow
println!("{:?}", map_by(foos,        |f|  f.id));  // consume the Foos

I wrote this, and it works for the above uses:
fn map_by<I,K,V>(iterable: I, f: impl Fn(&V) -> K) -> HashMap<K,V>
where I: IntoIterator<Item = V>,
      K: Eq + Hash
{
    iterable.into_iter().map(|v| (f(&v), v)).collect()
}

[Foo { id: 1, name: "Bill" }, Foo { id: 2, name: "Mary" }]
{1: Foo { id: 1, name: "Bill" }, 2: Foo { id: 2, name: "Mary" }}
{"Bill": Foo { id: 1, name: "Bill" }, "Mary": Foo { id: 2, name: "Mary" }}
{"Bill": Foo { id: 1, name: "Bill" }, "Mary": Foo { id: 2, name: "Mary" }}
{2: Foo { id: 2, name: "Mary" }, 1: Foo { id: 1, name: "Bill" }}

Great!  But it doesn't work when I let the HashMap OWN the values when the keys refer to them:
println!("{:?}", map_by(foos,        |f| f.name.as_str()));

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements

And unfortunately the error message melted my brain.  I tried specifying that the key and value have the same lifetime, but it didn't help.  Here it is in a playground.  What is the compiler trying to tell me, and what am I doing wrong?  Surely if this can work when we borrow the values, it can work when we own them.

A:
Surely if this can work when we borrow the values, it can work when we own them.

No. A HashMap will move entries around in memory when it needs to resize itself to accommodate new entries. If the key borrows the value, and the entry is moved, then the address of the value will change and the reference in the key will no longer be valid.
For more information, see Why can't I store a value and a reference to that value in the same struct?.


text:
Q: How do compare strings with nhibernate? I'm trying to do something like:
Session.Query<VoiceMailNumber>()
            .Where(x => (x.From.CompareTo(number) > 0) &&
                  (x.To.CompareTo(number)) > 0)

But that throws System.NotSupportedException.
From and number are both strings.
Any solution?

A: This solves it:
Session.CreateCriteria(typeof(VoiceMailNumber))
                .Add(Expression.Le("From", number))
                .Add(Expression.Ge("To", number))
                .UniqueResult<VoiceMailNumber>();

I'm not super happy with this solution, but since it's not possible to compare strings using query or queryover, it will have to do.

A: You can compare string exactly using this syntax:
Session.Query<VoiceMailNumber>()
  .Where(x => x.From==number)
  .And(x=>x.To==number);

Translates to:
select * from VoiceMailNumber where From='123456' and To='123456'


text:
Q: What is the best way of performing a string concatenation in making a dynamic URL? I am constructing a URL at runtime. So far I have done like
public string BuildURLAndNavigate(CodeType codeType)
{
    string vURL = string.Empty;

    string mstrNavServer = "http://some.com/nav";
    vURL = ConcatenateString(mstrNavServer , "/somepage.asp?app=myapp");

    //Build Code Type
    switch (codeType)
    {
    case CodeType.Series:
        vURL = ConcatenateString(vURL , "&tools=ser");
        break;
    case CodeType.DataType:
        vURL = ConcatenateString(vURL , "&tools=dt");
        break;
    }

    //build version
    string VER_NUM = "5.0";
    vURL = ConcatenateString(vURL , ConcatenateString("&vsn=" , VER_NUM));
    return vURL;
    }

    private string ConcatenateString(string expression1, string expression2)
    {
        return string.Concat(expression1 + expression2);
    }

But I am not happy with the one I am doing.
I am sure that there is definitely a best practice / better approach than this.
Kindly help me out in guiding for the same.
Thanks

A: You could use a StringBuilder:
public string BuildURLAndNavigate(CodeType codeType)
{
    StringBuilder vURL = new StringBuilder();

    vURL.Append("http://some.com/nav");
    vURL.Append("/somepage.asp?app=myapp");

    //Build Code Type
    switch (codeType)
    {
        case CodeType.Series:
            vURL.Append("&tools=ser");
            break;
        case CodeType.DataType:
            vURL.Append("&tools=dt");
            break;
    }

    //build version
    string VER_NUM = "5.0";
    vURL.AppendFormat("&vsn={0}", VER_NUM);

    return vURL.ToString();
}

A: Never build urls using strings, string builders, string concatenations.
You could start by defining a custom collection which will take care of properly URL encoding any value being added to it:
public class HttpNameValueCollection : NameValueCollection
{
    public override void Add(string name, string value)
    {
        base.Add(name, HttpUtility.UrlEncode(value));
    }

    public override string ToString()
    {
        return string.Join("&", Keys.Cast<string>().Select(
            key => string.Format("{0}={1}", key, this[key])));
    }
}

And then simply:
public string BuildURLAndNavigate()
{
    var uriBuilder = new UriBuilder("http://some.com/nav/somepage.asp");
    var values = new HttpNameValueCollection();
    values.Add("app", "myapp");

    switch (codeType)
    {
        case CodeType.Series:
            values.Add("tools", "ser");
            break;
        case CodeType.DataType:
            values.Add("tools", "dt");
            break;
    }

    // You could even do things like this without breaking your urls
    values.Add("p", "http://www.example.com?p1=v1&p2=v2");

    string VER_NUM = "5.0";
    values.Add("vsn", VER_NUM);
    uriBuilder.Query = values.ToString();
    return uriBuilder.ToString();
}

A: What you are doing is fine - it is simple and understandable. Anyone who reads the code can understand what you are doing.
In terms of performance - you are not doing much string manipulation, so unless you are building huge strings or doing this operation thousands of times a minute, you will not gain much by using StringBuilder. Before optimizing this code, test its performance. You will probably find that there are other bigger bottlenecks to work on first.
The only real comment I have is that your ConcatenateString function seems superfluous. It is not really adding anything to the code and all the call to it can simply be replaced by string.Concat. As mentioned in the answer from @abatishchev, you should be using (str1, str2) not (str1 + str2), as that defeats the reason for the call.

A: Like Saxon Druce said: You could use a StringBuilder, but, depending on CodeType values, you could eliminate the switch too:
public string BuildURLAndNavigate(CodeType codeType)
{
    StringBuilder vURL = new StringBuilder();

    vURL.Append("http://some.com/nav");
    vURL.Append("/somepage.asp?app=myapp");

    //Build Code Type
    vURL.Append(codeType == CodeType.Series ? "&tools=ser" : "&tools=dt");

    //build version
    string VER_NUM = "5.0";
    vURL.AppendFormat("&vsn={0}", VER_NUM);

    return vURL.ToString();
}

A: Do
return string.Concat(expression1, expression2);

not
return string.Concat(expression1 + expression2);

A: wouldn't the right way to do that be to use the Uri-class or the UriBuilder class?
for example the Uri ctor overload Uri(Uri, string):
public Uri(
   Uri baseUri,
   string relativeUri
);

Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");
Console.WriteLine(myUri.ToString());

http://msdn.microsoft.com/en-us/library/aa332624(v=VS.71).aspx

A: Yes, StringBuilder is the best solution here. You can find more information on MSDN page: http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx
StringBuilder contains very usefull methods:
StringBuilder.Append
Appends information to the end of the current StringBuilder.
StringBuilder.AppendFormat
Replaces a format specifier passed in a string with formatted text.
StringBuilder.Insert
Inserts a string or object into the specified index of the current StringBuilder.
StringBuilder.Remove
Removes a specified number of characters from the current StringBuilder.
StringBuilder.Replace
Replaces a specified character at a specified index.

A: I'd personally be inclined to just string.format something like that:
public string BuildURLAndNavigate(CodeType codeType)
{
    string vURL = "http://some.com/nav/somepage.asp?app=myapp&tools={0}&vsn={1}";
    string codevalue = "";
    //Build Code Type
    switch (codeType)
    {
    case CodeType.Series:
        codevalue = "ser";
        break;
    case CodeType.DataType:
        codevalue = "dt";
        break;
    }

    //build version
    string version = "5.0";
    return string.Format(vURL, codevalue, version);
    }
}

Apologies if there are any mistakes in that, I wasn't in VS when writing it so there might be a few typos I didn't notice - you should get the idea though.
The reason I like this method is because you can immediately see what your url's overall form is which can make it a bit easier to understand roughly what the url being returned is.

A: In order to keep all variables at one place, could we use following solution
public string BuildURLAndNavigate(CodeType codeType)
    {
        //code here - switch statement to calculate the codeValue

        //Anonymous type - To keep all variables at one place
        var urlComponents = new {
                                server = "http://some.com/nav",
                                pageName="/somepage.asp?app=myapp",
                                codevalue = "", //Replace with the actual value calculated in switch statement
                                versionPart="&vsn=",
                                version = "5.0"
                                };

        StringBuilder vURL = new StringBuilder();
        vURL.Append(urlComponents.server);
        vURL.Append(urlComponents.pageName);
        vURL.Append(urlComponents.codevalue);
        vURL.Append(urlComponents.versionPart);
        vURL.Append(urlComponents.version);
        return vURL.ToString();

    }


text:
Q: How to detect device rotation (orientation change) in flutter? My app has a draggable floating action button that could move everywhere on the screen and stay at that position when being dropped.
The code for the button is from a blogspot and not mine.
The problem is, since everything is set in portrait mode, and there is no detection when rotation occurs, the button could be unreachable when device rotates from portrait mode to landscape mode (if the button was previously on the bottom half of the screen in portrait mode).
Is there anyway to detect previous orientation in order to set the offset for the button again when it rotates?
Here is the code for the floating button class/widget
import 'package:flutter/material.dart';

class DraggableFloatingActionButton extends StatefulWidget {
  final Widget child;
  final double deviceWidth;
  final double deviceHeight;

  final Function onPressed;
  final GlobalKey parentKey;

  DraggableFloatingActionButton({
    required this.child,
    required this.deviceWidth,
    required this.deviceHeight,
    required this.onPressed,
    required this.parentKey,
  });

  @override
  State<StatefulWidget> createState() => _DraggableFloatingActionButtonState();
}

class _DraggableFloatingActionButtonState extends State<DraggableFloatingActionButton> {
  final GlobalKey _key = GlobalKey();

  bool _isDragging = false;
  late Offset _offset;
  late Offset _minOffset;
  late Offset _maxOffset;

  @override
  void initState() {
    _offset = Offset(widget.deviceWidth * 0.8, widget.deviceHeight * 0.75);

    WidgetsBinding.instance.addPostFrameCallback(_setBoundary);
    super.initState();
  }

  void _setBoundary(_) {
    final RenderBox parentRenderBox =
        widget.parentKey.currentContext?.findRenderObject() as RenderBox;
    final RenderBox renderBox = _key.currentContext?.findRenderObject() as RenderBox;

    try {
      final Size parentSize = parentRenderBox.size;
      final Size size = renderBox.size;

      setState(() {
        _minOffset = const Offset(0, 0);
        _maxOffset = Offset(parentSize.width - size.width, parentSize.height - size.height);

      });
    } catch (e) {
      print('catch: $e');
    }
  }

  void _updatePosition(PointerMoveEvent pointerMoveEvent) {
    double newOffsetX = _offset.dx + pointerMoveEvent.delta.dx;
    double newOffsetY = _offset.dy + pointerMoveEvent.delta.dy;

    if (newOffsetX < _minOffset.dx) {
      newOffsetX = _minOffset.dx;
    } else if (newOffsetX > _maxOffset.dx) {
      newOffsetX = _maxOffset.dx;
    }

    if (newOffsetY < _minOffset.dy) {
      newOffsetY = _minOffset.dy;
    } else if (newOffsetY > _maxOffset.dy) {
      newOffsetY = _maxOffset.dy;
    }

    setState(() {
      _offset = Offset(newOffsetX, newOffsetY);
    });
  }

  @override
  Widget build(BuildContext context) {

    return Positioned(
      left: _offset.dx,
      top: _offset.dy,
      child: Listener(
        onPointerMove: (PointerMoveEvent pointerMoveEvent) {
          _updatePosition(pointerMoveEvent);

          setState(() {
            _isDragging = true;
          });
        },
        onPointerUp: (PointerUpEvent pointerUpEvent) {
          print('onPointerUp');

          if (_isDragging) {
            setState(() {
              _isDragging = false;
            });
          } else {
            widget.onPressed();
          }
        },
        child: Container(
          key: _key,
          child: widget.child,
        ),
      ),
    );
  }
}

As you can see, it only sets the button's offset based on portrait mode once in initState function, and doesn't deal with rotation.
A walk around that I could think of at this moment is just having another floating button specifically set for landscape mode.
Thank you in advance for any answer.

A: Ok, so I still don't know how to detect rotation, but my walk around works.
All I do is create another class(widget) for a landscape floating button.
In main, check device orientation to use either the floating button portrait class or landscape class.
The only thing that I change in the landscape button class is
from
_offset = Offset(widget.deviceWidth * 0.8, widget.deviceHeight * 0.75);

to
_offset = Offset(widget.deviceHeight * 1.75, widget.deviceWidth * 0.3);

A: You shouldn't care about orientation.  You should use something like LayoutBuilder to determine your space available, and make breakpoint decisions based on that.  LayoutBuilder will update immediately if the device space changes, and you should react to that by doing another layout.


text:
Q: extracting keys from json string using json4s can someone tell me how to extract keys from json using json4s.
My use case:
json stored as string in scala variable:
 {
 "key1" : "val1",
 "key2" : ["12", "32"],
 "key3" : {"keyN" : "valN"}
 }

I'd like to transform this into a following Map[String, String]:
 (key1 -> "val1", key2 -> "[\"12\",\"32\"]", key3 -> "{\"keyN\":\"valN\"}"

is there a simple way to achieve this with json4s?
Thanks in advance

A: val result: Map[String, String] = parse( """ {
                                           | "key1" : "val1",
                                           | "key2" : ["12", "32"],
                                           | "key3" : {"keyN" : "valN"}
                                           | }""".stripMargin).mapField(k => {
  val v: String = k._2 match {
    case s: JString => k._2.extract[String]
    case _ => write(k._2)
  }
  (k._1, JString(v))
}).extract[Map[String, String]]
println(result)

You can use mapField map the JValue toString

*

*if the value's type is String just extract as String

*if the value's type is others, use the json4s to parse it to as JSON string

*finally extract the JValue as  Map[String, String].

A: implicit val formats = DefaultFormats

val a = parse(""" { "numbers" : [1, 2, 3, 4] } """)
println(a.extract[Map[String, Any]].keySet)


text:
Q: Filtering an array which controls v-for in Vue app with array.filter works with equality but not RegExp I would like to search in a text box and filter a list of objects by whether a property matches the entered text.
Each of the objects in the filteredBuildings array creates a shape on a Google Map.
I have the following in my Vue app:
...

data: {
    searchtext: '',
    buildings: [
        {
            name: 'Home',
            ...
        },{
            name: 'Work',
            ...
        }
    ],
},
computed: {
    filteredBuildings () {
        if( this.searchtext == '' )
            return this.buildings;

        const re = new RegExp( this.searchtext, 'i' );
        return this.buildings.filter( b => {
            // return b.name === this.searchtext;
            // return b.name.toLowerCase().indexOf( this.searchtext.toLowerCase() ) > -1;
            return re.test(b.name);
        });
    },
},

...

and the templates are complicated, but something like this:

// the main component

    <GoogleMapPolygon v-for="b in filteredBuildings"
        :key="b.id"
        :id="b.id"
        :name="name"
        ...
    />

// the GoogleMapPolygon component
// (no <template>)
...
data: {
    polygon: null,
    ...
},
mounted () {
    this.polygon = new google.maps.Polygon({
        map: map,
        ...
    });
    ...
},
destroyed () {
    this.polygon.setMap(null);
},
render () {
    return false;
},

If I uncomment the line with === matching, it works just fine.
If I use either the indexOf matching or the RegExp .test(), I get the following error:

[Vue warn]: Error in nextTick: "NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node."

and the app completely dies.
The extra time that the RegExp or indexOf takes seems to be enough to cause the problem. That brings my thinking to nextTick(), but I'm not sure where I would put that.

A: The problem comes from modifying the array of buildings (the elements which are beings used in the v-for directive ) too quickly. Judging by the error, Vue is using those elements as reference points to insert other array items, but reference DOM element has disappeared by the time vue tries to insert the new one.
This could potentially be just a problem with Vue interacting with Google Maps
Solution is to wrap the component being iterated in an element which won't go away when other parts are toggled. For example (from my original question code):

    <GoogleMapPolygon v-for="b in filteredBuildings"
        :key="b.id"
        :id="b.id"
        :name="name"
        ...
    />

I also got this problem when removing one marker and replacing it with another just after it, and this solves that issue as well:

    <GoogleMapMarker
        v-if="this.zoom > 15"
        :key="'you-are-here-marker'"
        :lat="currentLat"
        :lng="currentLng"
    />

    <GoogleMapMarker
        v-if="this.zoom < 16"
        :key="'campus-center-marker'"
        :lat="campusCenter.lat"
        :lng="campusCenter.lng"
    />

Before adding the section tags, I was getting the same error when these two components tried to destroy and create when this.zoom changed.


text:
Q: Laplace Transform of $f(t) = u(\sin(2t))$? What is the Laplace Transform of $f(t) = u(\sin(2t))$?
I'm confused how to proceed further? because $u(t)=0$ for t<0. What does having $\sin(2t)$ in argument mean?
Or $u$ has to be taken as unknown function?

A: If $u(t) = 1$ for positive $t$, and $0$ otherwise, then $u(\sin(2t)) = 1$ whenever $\sin(2t)$ is positive.
That is, $f(t) = 1$ whenever $2t$ is in one of the intervals $(0,\pi),\;(2\pi,3\pi),\;(4\pi,5\pi),\;(-2\pi,-\pi),\;\cdots$
meaning $t$ is in one of the intervals $(0,\frac\pi2),\;(\pi,\frac{3\pi}2),\;(2\pi,\frac{5\pi}2),\;(-\pi,-\frac\pi2),\;\cdots$
and $f(t) = 0$ otherwise. This is a square wave.


text:
Q: turf.within() fails but turf.inside() is successful I am trying to use turf.js to return points within a polygon, but turf.within() generates an empty feature list even for points I know to be within a polygon - turf.inside() returns true for the same points and polygon. I provide an example below. I can successfully run the example at turf.within() and am not sure what it is about my geometry that is the problem.
<script type="text/javascript" src="https://npmcdn.com/@turf/turf/turf.min.js"></script>

....
var thePoint = [-118.049551, 33.866965]

var test = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": thePoint
      }
    }, {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": thePoint
      }
    }
  ]
};

var cerrito = { "type": "Feature", "properties": { "GEO_ID":    "1600000US0612552", "STATE": "06", "PLACE": "12552", "NAME": "Cerritos", "LSAD": "city", "CENSUSAREA": 8.725, "Shape_STAr": 246572616.215, "Shape_STLe": 118080.76087 }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -118.028887999836968, 33.882629000032836 ], [ -118.028681155924062, 33.873316057140322 ], [ -118.028772420533898, 33.873315497179512 ], [ -118.028772240680681, 33.873285861714471 ], [ -118.028761755934283, 33.872110544548683 ], [ -118.028717388339928, 33.866241889545748 ], [ -118.028792999919617, 33.866240999737094 ], [ -118.035119980483032, 33.866020314132811 ], [ -118.035591866241305, 33.866016576824734 ], [ -118.035818357122793, 33.866015383719059 ], [ -118.035983055259194, 33.866014509762415 ], [ -118.036147752309518, 33.8660136310734 ], [ -118.036148847050185, 33.866013630744973 ], [ -118.037598000415159, 33.866012999764315 ], [ -118.037597881676277, 33.866006075268416 ], [ -118.037624048408333, 33.866005950805395 ], [ -118.037575372135976, 33.86388909386703 ], [ -118.037562273006358, 33.863314044528884 ], [ -118.037540454019165, 33.86236905889217 ], [ -118.037606327718564, 33.862368507358319 ], [ -118.037979218998117, 33.862365367620129 ], [ -118.039225723817765, 33.862354938919154 ], [ -118.039350888987059, 33.862353881198253 ], [ -118.039574899257346, 33.862352021930512 ], [ -118.039782079613744, 33.862350277788913 ], [ -118.039963633664883, 33.86234876086143 ], [ -118.040128290807047, 33.862347360175178 ], [ -118.040309482829713, 33.862345842847105 ], [ -118.040474501989308, 33.862344468612086 ], [ -118.040655693999881, 33.862342951664914 ], [ -118.040820383551591, 33.862341577067333 ], [ -118.041001575536058, 33.862340031653119 ], [ -118.041166594672802, 33.862338656470193 ], [ -118.041522357556943, 33.86233567659459 ], [ -118.041555328956449, 33.86233539026582 ], [ -118.04158826686961, 33.86233513188656 ], [ -118.041667975939376, 33.862334444439369 ], [ -118.041884905794092, 33.862332720355347 ], [ -118.041879045435579, 33.861679208477895 ], [ -118.041878661410877, 33.861635133586446 ], [ -118.041877779312557, 33.861530668241585 ], [ -118.041877117333357, 33.861453668349675 ], [ -118.041875622573116, 33.86128871703405 ], [ -118.041874434390664, 33.861151243763409 ], [ -118.04187324622599, 33.86101379844164 ], [ -118.041872056970632, 33.860876325175354 ], [ -118.041870868813831, 33.86073887985755 ], [ -118.041869613384449, 33.860598713795902 ], [ -118.041868145114535, 33.860428321848957 ], [ -118.04186653720933, 33.860242294996745 ], [ -118.041865207827939, 33.860088170827417 ], [ -118.041854341147129, 33.858838905318855 ], [ -118.041854202456747, 33.8588251662961 ], [ -118.041853336146318, 33.858724067229424 ], [ -118.046188000416265, 33.858768000030139 ], [ -118.046186748924541, 33.858687270846296 ], [ -118.046200389259099, 33.858687186283355 ], [ -118.046186014574644, 33.857785576122218 ], [ -118.046163305133547, 33.856407842019244 ], [ -118.046152668322023, 33.855664249739483 ], [ -118.046110568906883, 33.853648342941831 ], [ -118.04611084525645, 33.853610518941778 ], [ -118.047386006877716, 33.853589266798537 ], [ -118.048728911992114, 33.853575817845297 ], [ -118.049101279351319, 33.853572084045524 ], [ -118.049609117085879, 33.853568105873244 ], [ -118.05041069369274, 33.85356182224956 ], [ -118.050410420346836, 33.853533108261765 ], [ -118.050405543181043, 33.853033914419463 ], [ -118.050399505365675, 33.852413871433946 ], [ -118.050398863336483, 33.852345210650313 ], [ -118.050398171596498, 33.852276536365281 ], [ -118.050395364025476, 33.851988181322085 ], [ -118.050394029188837, 33.851850845358634 ], [ -118.0503926949755, 33.851712741307736 ], [ -118.050392161744654, 33.85165789437027 ], [ -118.050391361261092, 33.851575460340229 ], [ -118.050390027518588, 33.85143812528397 ], [ -118.050388692733023, 33.851300845222546 ], [ -118.050387326600486, 33.851163537229304 ], [ -118.050386025351628, 33.851026311248653 ], [ -118.050383464434944, 33.850765297230296 ], [ -118.050382854871259, 33.850696677914939 ], [ -118.050382130718276, 33.850627962186074 ], [ -118.050379462200738, 33.850353264157327 ], [ -118.050375711015633, 33.849966976406435 ], [ -118.053892316950595, 33.849848893473471 ], [ -118.054516818610182, 33.849844709837626 ], [ -118.054590588300428, 33.849844214857512 ], [ -118.054722683312946, 33.849843325535495 ], [ -118.054722478592268, 33.849821017688754 ], [ -118.054723000454345, 33.849821000322997 ], [ -118.054716601109988, 33.84918063060708 ], [ -118.054705566290011, 33.84797815444341 ], [ -118.054700499743277, 33.847440996646093 ], [ -118.054689180780002, 33.846217950124199 ], [ -118.054776697011036, 33.846215943261306 ], [ -118.056046115878445, 33.846208952311493 ], [ -118.057043290604042, 33.846203779261714 ], [ -118.058278859805654, 33.846196339066665 ], [ -118.059040364775043, 33.846192198135391 ], [ -118.059040016006662, 33.846124967096777 ], [ -118.060671000051059, 33.846177999563118 ], [ -118.06338900026266, 33.84615300022368 ], [ -118.065990999985502, 33.846131999565429 ], [ -118.072090999789609, 33.846084000390604 ], [ -118.081980999696881, 33.84600600023699 ], [ -118.08202099972182, 33.849640999592488 ], [ -118.086370999820048, 33.84963300020425 ], [ -118.086368999500323, 33.845970999859297 ], [ -118.086803999550057, 33.845968999565606 ], [ -118.092398000044483, 33.845925000070416 ], [ -118.098939000208091, 33.845875000320532 ], [ -118.09921100033479, 33.845875999972094 ], [ -118.100211999558695, 33.848065999601282 ], [ -118.101733000020189, 33.853478000147867 ], [ -118.103054999461108, 33.858318000193101 ], [ -118.108316999981298, 33.858371000240467 ], [ -118.108428999611235, 33.865586999998889 ], [ -118.108536000018645, 33.872715000058548 ], [ -118.106910000099688, 33.872711000330419 ], [ -118.106974000434647, 33.872942999957047 ], [ -118.108003999515034, 33.876790000315744 ], [ -118.108546999473432, 33.87984299979373 ], [ -118.108563999545112, 33.886942999906346 ], [ -118.108417999623612, 33.886938999677412 ], [ -118.108160000123547, 33.886939999577628 ], [ -118.104370000310539, 33.886968000366373 ], [ -118.10425600018489, 33.887381999848436 ], [ -118.100572999781591, 33.887395000134291 ], [ -118.100547000184832, 33.886982999787215 ], [ -118.09988300024132, 33.886990000446659 ], [ -118.09988699995877, 33.88740200023738 ], [ -118.095532999746752, 33.887425999876328 ], [ -118.095537999774862, 33.88211299995568 ], [ -118.095466999498029, 33.880314000301986 ], [ -118.09541300051032, 33.87852799995575 ], [ -118.09380399970361, 33.87855300002056 ], [ -118.091064999993833, 33.878859999883623 ], [ -118.091085999524168, 33.88032599969636 ], [ -118.087806000080136, 33.880338000092316 ], [ -118.087776999582886, 33.876750000365199 ], [ -118.091033999660468, 33.876416000198674 ], [ -118.090991999619234, 33.8729809995612 ], [ -118.090990999805427, 33.865683999854205 ], [ -118.090901000460704, 33.861313000431181 ], [ -118.089982999574389, 33.861319000332337 ], [ -118.089973999821112, 33.860224999604107 ], [ -118.086482999908952, 33.860250000054762 ], [ -118.086474999522395, 33.85842399971353 ], [ -118.086450000287186, 33.856003999941251 ], [ -118.082092000279232, 33.856040000312333 ], [ -118.082110999618877, 33.860495000048402 ], [ -118.078810999737044, 33.85847399969186 ], [ -118.075151000444947, 33.856228000446528 ], [ -118.072288000163809, 33.856968999864691 ], [ -118.072240999730425, 33.854512000252328 ], [ -118.070459000360898, 33.853411000398474 ], [ -118.068915000458702, 33.853423000135727 ], [ -118.069006999624165, 33.858557000390903 ], [ -118.071223999523767, 33.858534999730935 ], [ -118.070178000376117, 33.860339000416801 ], [ -118.070294000094378, 33.865815999626136 ], [ -118.070313999561719, 33.869456999865655 ], [ -118.0724970001271, 33.869453999697591 ], [ -118.070334999534126, 33.869835999844774 ], [ -118.070384000066582, 33.873111000077408 ], [ -118.08004299960642, 33.873053999696083 ], [ -118.07964899968843, 33.876462000326832 ], [ -118.07927399950583, 33.87674000007636 ], [ -118.075086999544695, 33.8767670000233 ], [ -118.074840999957502, 33.876769000254562 ], [ -118.074895000371953, 33.880383000438925 ], [ -118.072708000101883, 33.880391999903772 ], [ -118.072825000397017, 33.885832999950722 ], [ -118.068447000489812, 33.885887999807679 ], [ -118.06846999965768, 33.887112000073593 ], [ -118.068475999850449, 33.887559000148578 ], [ -118.066323999719302, 33.887571000149549 ], [ -118.06528799964515, 33.887577000140304 ], [ -118.064333000067364, 33.887581999621858 ], [ -118.06408499971505, 33.887165000021376 ], [ -118.055376000176864, 33.887216000217663 ], [ -118.055382999695453, 33.887649999683752 ], [ -118.046538999840678, 33.887713000322073 ], [ -118.038572000150765, 33.88777300012908 ], [ -118.028887999836968, 33.882629000032836 ] ] ] ] } }

var cerritoPolygon = turf.polygon(cerrito.geometry.coordinates[0]) //turn cerrito coordinates into polygon

var cerritoFeatureCollection = turf.featureCollection(cerrito) //create a feature collection

var ptsWithin = turf.within(test, cerritoFeatureCollection); //see if test points are within the cerrito featureCollection

var pt = turf.point(thePoint);

var isInside = turf.inside(pt, cerritoPolygon);

console.log(ptsWithin)//returns a featureCollection with an empty features array
console.log(isInside)//returns true - thePoint is in the cerrito polygon


text:
Q: Unable to determine whether the interceptor is working or not in Struts2 I have configured struts.xml file as follows :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">

      <action name="hello"
            class="com.struts2examples.HelloWorldAction"
            method="execute">
            <result name="success">/HelloWorld.jsp</result>
            <result name="error">/AccessDenied.jsp</result>
            <interceptor-ref name="params"/>
            <interceptor-ref name="timer" />
      </action>
   </package>
</struts>

It should log the time of execution action hello. When I am calling the hello action on server, Logs get generated in tomcat logs as :
0:0:0:0:0:0:0:1 - - [18/Nov/2013:17:24:38 +0530] "GET /StrutsHelloWorld/Login.jsp HTTP/1.1" 404 1033
0:0:0:0:0:0:0:1 - - [18/Nov/2013:17:29:30 +0530] "POST /Struts2HelloWorld/hello HTTP/1.1" 200 129
0:0:0:0:0:0:0:1 - - [18/Nov/2013:17:29:41 +0530] "POST /Struts2HelloWorld/hello HTTP/1.1" 200 105
0:0:0:0:0:0:0:1 - - [18/Nov/2013:17:31:04 +0530] "POST /Struts2HelloWorld/hello HTTP/1.1" 200 105

Nowhere the interceptor logs are shown. I am accessing the
localhost_access_log.2013-11-18.txt file in tomcat logs. Am I accessing the wrong file? If it is then where would be the logs generated?

A: You didn't specified which library you are using (eg. Log4j), nor how it's configured, but you should look inside your log file, not in tomcat one.
From the documentation:

This interceptor logs the amount of time in milliseconds. In order for
  this interceptor to work properly, the logging framework must be set
  to at least the INFO level. This interceptor relies on the Commons
  Logging API to report its execution-time value.
Parameters

*

*logLevel (optional) - what log level should we use (trace, debug, info, warn, error, fatal)? - defaut is info

*logCategory (optional) - If provided we would use this category (eg. com.mycompany.app). Default is to use
  com.opensymphony.xwork2.interceptor.TimerInterceptor.
The parameters above enables us to log all action execution times in
  our own logfile.

That said, you are using only TWO interceptors; it would be better to add the Timer Interceptor to the defaultStack or at least to the basicStack (or to a custom stack of your). Putting it after the stack will log only Action's execution time, while before the stack will log Interceptors's execution time too:
Log only Action's execution time:
<action name="hello" class="com.struts2examples.HelloWorldAction">
    <interceptor-ref name="defaultStack"/>
    <interceptor-ref name="timer" />
    <result>/HelloWorld.jsp</result>
    <result name="error">/AccessDenied.jsp</result>
</action>

Log Action's and Interceptor's execution time:
<action name="hello" class="com.struts2examples.HelloWorldAction">
    <interceptor-ref name="timer" />
    <interceptor-ref name="defaultStack"/>
    <result>/HelloWorld.jsp</result>
    <result name="error">/AccessDenied.jsp</result>
</action>

Note that method="execute" or result name="success" are not necessary because they're the default.


text:
Q: Can we append App_DLLs value? I have a situation where two application are injecting dlls and updating HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs with its value.
As App_DLLs is REG_SZ type registry. So we can have only value of AppInit_DLLs which is making only application running at one time.
Is there any way that I can append the value of App_DLLs so that both application can use their respective dlls and run concurrently

A: Working with the AppInit_DLLs registry value


text:
Q: How to cancel an alertdialog? I wanted to do a password alert box on an activity so once it has the correct answer it closes the dialog box but I cant seem to find a way when searching of how to close a dialog box the way I have coded it anyway.
Here is my code
final AlertDialog.Builder alert1 = new AlertDialog.Builder(this);
alert1.setTitle("Password");
alert1.setMessage("Please enter your password below and press Ok.");

final EditText input = new EditText(this);
alert1.setView(input);

alert1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        String value = input.getText().toString().trim();
        ((Global) Menu.this.getApplication()).setgPassword(value);
        ((Global) Menu.this.getApplication()).setgSiteId(strSavedMem1);
        LogIn();
    }
});

alert1.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        System.exit(0);
    }
});

alert1.show();

Is there a way to close this alertbox?

A: You should check out this link of the Android documentation:
http://developer.android.com/guide/topics/ui/dialogs.html#DismissingADialog
There it is explained how can can cancel a Dialog.

A: You can receive dialog instance in DialogInterface onClick method.
@Override
public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
}

A: Try like this:
final AlertDialog.Builder alert1 = new AlertDialog.Builder(this);
                      alert1.setTitle("Password");
                      alert1.setMessage("Please enter your password below and press Ok.");
                      final EditText input = new EditText(this);
                      alert1.setView(input);
                      alert1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int whichButton) {
                              String value = input.getText().toString().trim();
                              ((Global) Menu.this.getApplication()).setgPassword(value);
                              ((Global) Menu.this.getApplication()).setgSiteId(strSavedMem1);
                              LogIn();
                              alert1.dismiss();
                          }
                      });

                      alert1.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int whichButton) {
                              //System.exit(0);
                              alert1.cancel();
                          }
                      });
                      alert1.show();

                }

A: Check this,
 AlertDialog.Builder successfullyLogin = new Builder(
        YourActivity.this);
      successfullyLogin.setCancelable(false);
      successfullyLogin.setMessage("Successfully LoggedIn !");

      successfullyLogin.setPositiveButton("Ok",
        new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog,
           int which) {
          // TODO Auto-generated method stub

         }
        });
      successfullyLogin.show();

A: Do you want the dialog to disappear when the user presses a button? If so, you don't have to do anything, it should be dismissed automatically (when the user presses any button).
Do you want the dialog to disappear on its own when the correct password has been entered? Then you will need to add a TextWatcher to the EditText field:
input.addTextChangedListener(new TextWatcher()....)

Callback functions in the TextWatcher will be called whenever the text changes, and you can there check whether the password is correct, and if it is, call
dialog.dismiss();

A: You don´t have to do anything.
As is said in the Android Documentation linked by anonymous:
"When the user touches any of the action buttons created with an AlertDialog.Builder, the system dismisses the dialog for you."
http://developer.android.com/guide/topics/ui/dialogs.html#DismissingADialog

A: Try this:
final AlertDialog.Builder Dialog = new AlertDialog.Builder(this);

Dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

      public void onClick(DialogInterface arg0, int arg1) {
        Dialog.setCancelable(true);

      }});

A: I know this question was asked a long time ago but I have a different solution from most of the other answers.

In my case, I wanted to cancel the AlertDialog when a certain button inside my inflated view was clicked. Of course, this has nothing to do with setNegativeButton() or setPositiveButton() so I had no access to any alertdialog object.

Here is how I solved this:
At the point of showing your AlertDialog (alertDialog.show()), you can just store the .show object into a variable as shown below:
AlertDialog shower = alertDialog.show();

Once this is done, you can easily cancel your alertdialog by calling shower.cancel() anywhere within your AlertDialog scope.
I hope this helps. Merry coding!


text:
Q: Upload image to FTP From my Swift application I´m sending an image file to my PHP script and from my PHP script I want to upload it to my FTP.
Here is my script
<?php

$ftp_server = "My FTP";
$ftp_user = "Username";
$ftp_pass = "Password";
$file = $_FILES["file"]["tmp_name"];
$remote_file = "test.png";

// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

// try to login
if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    echo "Connected as $ftp_user@$ftp_server\n";
} else {
    echo "Couldn't connect as $ftp_user\n";
}

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
    echo "Successfully uploaded $file\n";
    exit;
}
else {
    echo "There was a problem while uploading $file\n";
    exit;
}

// close the connection
ftp_close($conn_id);
?>

I´m connecting to the server and I´m able to upload a file BUT my issue is that the file I´m uploading is corrupt. I think it has to do with my $remote_file = "test.png";. Is it the right way to use ftp_putto upload the file and does anyone has a clue why it´s corrupt?

A: <?php

$ftp_server = "My FTP";
$ftp_user = "Username";
$ftp_pass = "Password";
$file = $_FILES["file"]["tmp_name"];
$remote_file = "test.png";

// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

// try to login
if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    echo "Connected as $ftp_user@$ftp_server\n";
} else {
    echo "Couldn't connect as $ftp_user\n";
}

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
    echo "Successfully uploaded $file\n";
    exit;
}
else {
    echo "There was a problem while uploading $file\n";
    exit;
}

// close the connection
ftp_close($conn_id);
?>


text:
Q: Piwik - Mirgration mysql to SQL Server Piwik supports only mysql, I want to integrate with sql server. Is there any way to migrate from mysql to sql server.

A: You've already answered the question, Piwik only supports MySQL, at least for now.
However, there is the possibility of pointing it to a another database server (MS SQL) with a different port and database driver. but since SQL differs between MySQL and MS SQL, so you might get unexpected results (or errors because you use some feature of MySQL that MS SQL doesn't support). You also need a different driver that Piwik would have to support.
You can get some more info on Piwik forum about MS SQL.


text:
Q: jQuery-Validation-Engine - Custom funcCall validation causes error when value is empty I have a custom validation function to verify that two password fields match using jQuery-Validation-Engine:
<input type="password" class="validate[required,funcCall[checkPassordMatch],maxSize[25]]"...

But if the field is not populated, and the form is submitted, I get the following exception:
Uncaught TypeError: Cannot read property 'checkPassordMatch' of undefined

Is there any way I can only run this validation only if the input is populated, or if "required" passes first?
For reference, my function is as follows:
    // Validate the passwords match
function checkPassordMatch(field, rules, i, options){
    console.log(field + ' : ' + rules + ' : ' + i  + ' : ' + options )

    if (field.val() != jQuery("#inputPassword").val()) {
        return options.allrules.passwordMatch.alertText;
    }
}

Appreciate any thoughts.

A: This custom function is not needed. I can use:
validate[required,equals[password]]


text:
Q: access violation reading location 0xfeef002A How to see in visual studio whether the address is also accessed from somewhere else at the same time?
what can be the different reasons access violation is cause?

A: This looks very close to one of the special values used by the Visual Studio runtime debug heap.  There are a number of values that the C runtime uses after memory has been allocated and deallocated so that you can diagnose memory corruption errors more easily.  The value 0xFEEEFEEE is used after memory has been freed.
I suspect what may be happening in your code is that an object has been deallocated but you still have a pointer to it (a dangling pointer) and you're trying to access a member variable of that object.  There are several things you could do to diagnose this problem, depending on the complexity of your code.  One is to enable Page Heap Verification, and the other is to add some breakpoints in the destructor of the class that is being dereferenced so find out where the object is being destroyed so you can reset the other pointers that reference it.  Consider using smart pointers such as shared_ptr<> to reduce the likelihood of dangling pointers.


text:
Q: Trouble rendering a sprite with pixi.js on iOS 8 I have a sprite that loads into a stage in chrome and safari, but not in iOS 8 device or simulator.  The canvas appears, but it is always white (even when I specify red).   And nothing seems to render in it.
Any idea what I'm doing wrong?
var renderer = PIXI.autoDetectRenderer(400, 300);

elem[0].appendChild(renderer.view);

var stage = new PIXI.Stage(0xFF0000);

var wheelTexture = PIXI.Texture.fromImage("/static/img/special/thing.png");
var wheelSprite = new PIXI.Sprite(wheelTexture);
stage.addChild(wheelSprite);
requestAnimationFrame(animate);

function animate() {
  renderer.render(stage);

  requestAnimationFrame(animate);
}

To put this question another way, I challenge you to draw a sprite on a canvas using Pixi.js in iOS8 and then tell me how it was accomplished.  I seem to be able to run most webgl demos and such in the iOS8 simulator, but this basic Pixi.js code doesn't work...
UPDATE:
It turns out that it is rendering everything fine, with the exception that if I don't use a pure black background on the container, it basically renders the stage and everything inside of it white so you can't see it.

A: The dev branch of pixi now works like a champ in ios8. I also pushed a patch up to the master branch too as it is quite an important fix.
https://github.com/GoodBoyDigital/pixi.js/commit/b29acff1455117567440acdb9fc16f9d1d5670db
Turned out to be a simple case of ios8 not liking it when I set the webGL colorMask alpha channel to false


text:
Q: Docker image not running on http://127.0.0.1:8050/ I've created a small dash app and trying to run on docker container.I get the following message
Dash is running on http://127.0.0.1:8050/
But when I try opening the link it shows trouble connecting to the page.
I tried the solution on Docker image not running on host 8050 but it doesn't work as well.
My dockerfile:
FROM python:3.9

ADD main.py .

RUN pip install dash

RUN pip install plotly

RUN pip install pandas

RUN pip install flask

EXPOSE 8080/tcp

CMD [ "python3" ,"./main.py" ]

A: As others said, you need to change the port you're exposing to 8050
FROM python:3.9

ADD main.py .

RUN pip install dash

RUN pip install plotly

RUN pip install pandas

RUN pip install flask

EXPOSE 8050

CMD [ "python3" ,"./main.py" ]

to run using docker run
docker run -p 8050:8050 <image_id>

you should then be able to access it at http://127.0.0.1:8050/

A: Dockerfile like this
FROM python:3.9

WORKDIR /code
COPY main.py /code
RUN pip install dash plotly pandas flask
EXPOSE 8050
CMD python main.py

and build it
docker build -t YOURAPP:latest .
and run it
docker run -p 8050:8050 YOURAPP:latest


text:
Q: What's the difference between name="" and :name="" If :name="name", the value of the name attribute will be the unique data it gets from the props.
But if I use this way name="name" without the : than it will be just "name".
What the : do with the name attribute?
Example code:
<template>
    <div class="form-group">
        <div
            class="form-control"
            :name="name">
        </div>
    </div>
</template>
<script>
    export default {
    name: 'base-date',
    props: ['id', 'name', 'placeholder', 'type', 'value']
</script>

A: : is the short notation for v-bind which binds one or more attributes, or a component prop to an expression dynamically.
On the other hand name="name" will add the string 'name' as an attribute value for your property.


text:
Q: Wrapping a Tkinter program in a scroll bar I am trying to incorporate a scrollbar in my Tkinter window so as I add more things the user can scroll down. From what I've read so far it seems I need to use a Listbox widget but running into trouble adding the scrollbar as it is only getting added to the bottom of the program and not wrapping the entire thing? My code is below.
import Tkinter as Tk
from Tkinter import StringVar

class SampleApp(Tk.Tk):
    def __init__(self):
        Tk.Tk.__init__(self)
        self.button = Tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()#place(x=150, y=600)
####Name#####
        labelText=StringVar()
        labelText.set(" Name")
        labelDir=Tk.Label(self, textvariable=labelText, height=1)
        labelDir.pack()

        directory=StringVar(None)
        self.name =Tk.Entry(self,textvariable=directory,width=25)
        self.name .pack()
    def on_button(self):
        with open('filename.html', 'w') as myfile:
            myfile.write('The button worked')

app = SampleApp()
scrollbar = Tk.Scrollbar(app)
scrollbar.pack( side = Tk.RIGHT, fill=Tk.Y )
app.mainloop()

A: The issue is that the Scrollbar widget is only implemented for Canvas, Listbox, and Text widgets. The Scrollbar must be configured to one of those widgets, and then you add widgets to that parent. Unfortunately, it's not the most straightforward widget to use. See Effbot's Scrollbar page for an example.


text:
Q: MySQL Insert Query with Foreign Key I want to insert a value in table glmast in the field called acname.
The conditions I am using is as follows
g.gl_id = p.gl_id AND p.pl_id='$pdidedit' with g as glmast and p as packlist

I tried joins, and try the below code..
INSERT INTO glmast (acname)
VALUES
('$glidnew') SELECT glmast.acname WHERE glmast.gl_id = packlist.gl_id AND packlist='$pdidedit'";

Any help highly appreciated..Thanks everyone..

A: You can write insert like
INSERT INTO glmast (acname) VALUES ('$glidnew');

or
INSERT INTO glmast (acname)
SELECT glmast.acname from glmast,packlist
  WHERE glmast.gl_id = packlist.gl_id
    AND packlist.gl_id = '$pdidedit'";

Have in mind that in second example there could be multiple inserts in cases when select returns multiple rows.

A: I think this may be what you're trying to do:
INSERT INTO glmast(gl_id, acname)
SELECT '$glidnew', glmast.acname
FROM glmast JOIN packlist ON glmast.gl_id = packlist.gl_id
WHERE packlist.pl_id='$pdidedit'

You keep saying INSERT, but I'm pretty sure you mean UPDATE:
UPDATE glmast g
JOIN packlist p ON g.gl_id = p.gl_id
SET g.acname = '$glidnew'
WHERE p.pl_id = '$pdidedit'

Or maybe this is it:
INSERT INTO glmast (acname, col1, col2, col3, ...)
SELECT '$glidnew', g.col1, g.col2, g.col3, ...
FROM glmast g
JOIN packlist p ON g.gl_id = p.gl_id
WHERE p.pl_id = '$pdidedit'

A: I belive it's something like this you're trying to achieve:
INSERT INTO glmast (acname) VALUES('$glidnew')
WHERE (
    SELECT glmast.acname FROM glmast GM
    JOIN packlist PL ON (PL.gl_id = GM.gl_id)
    WHERE PL.pl_id='$pdidedit'
)

But that syntax is not valid in MySQL.
You will have to run the SELECT-statement first, and then INSERT into the glmast table based on resultset given from SELECT-query:
Step 1:
SELECT glmast.acname FROM glmast GM
JOIN packlist PL ON (PL.gl_id = GM.gl_id)
WHERE PL.pl_id='$pdidedit'

Step 2:
INSERT INTO glmast (acname) VALUES({values from Step1})

In a way, you can say that $glidnew represents the values from Step1.


text:
Q: Unable to locate Attribute with the given name on this ManagedType [unknown] I have an entity Called
public class Customer implements Auditable {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "SellerID")
private Long id;

@Embedded
private AuditSection auditSection = new AuditSection();
......
......
}

@Embeddable
public class AuditSection implements Serializable {
private static final long serialVersionUID = -1934446958975060889L;
@Temporal(TemporalType.TIMESTAMP)
  @Column(name = "DateCreated")
  private Date dateCreated;

  @Temporal(TemporalType.TIMESTAMP)
  @Column(name = "DateModified")
  private Date dateModified;
  ......
  }

I am trying to use the criteriaBuilder and Predicates for Searching
 predicates.add(criteriaBuilder.and(criteriaBuilder.notEqual(root.get("modifiedDate"), new Date)));

Here I am getting the Exception
org.springframework.dao.InvalidDataAccessApiUsageException: Unable to locate Attribute  with the the given name [modifiedDate] on this ManagedType [unknown]; nested exception is java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [modifiedDate] on this ManagedType [unknown]
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:374) ~[spring-orm-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:256) ~[spring-orm-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528) ~[spring-orm-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153) ~[spring-tx-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) ~[spring-data-jpa-2.2.0.RELEASE.jar:2.2.0.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at com.sun.proxy.$Proxy187.findAll(Unknown Source) ~[?:?]
    at com.sawce.core.service.customer.impl.CustomerEnquiryServiceImpl.findByPagingCriteria(CustomerEnquiryServiceImpl.java:73) ~[sawce-core-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
    at com.sawce.core.service.customer.impl.CustomerEnquiryServiceImpl$$FastClassBySpringCGLIB$$8026ffc6.invoke(<generated>) ~[sawce-core-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) ~[spring-aop-5.2.0.RELEASE.jar:5.2.0.RELEASE]

I have referred some of the similar questions but I did not get any solution.

A: The name of the attribute is dateModified not modifiedDate.
So the code must look like:
predicates.add(criteriaBuilder
  .and(criteriaBuilder.notEqual(
       root.get("auditSection").get("dateModified"), new Date)));

A: I have the same error but my mistake is that I send entity name    @Column(name = "abc") but when I send variable name it solved my error.


text:
Q: I am not "getting" ModelBinders in MVC 2 I understand that a ModelBinder is a good place to do work on the request so that you keep that type of code out of the controller.  Working with Form Values would be an example.  That seems to makes sense however, I inherited an application that is using a Custom Binder and I just can't seem to figure out how or why it works.
The binder itself exists to deal with only TimeZoneInfo objects as they (Time Zones) are used within the application so it is registered in the Application_Start method in the global like so:
  binders.Add(new System.Collections.Generic.KeyValuePair<Type, IModelBinder>(typeof(TimeZoneInfo), new TimeZoneInfoModelBinder()));

Where binders is of type ModelBinderDictionary.  The binder itself then looks like this:
public class TimeZoneInfoModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException("bindingContext");
        }
        string tzId = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;

        try
        {
            return TimeZoneInfo.FindSystemTimeZoneById(tzId);
        }
        catch (Exception ex)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
        }
        return null;
    }
}

Now from stepping through the code I know this Binder is only called when I POST data back to the server that involves a particular Model which has a TimeZoneInfo property on it.  My assumptions are:

*

*The runtime "knows" about all of the models and only invokes the custom binder when it finds a property with the same type as the one that was passed in to the binder.

*The reason this is being done is because the TimeZoneInfo type is a complex type and, therefore, can't be implicitly converted to from a string (POST data)

Is this a correct understanding of this particular instance or am I missing something?
Thanks!

A: You're close...
The model binder considers all of the data from the request's form data, the URL query string, and routing parameters.  The binder will attempt to bind to the arguments of the action method and to any public properties of the model that have both a get and set defined.  This is done by considering the name of the parameter and/or public property.
Since all of the input sources are in a name-value format, the names are matched.  For example, if there is an "id" routing parameter and your action method has an "id" argument in its signature, the binder will bind the routing parameter to that action method argument.  If there is a country form field and a model with a public country property, the model binder will attempt to bind the form field to the model.  Etc.
The binder considers the type of the property when binding.  The default model binder knows how to bind to the scalar properties (int, decimal, DateTime, etc.).  It also can bind to a list (key format MyList[0]) or to a complex type that in turn exposes child properties (e.g, key format Rectangle.Width).
The example you have posted adds the ability to bind to a TimeZoneInfo object.  That binder is being invoked because the name of a form parameter, query argument or routing parameter matches the name of a public property on your model that exposes a getter and setter that returns a TimeZoneInfo object.
Note the ModelBinder works in concert with the ModelState dictionary.  It's important that invalid user input gets preserved even if it cannot be converted to the target type.  In that case, an error is added to the ModelState dictionary and the raw value of the input parameter is kept so that it can be included in a re-rendering of the form with validation errors.


text:
Q: SQL Server : how can I merge these 2 queries together using a distinct I have a query that gets a list of distinct deviceID's, now I want to join that query with another query that has an inner join.
This is my first query
Select distinct deviceid
from session
where cast(createdon as date) between '01/01/2018' and '01/30/2018'
  and len(deviceid) > 10

That query returns the distinct DeviceId's I need. I now want to use that DeviceID from that query and replace it with the DeviceID in this query
Second query:
select f.PracticeID, F.Name, D.DeviceID, d.SerialNumber
from device d
inner join facility f on f.id = d.locationid
inner join session s on s.deviceid = d.deviceid
where d.deviceID = 'deviceID'

How can I merge those 2? I want to get the results from 1st query and use it for the 2nd query DeviceID column. Right now I am manually executing the DeviceID in the second query that I get from the first. I am using SQL Server 2012

A: You want to get all the data from the second query for the distinct DeviceID from the first one?  This should do it.
select f.PracticeID,F.Name,D.DeviceID,d.SerialNumber from device d
inner join facility f on f.id=d.locationid
inner join session s on s.deviceid=d.deviceid
where d.deviceID in (
     Select distinct deviceid from session where cast(createdon as date) between
     '01/01/2018' and '01/30/2018' and len(deviceid)>10
)

A: You can use a sub query to achieve this :-
select f.PracticeID,F.Name,D.DeviceID,d.SerialNumber from ( Select distinct deviceid from session where cast(createdon as date) between
'01/01/2018' and '01/30/2018' and len(deviceid)>10) d
inner join facility f on f.id=d.locationid
inner join session s on s.deviceid=d.deviceid
where d.deviceID='deviceID'


text:
Q: Summing rows above blank cell until previous blank cell Hello!
I am trying to build a macro, that finds a blank cell in a range in a single column and sums all cells between this blank cell and the previous blank cell.
I've searched the web a lot, and while others have asked this question, i do not find the answers to them particularly helpful in my situation, as i need this to work through 3500+ rows.
E.g:
4
3
4
BLANK 1
2
5
7
1
BLANK 2
1
4
BLANK 3

In this case the cell called "BLANK 1" would be the sum of the 3 previous rows: 4+3+4=11
"Blank 2" would be 15 and so forth.
The range is "G8:G3561".
Edit
For the quick answer see Mr_Nitrogen's answer. It works beautifully!
However, as I am new to VBA and coding in general I do not know how or why the code works.
I am very eager to obtain a better understanding of VBA, which is why I'm continuing this thread (if allowed to).
Furthermore, I would like to provide evidence for the commenters that I have indeed worked on this myself and that I prefer to build my own code.
It's important for me to understand why my code works or doesn't work, which is why i hope that you still want to help me develop my own code.
I finally found an approach that is logical to me. I know that this is not the simplest way to do it, but I would like to know if it could work.
I've written the following code.
Sub Sum_storage()
Dim rng As Range
Dim cell As Range
Dim cell2 As Range
Dim cell3 As Range

Range("G8").End(xlDown).Offset(1, 0).Select
Set cell = Selection
cell.Value = "temp" 'Finds the first blank cell in column G _
                     and creates a temporary value in order _
                     to find the second blank cell

Range("G8").End(xlDown).Offset(1, 0).Select
Set cell2 = Selection

cell.Offset(1, 0).Select
Set cell3 = Selection  'The range i need to sum can _
                        now be described as "cell3:cell2"

Set rng = Range(Range("cell3"), Range("cell2")) 'The code works until this point
cell2.Value = WorksheetFunction.Sum(rng)

The idea is to define the range i want to sum with multiple variables.
My problem is trying to refer to these variables (and setting them in an easier way than using .Offset).
Is it simply not possible to set a range (rng) based on two previously set ranges?
If this is possible the next step for me is creating some kind of loop that could make this work for all 3500+ rows.

A: You were on the right track with using End(xlDown).
This one should be a way faster than looping through all cells, because this jumps to the next empty cell and sums via WorksheetFunction.Sum.
Option Explicit

Public Sub DoMyStuff()
    Dim ws As Worksheet
    Set ws = Worksheets("Tabelle8") 'define your worksheet here

    Dim FirstCell As Range
    Set FirstCell = ws.Range("G8")

    Dim VeryLastCell As Range 'get very last cell as stop criteria
    Set VeryLastCell = ws.Cells(ws.Rows.Count, "G").End(xlUp)

    Do
        Dim LastCell As Range
        If FirstCell.Offset(1) = vbNullString Then 'test if there is only one cell to sum
            Set LastCell = FirstCell
        Else
            Set LastCell = FirstCell.End(xlDown)
        End If

        With LastCell.Offset(1, 0) 'this is the cell we want to write the sum
            .Value = Application.WorksheetFunction.Sum(ws.Range(FirstCell, LastCell))
            .Interior.Color = RGB(255, 0, 0)
        End With

        Set FirstCell = LastCell.Offset(2, 0)

    Loop While FirstCell.Row < VeryLastCell.Row
End Sub

A: This isnt that complicated to do with for loop, maybe something like
lastrow = Cells(Rows.Count, "G").End(xlUp).Row
firstrow = 8
TempTotal = 0
for x = firstrow to lastrow + 1
    If Cells(x, "G") <> "" Then
        TempTotal = TempTotal + Cells(x, "G")
    Else:   Cells(x, "G") = TempTotal
            Cells(x, "G").Interior.ColorIndex = 4
            TempTotal = 0
    End if
    Next x

Ive made an edit to make it a bit simpler
The Logic of the Code:

*

*Define the last row with data in column "G"

*Move down cell by cell until that row

*If the cell has a value in it, add it to the temporary total.

*If it is blank, inset the temporary total and reset the tempTotal to zero

*

*This is the first line, in which we select the very last last cell in column "G", use use End(xlup) on it to get to the last cell with data and use .row to get the row number of that cell

*Set up a For loop, which runs the code between "for" and "next x" lines repeatedly while incrementing the value of x from "firstrow" to "lastrow + 1" each time it repeats ( so if firsrow is 1 and lastrow is 100) then it will run the code 100 times with x = 1,2,3,4,5 etc.)

*this is the "if" statement, "<>" means does not equal, so we are saying if the cell on row x, col "G" is not equal to "" which is an empty string (or nothing) then we do the next line (add its value to tempTotal)

*if the "If" statement isnt true (if the cell is blank) then we do what is under the "Else" and make that cell equal to TempTotal, change its color to green (4 is a colorcode, they go between 1 and 50), and reset the temptotal to 0.


text:
Q: Redirecting in Yesod to Routes with Arguments Assume I have a route
/argument/#Int ArgumentR GET POST

and the corresponding handlers
getArgumentR :: Int -> Handler Html
getArgumentR x = undefined

postArgument :: Int -> Handler Html
postArgument x = do
    ...
    redirect (??)

where, after running a form, I want to redirect from the post to the get Handler (for the same x). How can I turn ArgumentR into an excepted Route, i.e. apply the argument x to ArgumentR?

A: Routes like ArgumentR listed in routes file are simple data constructors. The number of arguments they take equals to the number of #-pieces in its declaration. So, in your case you need
redirect (ArgumentR x)


text:
Q: show this is a orthogonal basis let $f_n = \frac{1}{\sqrt{2\pi}} e^{inx}$ show that the set $ T = \{ f_n \}$ is an orthogonal basis on $L^2([-\pi,\pi]) \subset H$.
I have shown it is orthogonal, but not a basis. My idea was to take an element g in $T^\perp$ and show that element must be $0$:
if $g \in T^\perp$ then $<g,f_n> = 0 \iff \frac{1}{\sqrt{2\pi}} < g , e^{inx}> 0 $ but I cant conclude $g = 0$


text:
Q: Display new line in MS Charts Tooltip I am using MS Charts in my project and things are going well. I am using this article for complex Tooltip content, When i addd line break "\n" its working properly on IE but not on Firefox.
Check the following screenshots, any help will be appreciated.
IE:

Firefox:

A: I am looking into a similar solution but it seems many line feed characters work in IE but none in firefox.
Here is a link to that -
How can I use a carriage return in a HTML tooltip?
The other thing you can try is to use a widget like Yahoo tooltip -
http://developer.yahoo.com/yui/examples/container/tooltip.html


text:
Q: urllib error: cannot fetch html data. Python, Beagle Bone Black I was making my project on mac and I tried to do the same things by Beagle Bone Black(BBB).
However, I couldn't use urllib in BBB so I am stuck: I cannot go forward.(it is working well in my mac)
I tried this simple code as an example:

import urllib
conn = urllib.urlopen('http://stackoverflow.com/questions/8479736/using-python-urllib-how-to-avoid-non-html-content')

then this Error occurred:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/urllib.py", line 86, in urlopen
    return opener.open(url)
  File "/usr/lib/python2.7/urllib.py", line 207, in open
    return getattr(self, name)(url)
  File "/usr/lib/python2.7/urllib.py", line 351, in open_http
    'got a bad status line', None)
IOError: ('http protocol error', 0, 'got a bad status line', None)

I need to fetch a html data for my project.
How can I solve this problem? Do you have any ideas ?
Thank you.
When I tried urllib2
I got this:
>>> import urllib2
>>> conn = urllib2.urlopen('http://stackoverflow.com/questions/8479736/using-python-urllib-how-to-avoid-non-html-content')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 418, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1207, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1180, in do_open
    r = h.getresponse(buffering=True)
  File "/usr/lib/python2.7/httplib.py", line 1030, in getresponse
    response.begin()
  File "/usr/lib/python2.7/httplib.py", line 407, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python2.7/httplib.py", line 371, in _read_status
    raise BadStatusLine(line)
httplib.BadStatusLine: ''

Also I tried this:
curl http://stackoverflow.com/questions/8479736/using-python-urllib-how-to-avoid-non-html-content
curl: (52) Empty reply from server

and this:
wget http://stackoverflow.com/questions/8479736/using-python-urllib-how-to-avoid-non-html-content
Connecting to stackoverflow.com (198.252.206.16:80)
wget: error getting response

but they didn't work
at home, I also tried and failed but returns a different error:
conn = urllib2.urlopen('http://stackoverflow.com/questions/8479736/using-python-urllib-how-to-avoid-non-html-content')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 418, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1215, in https_open
    return self.do_open(httplib.HTTPSConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1177, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno -2] Name or service not known>

environment
BBB: Linux beaglebone 3.8.13 #1 SMP Tue Jun 18 02:11:09 EDT 2013 armv7l GNU/Linux
python version: 2.7.3

A: I'm really want to recommend you requests lib:
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'

http://www.python-requests.org/en/latest/
How to install:
sudo pip install requests


text:
Q: How do we denote the $0$ vector in a Quotient Space $V /W$? Just $0$ or $0 + W$? Unfortunately my textbook has no mention of the notation for this, nor can I find clarification for this online.

A: I think the most standard way to write it is just $0$, but you can also call it $0 + W$ or $[0]$. There is no fixed notation in this sense: Different books use different notations.


text:
Q: How do i plot multiple axvspan OR vspan's on a line plot when value is True I'm trying to highlight on a line chart that has a line of stock price, and then a band above and below the stock price line.
I have a column whose value is "1" every time the stock price exceeds the bands, and Nan when the stock price is in between the lines.
I want to highlight the regions where the value is "1", or when the stock price exceeds the bands. This happens multiple times, and I am unable to find a way to create more than one vspan correctly.
I am using pandas. The dates are the x-axis and are indexed. Any help with this?
I've been looking at plotly extensively for a day now, but don't see it being possible. I am struggling to figure out how to use matplotlib for this.
In the code below, i am trying to compare "OPEN" (the column that is a 1 if price exceeds a band) and "AAPL.O", which is the ric variable that is the closing price
def add_SMA_bands(data,ric):
    df = pd.DataFrame(data[ric])
    SMAname = "SMA_{}".format(ric)
    SMAstd = "SMAstd_{}".format(ric)
    SMAUpper = "UpperBand_{}".format(ric)
    SMALower = "LowerBand_{}".format(ric)
    df[SMAname] = df["{}".format(ric)].rolling(SMA).mean()
    df[SMAUpper] = df[SMAname] + (df["{}".format(ric)].rolling(SMA).std())*2
    df[SMALower] = df[SMAname] - (df["{}".format(ric)].rolling(SMA).std())*2
    return df

dfs={}

for ric in rics:
    df = add_SMA_bands(data,ric)
    df.dropna(inplace=True)
    dfs[ric]=df

for ric in rics:
    dfs[ric]["OVER"] = np.where(dfs[ric][ric]<dfs[ric]["LowerBand_{}".format(ric)],1, (np.where(dfs[ric][ric]>dfs[ric]["UpperBand_{}".format(ric)],1,0)))
    dfs[ric]["OVER"][dfs[ric]["OVER"]==0]=np.nan