text:
Q: Running Jax-rs 2.1 HTTP PATCH on Wildfly - 405 Method Not Allowed I am trying to run a rest api with a http patch method on a wildfly 10.1.0.Final. If I made a request on this endpoint i get a 405 Method Not Allowed.
I use javax.javaee-api:8.0.
Patch:
@PATCH
@Path("/documents/{id}")
public Response patchDocument(@PathParam("id") String id,
        @ApiParam(value = "", required = true) @Valid PatchRequestSTO jsonPatch) {
    return ok(jsonPatch.toString()).build();
}

Response: 405 Method Not Allowed
Allow:OPTIONS, PUT
Connection:keep-alive
Content-Length:0
Date:Fri, 05 Jan 2018 07:55:44 GMT
Server:WildFly/10
X-Powered-By:Undertow/1

Put:
@PUT
@Path("/documents/{id}")
public Response putDocument(@PathParam("id") String id,
        @ApiParam(value = "", required = true) @Valid PatchRequestSTO jsonPatch) {
    return ok(jsonPatch.toString()).build();
}

Response: 200 Ok

A: Are you using javax.javaee-api:8.0 as dependency in your project? That is not enough to run a Java EE 8 application on WildFly 10.1.0.Final, because wildfly does not support it.
So you need an application server (Glassfish, Open Liberty, ...) that is supporting JavaEE 8 to use the new features.


text:
Q: amazon-memory-db MemoryDB is compatible with Redis, a popular open source data store, enabling you to quickly build applications using the same flexible and friendly Redis data structures, APIs, and commands that they already use today.
With MemoryDB, data is stored in memory, which enables you to achieve microsecond read and single-digit millisecond write latency and high throughput. MemoryDB also stores data durably across multiple Availability Zones (AZs) using a Multi-AZ transactional log to enable fast failover, database recovery, and node restarts.
See: What is MemoryDB for Redis?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it valid to cast integer to GLvoid* in C++20 using bit_cast? A previous question has asked for how to cast between integer types and GLvoid* in C++11 (based on the tags for that question) but here I'm interested in C++20.
Now that there is std::bit_cast as an option for doing type conversion, I'm wondering if it would be the "correct" way to use integers with OpenGL functions that for historical reasons take a GLvoid* to represent a byte offset (e.g. glDrawRangeElements), or whether the methods referenced at the previous question should be used instead.

A: bit_cast is definitely the wrong thing here. void* is not required to be the same size as most integer types. bit_cast requires that the source and destination types have the exact same size. Therefore, on 32-bit systems, a std::bit_cast<void*>(24ull) is a compile error. While on 64-bit systems, a simple std::bit_cast<void*>(24) is a compile error.
And not even uintptr_t is required to have the same size as a pointer; only that it has at least as many bits as a pointer. If it has more, then bit_cast will choke on it.
Just do a reinterpret_cast<void*>, if you don't feel like using a C-style cast.

A: No, although (with an appropriately-sized integer) it will often work in practice, and none of this is strictly-conforming anyway.  This is a C API, so it means (void*)offset (in C).  If your toolchain has the expected C compatibility), you can write that in C++, in which case it's equivalent to reinterpret_cast<void*>(offset), but not necessarily to bit_cast<void*>(offset) (which preserves the bit pattern even if reinterpret_cast doesn't and additionally requires that sizeof offset==sizeof(void*)).


text:
Q: Copy files inside of docker container before volumes are created (Solr docker image with custom configuration) I need to create docker container with Solr that has custom configuration created.
In order to create that config when installed not in docker container I need to do the following:
cp -r /opt/solr/server/solr/configsets/basic_configs /opt/solr/server/solr/configsets/myconf

Then I have to copy my custom schema.xml to that location:
cp conf/schema.xml solr/server/solr/configsets/myconf/conf

And then remove managed schema:
rm /opt/solr/server/solr/configsets/nutch/conf/managed-schema

I have this docker-compose.yml that I need to modify to do the same as commands above:
version: '3.3'
services:
  solr:
    image: "solr:7.3.1"
    ports:
     - "8983:8983"
    volumes:
      - ./solr/conf/solr-mapping.xml:/opt/solr/conf/schema.xml
    entrypoint:
      - docker-entrypoint.sh
      - solr-precreate
      - mycore

schema.xml can go to valumes part, but I don't really understand where should I place this first cp and rm commands.
Thanks!

A: You can add your commands to your docker compose file (
https://docs.docker.com/compose/compose-file/#command)
version: '3.3'
services:
  solr:
  image: "solr:7.3.1"
  ports:
    - "8983:8983"
  volumes:
      - ./solr/conf/solr-mapping.xml:/opt/solr/conf/schema.xml

  command: 'bash -e -c "precreate-core mycore; cp /opt/solr/conf/schema.xml /opt/solr/server/solr/mycores/mycore/conf/schema.xml; cp /opt/solr/conf/solrconfig.xml /opt/solr/server/solr/mycores/mycore/conf/solrconfig.xml; rm /opt/solr/server/solr/mycores/mycore/conf/managed-schema; solr-foreground;"'

it works for me


text:
Q: placing button menu in lightning-tile lwc I am trying to create a tile which will iterate records. I am trying to place the button menu exactly opposite to "Salesforce UX" towards right corner. I am unable to it. Below is my code. How to place it towards right corner of tile.

                Salesforce UX

                <lightning-button-menu alternative-text="Show menu">
                    <lightning-menu-item value="MenuItemOne" label="Menu Item One"></lightning-menu-item>
                    <lightning-menu-item value="MenuItemTwo" label="Menu Item Two"></lightning-menu-item>
                    <lightning-menu-item value="MenuItemThree" label="Menu Item Three"></lightning-menu-item>
                    <lightning-menu-item value="MenuItemFour" label="Menu Item Four"></lightning-menu-item>
                </lightning-button-menu>

Name:

Description for first label

Address:

Description for
                        second label
                        Description for second label

Industry:

Manufacture

CreatedDate:

2021-11-12

Phone:

+1 1111111111

A: The Tile blueprint provided by the Lightning Design System shows how to accomplish this.
The key piece you're missing is using slds-grid and slds-grid_align-spread to put the title and actions in the same row, spread aligned to the left and right.

        Tile Title

A: add this: slot="actions"
https://developer.salesforce.com/docs/component-library/bundle/lightning-card/example


text:
Q: Does Java have a data structure that supports Concurrent Modification? I'm making a game in Java. Every enemy in the game is a thread and they are constantly looping through the game's data structures (I always use the class Vector).
Lately I have been getting the "ConcurrentModificationException" because an element is being added/removed from a Vector while a Thread is looping through it. I know there are strategies to avoid the add/remove problem (I actually use some to avoid problems with Removes but I still have problems with "Adds").
I heard that java supports a Vector/List that avoids the ConcurrentModificationException.
Do you have any idea of what this structure might be?
Thanks.

A: Check out java.util.concurrent, it has what you're looking for.

A: CopyOnWriteArrayList. But read its javadocs carefully and consider if in practice it gives the behavior that you are expecting (check Memory Consistence effects), plus if the performance overhead is worth it. Besides synchronization with ReentrantReadWriteLock, AtomicReferences, and Collections.synchronizedList may help you.


text:
Q: Multiplication of elements in list of lists hello I am trying to multiply certain lists in a list of lists by variables.
let's say I have the following
[['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
 ['cow', 4, 3, 2, 10],
 ['pig', 20, 4, 7, 2]]

and the following variables :
cows = 2
pigs = 4

How would I multiply the cow list by the variable cow and the pig list by the variable pig to create
[['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
 ['cow', 8.0, 6.0, 4.0, 4.0],
 ['pig', 80.0, 16.0, 28.0, 8.0]]

It doesnt have to be floats, but this would be ideal.
I tried it with something like this
matrix = [['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
          ['cow', 4, 3, 2, 10],
          ['pig', 20, 4, 7, 2]]
cows = 2
pigs = 4
weightmatrix = []

for value in matrix:
    try:
        weightmatrix.append(matrix[1]*cows)
        weightmatrix.append(matrix[2]*pigs)
    except:
        pass
print(weightmatrix)

However for me this creates double the elements in every list, it just seems to copy and paste the list behind each other instead of multiplying the values.

A: Here's how I'd solve it:
matrix = [['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
          ['cow', 4, 3, 2, 10],
          ['pig', 20, 4, 7, 2]]
multipliers = {
    "cow": 2,
    "pig": 4,
}

for i, row in enumerate(matrix):
    m = multipliers.get(row[0])
    if m is not None:
        matrix[i] = [row[0]] + [x * m for x in row[1:]]

A: You need to replace each item individually in the list when you get a match. You can't just multiply the whole list.
I would also suggest putting the operations into  dict for convenience.
matrix = [
    ['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
    ['cow', 4, 3, 2, 10],
    ['pig', 20, 4, 7, 2],
]
ops = {
    'cow': 2,
    'pig': 4,
}

for row in matrix:
    if row[0] in ops:
        for i in range(1, len(row)):
            row[i] *= ops[row[0]]


text:
Q: Is it possible to calculate Monte Carlo without the unit of square? I am in economic, first day a novice in Monte Carlo even both, today my stranger friend give me a sample to finding pi area using Random Sample where area of circle divided by area of square
my question is:

*

*Why the sample should be and always use pi in the area of square of box. Could i change the pi function with supply and Demand function or any economic functions?

*If the the pi function in monte carlo always use box square as the exterior, Is it possible without the square to calculate the pi as interior?

A: I'm afraid I don't understand your first question fully, so I'll skip that. But as for your second, any shape with a known area is fine. You can use a 4657-gon for all it matters, as long as you know the area. Obviously, if you use a 4657-gon, you're gonna have a pretty hard time determining which points are in and out of the inside shape. Essentially, for your situation, if you can stick a circle in it, it's fine.


text:
Q: How can I dynamically change the number of items in a JComboBox private void dropDownMenu(JPanel jp1, String prodId){
    int len = storeManager.getInv().getStockAmount(prodId);
    int[] nums = new int[len];
    String[] numPossible = new String[len];

    for (int i=0; i<len; i++){
        nums[i] = i+1;
    }
    for (int i=0; i<len; i++){
        numPossible[i] = String.valueOf(nums[i]);
    }
    JComboBox<String> cb = new JComboBox<String>(numPossible);
    JButton okButton = new JButton("Add To Cart");
    okButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Product p1 = storeManager.getInv().getProd(prodId);
            String quan = (String) cb.getSelectedItem();
            int quantity = Integer.parseInt(quan);
            if (quantity > storeManager.getInv().getStockAmount(prodId)) {
                System.out.println("Not Enough Stock.");
            } else {
                storeManager.getCart().addToCart(p1, quantity);
                storeManager.getInv().removeStockAmount(prodId, quantity);
                //update the dropdown menu here
            }
        }
    });
    jp1.add(cb);
    jp1.add(okButton);
}

Essentially what i am looking for is that whenever i select a number from the drop down menu, i want the number of items in the menu to be reduced by the amount that was added to cart. for example if i add 5 to cart then i want the dropdown menu to go from allowing me to choose 10 to 5 only.
Image of GUI

A: As a thought...Instead of doing all these conversions from integer to string and string to back to integer in order to fill your combo box, why not just have a combo box of Integer? You're dealing initially with integer quantity values anyways:
JComboBox<Integer> cb = new JComboBox<>();
int len = storeManager.getInv().getStockAmount(prodId);
for (int i = 1; i <= len; i++) {
   cb.addItem(i);
}
cb.setSelectedIndex(0);

Your action listener might look something like this now:
okButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        Product p1 = storeManager.getInv().getProd(prodId);
        int quantity = (int) cb.getSelectedItem();
        /* This 'if' statement below would be moot if the Combo-Box
           is properly updated unless editing is allowed in the combo
           which in this case...disable that feature.     */
        if (quantity > storeManager.getInv().getStockAmount(prodId)) {
            System.out.println("Not Enough Stock.");
        } else {
            storeManager.getCart().addToCart(p1, quantity);
            len = storeManager.getInv().removeStockAmount(prodId, quantity);
            cb.removeAllItems();
            for (int i = 1; i <= len; i++) { cb.addItem(i); }
            cb.setSelectedIndex(0);
        }
    }
});

Possibly better yet would be to utilize the JSpinner component instead of a Combo Box. A drop-down list in this use case always seems a bit obtrusive in my opinion.


text:
Q: How to pass arguments from tornado to a html file? I have shared a part of my code and in the Class 'Room',variable 'nw' has the query string value.Now,I want the html file to autofill the 'nw' field with the query string value dynamically.How do I get that?Does self.get_namespaces help?
    class Room(tornado.web.RequestHandler):
    def get(self):
       nw=self.get_argument("nw")
       print(nw)
       self.render("RoomPost.html")

class static(tornado.web.RequestHandler):
    def get(self,key):
           iname="static/" +key
    print iname
              self.render(iname)
settings = {
    'debug': True,
    'static_path': 'static'}

application = tornado.web.Application([

        (r"/room",Room ),

        #(r"/static/(.*)",static)
        ], **settings)
if __name__ == "__main__":
    application.listen(5500)
tornado.ioloop.IOLoop.instance().start()

Following is the html file

<link rel="stylesheet" href="{{ static_url("css/registration.css")}} />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<c:import url="InnerHeader.js"></c:import>

    <form action="/room" method="post" >
    <fieldset>
        <legend>
            <b1>Room Add</b1>
        </legend>

                Name of NW/Name of Home
                <input type="text" name="nw" placeholder="Kfx-Home"
                    maxlength="15" size="30" autofocus required/>

                 &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
                <input type="submit"     value="  Submit  " />

        </fieldset>
    </form>

A: The following link helped me figure out the answer:
How to pass arguments from tornado to a js file but not html?.
I added self.render("RoomPost.jsp",nw=nw)  in tornado script and autofocus required value="{{nw}}" readonly/> in .jsp script.


text:
Q: CakePHP Options: Not sure about this entry I  have this in my options
a:4:{i:0;s:10:"Test";i:1;s:12:"FMy Files";i:2;s:7:"Walmen ";i:3;s:15:"Testing on the roof";}

How do I read or interpret it?
Does it floow have a certain criterion?
What is it called?

A: This is not JSON (notice the semicolons). This is serialized PHP data. You shouldn't have to do anything with it, and certainly not edit it (as you've obviously done, I guess to anonymise it): this is generated by PHP and should only be manipulated by the proper script. It contains metadata about itself, for data integrity checking, I think: Types and Lengths.

A: $x = json_decode($jsonEncodedString);

Update: After I read the code more closely, it seems, that this isn't JSON. This may be serialized PHP as @passcod already mentioned, but its broken. For example the segment s:10:"Test" describes a 10-characters String with content Test, that is obviously wrong. Simply unserialize() will fail. Dont know, where you get this from, but you should repair "the creator".


text:
Q: Convert multiple GeoTIFF to one KMZ I am using GDAL to convert GeoTIFF to KMZ. I am using the following command:
gdal_translate.exe -of KMLSUPEROVERLAY *.tif out.kmz

If I have one TIF file in the folder, it works ok. If I have more than one, then I receive the following error:
FAILURE: Too many command options.

How can I run the gdal_translate.exe command to combine more than one TIF file into one KMZ file?

A: If you have more than one GeoTIFF, you can mosaic them before the conversion. For instance, you can make a virtual mosaic from all of them contained in the same directory:
gdalbuildvrt mosaic.vrt *.tif
gdal_translate -of KMLSUPEROVERLAY mosaic.vrt out.kmz


text:
Q: Does a graph contain a 3-cycle or a 4-cycle Given a graph $\mathscr G$, that has 100 nodes each with a degree  can you show that this graph contains a 3-cycle and/or a 4-cycle?
The graph in question represents 100 people at an event, and they each know $\ge 70$ people. I need to prove that there a 3 people there who know eachother. So I translated it to finding a 3-cycle in the graph.
I've approached it this way:
3 people know 70 people minimum. So any 3 nodes $n \in  \mathscr G$  have $\sum deg(n)$$\ge$ $3*70$.
This means that these 3 people at least have $(3*70) - 100 = 110$ nodes in common. These nodes can be friends with 2 OR 3 persons.
This is where I'm not so sure anymore:
Suppose each node has only been counted twice. This means that 2 of the 3 persons should have $55$ nodes in common, which leaves out the 3rd person who knows $70$ other people.
If two people have $55$ nodes in common, they each have a minimum of $15$ unique nodes. This makes a total of $85$ nodes for the both of them.
So, $100 - 85 = 15$. This means that there are only 15 people who are still left unconnected. So, the third person should at least be connected to 55 other nodes too.
Worst case, 30 of these nodes are the unique nodes from person 1 and 2. So at least 25 nodes are connected to person 1, 2 and 3.
Which leads us to a contradiction that there is a 3-cycle.
Is this a valid proof?

A: Consider the following theorem:
Let $G = (V,E)$ be a simple graph. If $|E|>\frac{1}{4}\cdot |V|^2$, then $G$ contains a triangle.
Let us probe your problem: We know $|V|= 100$.
From $2 \cdot |E| = \sum_{v \in V} d(v) \geq \sum_{v \in V} 70 = 100 * 70 = 7000$ follows $|E| \geq 3500$.
Since $\frac{1}{4}\cdot |V|^2 = \frac{1}{4}\cdot 10000 = 2500$, it follows that your graph does contain a triangle.
As reference for this theorem (including its proof) see theorem 1.7 on page 12 in "Handbook of Combinatorics", Vol. 1, ISBN-10: 0262571722.

A: Divide the group in half.  The fifty people in one half must each know at least 20 people in their half.  The maximal girth 5 cage graph for 50 vertices is the Hoffman-Singleton graph, with degree 7.
If each person knows more than 57 people, a 3 or 4 cycle is also forced.


text:
Q: Quit unexpectedly while using the libjvm.dylib plug-in I'm creating an application with Java 1.8 and running on Mac but
my application have problem running on Mac OSX 10.8 always showing error "quit unexpectedly while using the libjvm.dylib plug-in"
but on other OSX runs smoothly without problem.
Here's the error...
Process:         java [247]
Path:            /usr/bin/java
Identifier:      net.java.openjdk.cmd
Version:         1.0 (1.0)
Code Type:       X86-64 (Native)
Parent Process:  ??? [1]
User ID:         501

PlugIn Path:       /Users/Shared/*/libjvm.dylib
PlugIn Identifier: libjvm.dylib
PlugIn Version:    ??? (1)

Date/Time:       2015-04-22 00:57:51.018 -0700
OS Version:      Mac OS X 10.8 (12A269)
Report Version:  10

Interval Since Last Report:          21289 sec
Crashes Since Last Report:           12
Per-App Interval Since Last Report:  1821 sec
Per-App Crashes Since Last Report:   11
Anonymous UUID:                      829F8A3C-A684-4821-9CC3-7C29F828A3ED

Crashed Thread:  31  Java: QuantumRenderer-0

Exception Type:  EXC_BAD_ACCESS (SIGABRT)
Exception Codes: EXC_I386_GPFLT

Application Specific Information:
abort() called

Thread 0:: AppKit Thread  Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff8d713686 mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff8d712cf7 mach_msg + 251
2   com.apple.CoreFoundation        0x00007fff8df29f23 __CFRunLoopServiceMachPort + 195
3   com.apple.CoreFoundation        0x00007fff8df2f606 __CFRunLoopRun + 1078
4   com.apple.CoreFoundation        0x00007fff8df2edd2 CFRunLoopRunSpecific + 290
5   com.apple.HIToolbox             0x00007fff948c8774 RunCurrentEventLoopInMode + 209
6   com.apple.HIToolbox             0x00007fff948c8512 ReceiveNextEventCommon + 356
7   com.apple.HIToolbox             0x00007fff948c83a3 BlockUntilNextEventMatchingListInMode + 62
8   com.apple.AppKit                0x00007fff938eafa3 _DPSNextEvent + 685
9   com.apple.AppKit                0x00007fff938ea862 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
10  libosxapp.dylib                 0x000000019dff442a -[NSApplicationAWT nextEventMatchingMask:untilDate:inMode:dequeue:] + 124
11  com.apple.AppKit                0x00007fff938e1c03 -[NSApplication run] + 517
12  libosxapp.dylib                 0x000000019dff423e +[NSApplicationAWT runAWTLoopWithApp:] + 156
13  libsplashscreen.dylib           0x000000019dfd3128 __SplashInitPlatform_block_invoke_1 + 360
14  JavaNativeFoundation            0x000000019d7cfe5c +[JNFRunLoop _performCopiedBlock:] + 15
15  com.apple.Foundation            0x00007fff9098c8a7 __NSThreadPerformPerform + 225
16  com.apple.CoreFoundation        0x00007fff8df0c841 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
17  com.apple.CoreFoundation        0x00007fff8df0c165 __CFRunLoopDoSources0 + 245
18  com.apple.CoreFoundation        0x00007fff8df2f4e5 __CFRunLoopRun + 789
19  com.apple.CoreFoundation        0x00007fff8df2edd2 CFRunLoopRunSpecific + 290
20  java                            0x000000010beba6cc CreateExecutionEnvironment + 871
21  java                            0x000000010beb665c JLI_Launch + 1952
22  java                            0x000000010bebc68a main + 101
23  java                            0x000000010beb5eb4 start + 52

Thread 1:
0   libsystem_kernel.dylib          0x00007fff8d715386 __semwait_signal + 10
1   libsystem_c.dylib               0x00007fff95909ce5 pthread_join + 847
2   java                            0x000000010beb9ccc ContinueInNewThread0 + 102
3   java                            0x000000010beb72d0 ContinueInNewThread + 201
4   java                            0x000000010beb9aa1 JVMInit + 315
5   java                            0x000000010beb704e JLI_Launch + 4498
6   java                            0x000000010bebc68a main + 101
7   java                            0x000000010beba35e apple_main + 92
8   libsystem_c.dylib               0x00007fff9587f782 _pthread_start + 327
9   libsystem_c.dylib               0x00007fff9586c1c1 thread_start + 13

Thread 2:
0   libsystem_kernel.dylib          0x00007fff8d7150fa __psynch_cvwait + 10
1   libsystem_c.dylib               0x00007fff95883fc9 _pthread_cond_wait + 869
2   libjvm.dylib                    0x000000010c46e473 Parker::park(bool, long) + 495
3   libjvm.dylib                    0x000000010c55fd4c Unsafe_Park + 126
4   ???                             0x000000010d47a9aa 0 + 4517767594
5   ???                             0x000000010d47ade6 0 + 4517768678
6   ???                             0x000000010d08f160 0 + 4513657184
7   ???                             0x000000010d08f98d 0 + 4513659277
8   ???                             0x000000010d08f98d 0 + 4513659277
9   ???                             0x000000010d08f98d 0 + 4513659277
10  ???                             0x000000010d08f710 0 + 4513658640
11  ???                             0x000000010d08f160 0 + 4513657184
12  ???                             0x000000010d08f710 0 + 4513658640
13  ???                             0x000000010d08f98d 0 + 4513659277
14  ???                             0x000000010d08f98d 0 + 4513659277
15  ???                             0x000000010d08f98d 0 + 4513659277
16  ???                             0x000000010d08f98d 0 + 4513659277
17  ???                             0x000000010d08f710 0 + 4513658640
18  ???                             0x000000010d08f98d 0 + 4513659277
19  ???                             0x000000010d08f98d 0 + 4513659277
20  ???                             0x000000010d08f98d 0 + 4513659277
21  ???                             0x000000010d0884e7 0 + 4513629415
22  libjvm.dylib                    0x000000010c2e8516 JavaCalls::call_helper(JavaValue*, methodHandle*, JavaCallArguments*, Thread*) + 1710
23  libjvm.dylib                    0x000000010c31d58b jni_invoke_static(JNIEnv_*, JavaValue*, _jobject*, JNICallType, _jmethodID*, JNI_ArgumentPusher*, Thread*) + 447
24  libjvm.dylib                    0x000000010c316785 jni_CallStaticVoidMethod + 349
25  java                            0x000000010beb7c82 JavaMain + 2456
26  libsystem_c.dylib               0x00007fff9587f782 _pthread_start + 327
27  libsystem_c.dylib               0x00007fff9586c1c1 thread_start + 13


text:
Q: accidentally loaded schema into the actual postgres database I just did this:
    my_db=> \c postgres
    postgres=> alter table my_db rename to my_db_27032011;
    ALTER DATABASE
    postgres=> create database my_db
    CREATE DATABASE
    postgres=> \i my_fixed_db_schema.sql
    CREATE TABLE
    ALTER TABLE
    INSERT
    INSERT
    ....

    postgres=>

See the mistake? This would be fine if my_db was small, but it's not - it's over a thousand tables, with constraints and triggers all over the place.
Any clues as to how I can undo this? I don't have a backup of the postgres db itself because, well, what sort of idiot would break that?
It's probably not going to affect day-to-day running, as the actual postgres tables are (probably) intact. It's just messy and I'd like to fix it, but without re-installing the entire server.


text:
Q: Legendre Symbol, $(\frac{a}{p})=(\frac{a+1}{p})=1$ Show that for every prime p ($p>5$) there exist integers $a$ and $b$ with $1\leq a,b\leq p-1$ such that:
$$\left(\frac{a}{p}\right)=\left(\frac{a+1}{p}\right)=1$$
I tried assuming that there was no integers such that the condition above was true, but I couldn't get to any contradiction.
thank you guys for any hint or adivice you could give me.


text:
Q: Getting different answers between Numpy and manual calculation I have several matrices:
A=np.array([[-4, -1, -3] ,[1, -4,5],[ 3,4,3],[-5, -1,2]])
b = np.array([[-1], [4],[-4],[-2]])
x=np.array([[ 0.58732799],[-1.19370936],[-0.22879177]])

I want to calculate the residual, r = Ax-b
r=A@x-b

print(r)

[[ 0.53077272]
 [ 0.21820656]
 [ 0.30077121]
 [-0.20051414]]

If I take the norm of r, I get:
print(np.linalg.norm(r))
0.678235

If I do the same thing in numpy, I get a different answer:
x,residuals,rank,sigma=np.linalg.lstsq(A,b,rcond=None);
print("Vector x:\n " + repr(x))
print(residuals)

Vector x:
 array([[ 0.58732799],
       [-1.19370936],
       [-0.22879177]])
[0.46000302]

Namely, the residuals are not identical. Does someone know why?

A: https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html says:

residuals:
  Sums of residuals; squared Euclidean 2-norm

It is the square of what you calculated in the first example.
>>> 0.678235 * 0.678235
0.460002715225


text:
Q: Error when running CloudKit example I get the following error when trying to run the most basic Cloudkit example, as shown here http://getcloudkit.com/curl.html:
 /Users/ed/.rvm/gems/ruby-1.9.2-p180/gems/cloudkit-0.11.2/lib/cloudkit/rack/builder.rb:43
 :in `expose': undefined method `<<' for nil:NilClass (NoMethodError)
 from /Users/ed/Work/Play/config.ru:3:in `block in <main>'

from /Users/ed/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/lib/rack/builder.rb:51:in `instance_eval'
from /Users/ed/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/lib/rack/builder.rb:51:in `initialize'
from /Users/ed/Work/Play/config.ru:1:in `new'
from /Users/ed/Work/Play/config.ru:1:in `<main>'
from /Users/ed/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/lib/rack/builder.rb:40:in `eval'
from /Users/ed/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/lib/rack/builder.rb:40:in `parse_file'
from /Users/ed/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/lib/rack/server.rb:200:in `app'
from /Users/ed/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/lib/rack/server.rb:301:in `wrapped_app'
from /Users/ed/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/lib/rack/server.rb:252:in `start'
from /Users/ed/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/lib/rack/server.rb:137:in `start'
from /Users/ed/.rvm/gems/ruby-1.9.2-p180/gems/rack-1.4.1/bin/rackup:4:in `<top (required)>'
from /Users/ed/.rvm/gems/ruby-1.9.2-p180/bin/rackup:19:in `load'
from /Users/ed/.rvm/gems/ruby-1.9.2-p180/bin/rackup:19:in `<main>'

Any ideas what this could be?

A: You probably have a version of Rack installed which is greater than 1.4
CloudKit is not Rack 1.4 ready.
Quick fix
$ gem uninstall -v '>=1.4' rack
$ gem install rack -v 1.3.6

Update:
Another solution is to specify which version of rack to load by not using rackup but this inline command:
$ gem install rack -v 1.3.6
$ ruby -e "gem 'rack', '=1.3.6'; require 'rack'; Rack::Server.start" config.ru


text:
Q: Please don't exploit the memory of the deceased to promote the network TL;DR:
Please don't exploit the memory of the deceased to promote the network.
That's really all I have.
The following is a description of what happens a week ago.

Steve Jobs died in October. He would have turned 57 a week ago.
A few CHAOS members used this opportunity to promote Ask Different and the network without consulting the community or the Ask Different moderators.
They organized a "party" at the NYC Apple store "to honor Steve Jobs on his birthday" and announced it on the same day just 5 hours before the event on the pretty inactive Meta.Apple.SE site.

NYC area users - join us to celebrate Steve Jobs' Birthday!
Come join Ask Different and Dr. Brendan for a party to honor Steve Jobs on his birthday. The party will start around 3 pm EST, and will take place outside the flagship Apple Store in NYC (59th Street and Fifth Avenue).
There will be black turtlenecks, cupcakes, and dancers. For more information, see this New York Post article covering the event. This event was also covered by CNBC this morning, so we're hoping for a great turnout!
If you can't make it to the event, we will be live tweeting it from @StackApple, so follow along!

This was originally tagged site-promotion, but that was removed later.

The mentioned Twitter coverage at @StackApple looks like this:

The images referenced look like this, and unfortunately don't show the crowd at the event:

The CNBC announcer mentions that the Dr Brendan guy and the SE "community development manager" were "two of his biggest fans".
Unfortunately, the two CHAOS members involved in the announcement haven't bothered to participate on the site they're apparently trying to be promoting so far (1, 2), which doesn't exactly help their credibility in doing something like this.
Given that they apparently aren't that big fans (based on the contributions and interview), and didn't care at all whether any active users of Apple.SE actually showed up (given the late, relatively hidden announcement), all that's left is a PR stunt using the birthday of a dead person to promote two businesses (which that person wasn't even involved it).

Please don't do that.

A: Mmm this isn't the first time this (the act of not giving adequate notice to at least the moderators) was done.
See http://meta.math.stackexchange.com/questions/3212/battle-of-the-sites-cancelled
Putting aside the Steve Jobs comment, what I see here is misrepresentation of the Ask Different Community. Here is what I think should be done for next time
For example, this should have appeared on the balloons and notices,

Happy Birthday Steve,
  Love @dr_brendan
  @stackexchange

Moderators have been told more than once that they are not allowed to utilize the Twitter accounts ( Would allowing moderators to update their Stack Exchange sites' Twitter accounts improve visibility and offer more value? ) yet we see it done here instead of it coming from @stackexchange or @stackhq where CHAOS normally operates from.
I have not read the entire CNBC interview because to be honest it felt like a plug for Stack Exchange, though based on what @Lauren said here,

The CNBC interview is all about what big fans Seth and Brendan are of Steve Jobs - they only mention Ask Different to say where Seth is from. I think it's a very tasteful interview, and we don't intend for this to be an excuse for a promotion.

Without going for pitchforks and inspecting Seth's profile
https://apple.stackexchange.com/users/11241/seth-rogers
https://apple.stackexchange.com/users/11241/seth-rogers?tab=reputation
There are +4 points gained, two suggested edits.
0 comments.
0 answers.
0 questions.
No enthusiast badge (assuming he just reads all the posts)
Total reputation: 105.
Not to call out Seth he may have good intentions when saying he was from Ask Different but his public face on the site does not count for much and it just looks bad. This gets back to the whole getting notice to moderators in advance so they can step in the interview or at least be mentioned by Seth.
Who is @dr_brendan and why is there a promoted tweet for him, this looks like conflict of interest from the outside. Sure, have an interview, say you are best of friends but the moment you mention

FF @dr_brendan...

You are going down slippery slopes. You have officially endorsed @dr_brendan on behalf of Ask Different that's a no-non seeing that most of Ask Different doesn't even know who he is. (This goes back to informing mods in advance)
So in summary for next time I suggest,

*

*pinging in advance when working on a SE project (this should have been learned from the Battle of Sites incident)

*don't use the Twitter accounts if you tell the moderators not to do the same

*don't say you belong to a specific site, especially when the stats say otherwise. You belong to Stack Exchange.

Other than that I think it was a good opportunity to promote Stack Exchange not an exploit on Steve and CHAOS is still learning, so no pitchforks this time.

Oh, one more thing
Contact Moderators in advance! All of this would have been averted if you did.
Why is it so hard for you do that?

In response to point 1 Abby T Miller raised she is missing the point of what I said.
*Don't say you belong to Ask Different and you are an Apple fan in same sentence. I don't care that you don't have time but it's a lie to say you are from Ask Different. You may have an account there. I have an account on Cooking you don't see me running around saying I am from Cooking. Because I am not, I just have an account there. This is about representation and you don't represent Ask Different to put bluntly. If you were an actual fan you would have the decency to inform your fellow Appleboys about it. This isn't about deeply being involved but shoot at least something... and if not get advice. To me it looks wrong in every way possible, you say you are big Apple fan you work for Stack Exchange know about Ask Different yet you don't contribute. And you cannot count those meta posts, that's your job*
I sat down and listened to the interview now. How can you think up an idea,

well, seth and i got together and just -- you know, we were brainstorming ideas for a fun event to have for steve jobs' birthday. and, you know, we just kind of came up with the idea of, you know, handing out black turtlenecks.

And have Ask Different fall under the radar in notice. That just doesn't make sense. Don't play with words, you are leaving out the community and moderators out of these brainstorming session for reasons unknown to me and it's not by accident.

... Something at Stack Exchange and Ask Different we take that inquisitiveness ... it's really part of our culture

So Seth didn't explicitly say he was from Ask Different but the "we" instead of "the community" goes along way. Nevertheless I will play down the contribution issue.
Near the end you hear Brendan say we are just going to "wing it"
So I guess that's how the whole cancelled/not cancelled problem appeared.
So this event should have never been un-cancelled. You make moderators jump through hoops to get their promotion proposals to SE Inc. yet SE employees can wing it??!!!? Screw that.

In response to point 2 you fall in your own trap.
The goals of CHAOS per-each-site are a subset of each moderator. Moderators are unpaid evangelists for Stack Exchange because they invest heavily in their site to make sure it is seen and is high quality. The only difference here is that CHAOS has tools and resources readily available to accomplish the task, moderators do not.
There have been numerous occasions where moderators would become confused as to who promotes their site only to be redirected to some template answer by Comm Team about "Moderators can promote if they wish and get the community to help out, if they need more help they can ping CHAOS to see what they can do" The thing is you never know when CHAOS is assigned to your site, so you cannot depend on them unless you are booming with traffic or reaching critical mass.
In terms of Twitter/Social Networks
If something actually occurred on Twitter that a moderator/community member did not like, the solution occurs after the damage. So I don't see how it helps anyone.
There have been instances where the community did indeed try to make their presence known outside of SE via Twitter/Google+/Facebook only to be asked to slap unofficial
So you want us to promote but unofficial so it does not tarnish the name of SE. Ok get it, thus we end up as second rate versions of the Official ones where most users think the official accounts are where it's at only to see walls of bot text instead and the occasional once in a lifetime real person update
The point here is CHAOS is failing hard at communication with moderators, this is not the first time, it's not the second time, this has happened multiple times and the community would like to help out but you are not making that very easy to do
FIX THAT.

A: Nobody disagrees that the Ask Different moderators should have been contacted prior to the event, and Seth or Lauren will continue this conversation with those mods directly. This event was a strange situation because it was canceled originally, but then un-canceled at the very last moment. As such the channels of communication got all thrown off. This is totally our fault.
There are, however, a few points about CHAOS in general that I think need to be made very clear, in response to the original question and to phwd's answer:

*

*CHAOS agents don't have nine kazillion reps like many of the other Stack Exchange employees do. We were hired from outside of the communities and we became Stack Exchange users on the day we joined the company. CHAOS is appointed to work with many of the sites across the network, and we rotate between sites with some frequency. Sometimes someone will work with a site on a topic that's new to them. They start out with 101 rep. Sometimes they know a little something about the topic and can earn some rep. Sometimes they don't. The amount of rep they have does not prohibit them from doing their job. The help of the moderators and the communities is always appreciated regardless of whether or not CHAOS agents have a bunch of rep on the site.

*The goals and functions of CHAOS are different from those of the moderators, so the tools we use will not be identical. Moderators and users will not automatically have access to the same things CHAOS has access to. CHAOS has access to certain very specific site twitter accounts, and we are working out a strategy for how best to use them. It's not clear whether or not site moderators will ever have access to their sites' twitter accounts, but if that happens, it won't be for quite a while. Until then, CHAOS will be using some of the twitter accounts. If members of the community feel that there is a problem with what's being tweeted, the solution is to take it up with the CHAOS team member directly, either in the site's meta, in chat, or via email. We are very accessible and we want to work with you on making our sites more awesome.
All that notwithstanding, the most important point to take away here is that it is our policy to discuss things we do that affect the community with moderators in meta or chat. This particular event fell under the radar, but it will be followed up on with the Ask Different mods.

An update wherein I'll actually address Daniel's original question...
Seth, Lauren and I have had a chat conversation with Daniel and the Ask Different moderators. We understand that a large part of the community feels that this event was in poor taste and we recognize that one of the reasons it seemed that way was because there was very little public communication about it in advance. This was not our intention and it is not something we intend to repeat. The point is taken and the lesson is learned.
We cannot undo the event or go back and change the way it was handled, but we can learn from the mistakes that were made and make sure they don't happen again.


text:
Q: Different batch sizes give different test score (pytorch) I am trying to test my model with different batch sizes and I am getting different dice for different batch sizes.
I am a beginner. I have tried to fix this problem for a long time, but I can't find any effective solution.
The code is here. Thanks!

A: Results changing depending on the batch size?
This is typically related to batch-wise layers such as batch normalization layers. Always check you are in eval mode when testing your code. In your case, net.eval() should fix the issue.

A: It has something to do with your calculation of average metrics, whether they are image-wise (case batch size = 1) averages or minibatch-wise averages. Either way, you have to keep the averaging consistent no matter what batch size you use. One direct solution is to modify your add method of Scoring:
class Scoring():
    def add(self,pred,target):
        self.number += pred.shape[0]
        for pre, tar in zip(pred.unsqueeze(1), target.unsqueeze(1)):
            dice = torch.tensor(get_Dice(pre,tar))
            self.dice += dice
            self.iou += torch.tensor(get_Iou(pre,tar))
            self.spe += torch.tensor(get_Spe(pre,tar))
            self.sen += torch.tensor(get_Sen(pre,tar))
            self.acc += torch.tensor(get_Acc(pre,tar))
            self.pre += torch.tensor(get_Pre(pre,tar))
        return dice


text:
Q: Limits of integral (CMCS 2010 Longlist) Let $f: [0, + \infty) \rightarrow (0, +\infty)$  be a continuous function such that$\lim\limits_{x \rightarrow \infty} \int_{0}^{x}f(t)\,dt=l\in \mathbb{R}$.
Prove that $$\lim\limits_{x \rightarrow \infty}\frac{1}{\sqrt {x}}\int_{0}^{x}\sqrt {f (t)}\,dt = 0.$$

A: By-parts integration ($u=t,~dv=fdt$) and then L'Hôpital's, in that order, gives
$$\triangle=\frac{1}{x}\int_0^x tf(t)dt=\int_0^xf(t)dt-\frac{1}{x}\int_0^x \left[\int_0^tf(\tau)d\tau\right]dt \xrightarrow{x\to\infty} l-l=0.$$
Equating the above with the result of direct application of L'Hôpital's to $\triangle$ gives
$$\lim_{t\to\infty} tf(t)=0.$$
Now apply L'Hôpital's to the original problem, noting $\sqrt{\cdot}$ is continuous on $[0,\infty)$.


text:
Q: Disable One-Page Checkout in OpenCart How can I disable OnePage Checkout in OpenCart?
Version 1.5.x comes with it in the default template and I would rather not use it as we want to have step by step pages and not use Ajax (speed/page views and process serves our needs better) for our customers.

A: It is possible to remove the one-page setup, but you'll have to do a very good work on the template (the checkout folder contains all steps). You will need personalized controllers as well. The built-in checkout page uses jQuery and Ajax to gathering all the information necessary in only one page, to send everything together when the customer clicks "confirm".
Once you don't want to use ajax, you will have to send the information from one page to the next using post requests, putting then in hidden <input>'s and/or in $_SESSION variable. Anyway, you will have some problems with the countries and locations, since OpenCart retrieves then via ajax.
Actually, some time ago I've found some templates on ThemeForest and other sites that implemented what you want, but I don't know if they are available anymore.

A: I would actually recommend you use something like Uber Checkout which while its still a short checkout process, is better visually as you don't have the panels that are standard in 1.5.X. If you're wanting to completely rewrite it to work like the old checkout system, well in theory it's already there, you just need to rewrite the controllers for the various steps to output full pages rather than JSON and put in validations through each step to make sure previous steps have been completed


text:
Q: A quick question concerning error function Why  $\frac{1}{\sqrt{2\pi }}\int_{-\infty }^{\infty}e^{tx}e^{-x^{2}/2}dx$
equals to $e^{t^{2}/2}$ ?
I know it is error function. but I just do not have any basic knowledge about error function and do not know how to derive it.

A: $e^{tx-x^{2}/2}=e^{-(x-t)^{2}/2} e^{t^{2}}$, Make the substitution $y=x-t$ to evaluate the integral.


text:
Q: Does Ubuntu come with a firewall by default? I have been told that Ubuntu comes with the firewall UFW. Is this true? Is there a GUI for it? If so, what is its name and where do I download?
Is it possible for UFW to notify us (like in windows with a pop-up window) when someone wants to access to your PC or when an application wants to access the internet?
If not, is there any firewall for Ubuntu that provides such notifications?

A: Yes Ubuntu has a firewall installed by default.
The Firewall in Ubuntu is iptables . It also comes with an easy to use command line frontend called UFW   (Uncomplicated Firewall).
If you want to change any settings, you can use the graphical front end to that command line front end, GUFW

As for your other question, getting a warning when an application connects to the internet:
I don't know of any programs that do this*, but I have written one. Now, this isn't great quality software - it's a quick hack in fact -but it works all right. You'll notice I haven't packaged it in any way, because I don't have any use for it and I don't think its tested well enough to be deployed on Anything That Matters™
It doesn't even have a name, here's how it looks:

(ignore the German captions, they will be in your local language)
And here's how to use it:

*

*Install Python 3

*download it and save it as a file on your computer

*Via the file properties, mark it as executable

*Double click and choose "Run"

The program will issue a warning for every application that tries to access the internet. It will not prevent it from doing so, but it'll let you know. You then have the option of putting it on a "White List" of trusted applications, which causes it to not warn you again about this particular program.
If you start it from a terminal, you'll get a few useful messages about what it's doing.
Again I have to stress, even though it works, I haven't tested it properly (i.e. with many users trying it out).
For the purposes of support, you may send me email about it, I don't mind

* It seems UFW is able to do it!
This section is really better suited for someone managing servers than for desktop users:
UFW comes with an Application Filter. It's configuration is a simple text file at /etc/ufw/applications.d.
To get a list of all the application filters, type
sudo ufw app list

Which should look like this:
Available applications:
  Apache
  Apache Full
  Apache Secure
  CUPS

To get more details on any one application, type - for example:
sudo ufw app info 'Apache Full'

More details are available in the relevant Ubuntu help wiki page

As for the question of default configuration:
By default, Ubuntu ships with no open ports on public interfaces
Source

A: Question 1.- here
Question 2.- as i far i know there isn't any tool for notification when someone wants access to your pc or when an application wants to go out on the internet? maybe that will be a feature for GUFW


text:
Q: Cannot find id of control inside gridview which inside another gridview Can anyone help me on this?
I have a button(ImageButton1) inside a GridView (gvSdt), and gridview b is inside another Gridview (gvClass).
but it come out an error said "The name 'gvSdt' does not exist in the current context"
The code i used as below:
protected void gvSdt_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = gvSdt.SelectedRow;
    int rowIndex = gvSdt.SelectedIndex;
    string strValue = gvSdt.DataKeys[rowIndex].Value.ToString();
}

A: Since gvSdt is contained within another GridView, you won't be able to access it directly, as it is repeated content. Since gvSdt can exist multiple times, gvSdt would therefore refer to multiple GridViews.
This is made easy however, since you are using the SelectedIndexChanged event of the GridView in question. Notice the sender argument of the method. The object that gets passed there is actually the GridView. So just cast it as such.
protected void gvSdt_SelectedIndexChanged(object sender, EventArgs e)
{
    GridView gvSdt = (GridView)sender;
    GridViewRow row = gvSdt.SelectedRow;
    int rowIndex = gvSdt.SelectedIndex;
    string strValue = gvSdt.DataKeys[rowIndex].Value.ToString();
}


text:
Q: Spit array in Angular or js I have some objects in an array that I need to split. Eg
[{"age":"3"},{"age":"5"},{"age":"4"},{"age":"5"}]

I need it to take however many inside the object and so it shows.
[3,5,4,5]

A: Splitting is not the correct action, I'd say you want to "map" the array, thus I'd suggest you use Array.prototype.map:
var array = [{"age":"3"},{"age":"5"},{"age":"4"},{"age":"5"}];
var ages = array.map(function (item) {
    return item.age;
});

A: try this

var arr =[{"age":"3"},{"age":"5"},{"age":"4"},{"age":"5"}];
var arr2 = [];

for (i = 0; i < arr.length; i++) {
  arr2.push(arr[i].age);
}
console.log(arr2);

A: Iterate the array using map and return the object property.
let parsed = array.map(e => e.age);


text:
Q: Concrete Mathematics chapter 2 infinite calculus (geometric series) Did the authors use finite calculus to evaluate this sum?
If so then how?
$$
  \sum_{k\ge0} x^k
= \lim_{n\rightarrow\infty} \frac{1-x^{n+1}}{1-x}
= \begin{cases}
   \frac{1}{1-x} & \text{if $0 \leq x < 1$}, \\
   \infty  & \text{if $x \geq 1$}.
  \end{cases}
$$
The book is Concrete Mathematics by Knuth.
Thank you.

A: If you divide $1-x^{n+1}$ by $1-x$ you will get     $\sum_{k=0}^n x^k$
Now if $|x|<1$, then as $n\to \infty $, $x^{n+1}\to 0$
If $x\ge 1$ then the series diverges to $\infty$
Thus the result:
$$\sum_{k\ge0} x^k
= \lim_{n\rightarrow\infty} \frac{1-x^{n+1}}{1-x}
= \begin{cases}
   \frac{1}{1-x} & \text{if $0 \leq x < 1$}, \\
   \infty  & \text{if $x \geq 1$}.
  \end{cases}$$


text:
Q: What is the default value of lastIndexOf? string.lastIndexOf(searchValue[, fromIndex])
MDN says that fromIndex default value is equal to the string.length, however, I really think it is string.length-1
But it doesn't matter what I think... I need someone to confirm what is the default value of fromIndex
Here is what they say:

"It can be any integer between 0 and the length of the string. The default value is the length of the string."

A: According to ECMAScript 5, it will be the length of the String.

15.5.4.8 String.prototype.lastIndexOf (searchString, position)
If position is undefined, the length of the String value is assumed, so as to search all of the String.
...

*

*Call CheckObjectCoercible passing the this value as its argument.

*Let S be the result of calling ToString, giving it the this value as its argument.

*Let searchStr be ToString(searchString).

*Let numPos be ToNumber(position). (If position is undefined, this step produces the value NaN).

*If numPos is NaN, let pos be +∞; otherwise, let pos be ToInteger(numPos).

*Let len be the number of characters in S.

*Let start min(max(pos, 0), len).

*Let searchLen be the number of characters in searchStr.

*Return the largest possible nonnegative integer k not larger than start such that k+ searchLen is not greater than len, and for all nonnegative integers j less than searchLen, the character at position k+j of S is the same as the character at position j of searchStr; but if there is no such integer k, then return the value -1.

A: It doesn't matter, at all.  Since the index is zero-based, both string.length and string.length-1 will include the entire string.
EDIT
You can test for differences in the result pretty simply:
var s = '01923456789abcdef';
alert(s.lastIndexOf('f',s.length+1));
alert(s.lastIndexOf('f',s.length));
alert(s.lastIndexOf('f',s.length-1));
alert(s.lastIndexOf('f',s.length-2));

That alerts 16, 16, 16, -1.   Thus, if you are very concerned with an extra few cycles being used when a useragent runs .lastIndexOf(), you can pass .length-1 and have it spend a few extra cycles parsing the extra parameter.

A: If fromIndex is as large or larger than the string length, the function returns -1.
If not, the string.substring(fromIndex) searches from the end of the substring.


text:
Q: jQuery + php file upload. Pass multiple parameters How to pass extra variables through $.ajax to post.php?
My first variable is
var form_data = new FormData($(this)[0])

I can pass it alone, but if I want to add another variable and make an array
data {
    "form_data": form_data,
    "name": "hello"
}

it does't work.
My current code:
$(document).ready(function() {
    $("form#data").submit(function(){

        var form_data = new FormData($(this)[0]);

        $.ajax({
            url: 'post.php',
            type: 'POST',
            data: form_data,
            success: function (data) {

                $('#result').html(data);

            },
            contentType: false,
            processData: false
        });

        return false;
    });
});

<form id="data" method="post" enctype="multipart/form-data">
    <input name="file" type="file" />
    <button>Submit</button>
</form>

A: Try this. The formData object has a method append. We're going to use that instead. We're going to append the file under the name file. In PHP access it with $_FILES['file']. Now for the array or object that you want to add to it. Use JSON.stringify on it to turn it into a string. We append the JSON string and add it to the name 'object'. To access the JSON in PHP json_decode($_POST['object']) will turn it into an object.
Fiddle
$(function(){
    $("form#data").submit(function (e) {
        e.preventDefault();
        var form_data = new FormData(),
            o = {};
        o.name = 'Adam';
        o.arr = ['test', 213];
        form_data.append('file', $('input[name="file"]', this)[0].files[0]);
        form_data.append('object', JSON.stringify(o));
        $.ajax({
            url: '/info/',
            type: 'POST',
            data: form_data,
            success: function (data) {

                $('#result').html(data);

            },
            contentType: false,
            processData: false
        });

        return false;
    });
});

A: I would JSON.stringify it then json_decode when you get it back in PHP
var data = JSON.stringify({ /* object */ });
Then in your php
$data = json_decode(....);

A: Try to define  a new bariable
var name = "hello";

and then insert it into $.ajax data
    $.ajax({
        url: 'post.php',
        type: 'POST',
        data: "form_data="+form_data+"&name="+name,
        success: function (data) {

            $('#result').html(data);

        },
        contentType: false,
        processData: false
    });

I never test this script, but there's no matter to check it out :D


text:
Q: How to create a table with varying columns and rows My apologies if this has been asked multiple times in the past. But I'm quite new to LateX and have been trying to write a lab report with it. All had been going well until I was trying to create this kind of table.
On another note, is there any possible way to move the table as I please? (the table keeps floating to where ever seems fit but not where I want it).

A: You can use siunitx and, possibly, booktabs.
\documentclass{article}
\usepackage{siunitx,booktabs} % beautiful tables

\DeclareSIUnit{\rpm}{rpm}

\begin{document}

\begin{table}[htp]
\centering

\begin{tabular}{
  S[table-format=1.3]
  S[table-format=1.2]
  S[table-format=3.0]
  S[table-format=1.2]
  S[table-format=1.3]
  S[table-format=3.0]
}
\toprule
\multicolumn{3}{c}{$I_L=\SI{0.8}{\ampere}$} &
\multicolumn{3}{c}{$I_L=\SI{1.5}{\ampere}$} \\
\multicolumn{3}{c}{$T=\SI{3.46}{\newton\metre}$, $\omega=\SI{1500}{\rpm}$} &
\multicolumn{3}{c}{$T=\SI{4.35}{\newton\metre}$, $\omega=\SI{1500}{\rpm}$} \\
\cmidrule(lr){1-3} \cmidrule(lr){4-6}
{$I_A$ (\si{\ampere})} &
{$I_f$ (\si{\ampere})} &
{$P_{\mathrm{in}}$ (\si{\watt})} &
{$I_A$ (\si{\ampere})} &
{$I_f$ (\si{\ampere})} &
{$P_{\mathrm{in}}$ (\si{\watt})} \\
\midrule
1.84  & 0.3  & 378 & 2.2  & 0.38 & 532 \\
1.54  & 0.4  & 380 & 1.9  & 0.45 & 527 \\
1.25  & 0.5  & 375 & 1.65 & 0.55 & 527 \\
1.14  & 0.6  & 384 & 1.57 & 0.65 & 530 \\
1.145 & 0.65 & 384 & 1.63 & 0.75 & 530 \\
\bottomrule
\end{tabular}

\caption{Load $V$-curves test}

\end{table}

\end{document}

Note how the units are specified, in a uniform style which is consistent with BIPM rules for the International System.

There's generally no need to print headers boldface, they're already prominent enough.
Avoid worksheet-like rules: they're good for presenting data on a computer screen, when one has to work with them. For handouts and print, they're just of a hindrance.


text:
Q: Magento getReadConnection() Error in /app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php on line 134 There is an error suddenly started popping up. The error occurs on various part of website like cart area, product detail page etc..
I am running my site on local server.
the error is as follows:

Fatal error: Call to a member function getReadConnection() on boolean in app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php on line 134

I have googled the issue but that didn't helped either.

A: You have to define the class and the resource model. Please check this link. I hope solve your problem.


text:
Q: How to post data using multipart? I develop one app. In my app i take one image from camera or one from gallery. I want to post image to server using Multipart but image not post it. My post data is below
{
     "suggested_item" :{
         "name": "apple",
         "description" : "nice apple",
         "image": "image.png"
     }
  }

My java code is
public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == PICK_FROM_CAMERA) {
    try{
        if(resultCode == -1){
            File file = new File(Environment.getExternalStorageDirectory()+File.separator +"image.png");
            bitmap = loadBitmap(file);
            iv_pic.setImageBitmap(bitmap);

        try {
            Uri tempUri = getImageUri(getActivity(), bitmap);
            Log.i(TAG,"onActivityResult PICK_FROM_CAMERA, tempUri : "+tempUri);

        //uploadFile(tempUri + "" + System.currentTimeMillis()+".png");
        } catch (Exception e) {
        e.printStackTrace();
        }
        }else{
        //setResult(RESULT_CANCELED);
        //Activity.this.finish();
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}else if (requestCode == PICK_FROM_GALLERY) {
        try{
           //Log.i(TAG,"onActivityResult PICK_FROM_GALLERY, data : "+data);
            if(data !=null){
                bitmap = null;
                try {
                    bitmap = new BitmapDrawable(MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData())).getBitmap();
                    iv_pic.setImageBitmap(bitmap);

                    try {
                        Uri tempUri = getImageUri(getActivity(), bitmap);
                        Log.i(TAG,"onActivityResult PICK_FROM_GALLERY, tempUri : "+tempUri);

                        //uploadFile(tempUri + "" + System.currentTimeMillis()+".png");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                //setResult(RESULT_CANCELED);
                //Activity.this.finish();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

public Uri getImageUri(Context context , Bitmap bitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG , 100 , bytes);
    String path = Images.Media.insertImage(context.getContentResolver() , bitmap , "Title" , null);
    return Uri.parse(path);
}

please help me thanks in advance.

A: To send binary data you need to use addBinaryBody method of MultipartEntityBuilder. Sample of attaching:
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
//Image attaching
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
File file;
multipartEntity.addBinaryBody("someName", file, ContentType.create("image/jpeg"), file.getName());
//Json string attaching
String json;
multipartEntity.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN));

Then make request as usual:
HttpPut put = new HttpPut("url");
put.setEntity(multipartEntity.build());
HttpResponse response = client.execute(put);
int statusCode = response.getStatusLine().getStatusCode();

A: I suggest using retrofit.
Posting multipart will be something like this:
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

Refer to this question for more details.
This is a good tutorial to check if you are not familiar to retrofit.

A: Here I am Posting Full Code for Upload Image Using HTTP on Server also PHP code for understanding,
Class File
package com.stackexmples;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by windws on 26-Mar-16.
 */
public class UploadImage extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_TAKE_GALLERY_VIDEO = 11;
    private static final String TAG = "UploadMultipleFile";
    private AppCompatButton btnUploadFiles;
    private AppCompatButton bntSelectImage;
    private String filemanagerstring;
    private String selectedImagePath="";
    private TextView tvVideoList;
    private TextView tvImageList;
    private int selected = 0;
    private LinearLayout ll;
    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_multiple_file);
        initView();
        initListener();

    }

    private void initView() {
        btnUploadFiles = (AppCompatButton) findViewById(R.id.btnUploadFiles);
        bntSelectImage = (AppCompatButton) findViewById(R.id.bntSelectImage);
    }

    private void initListener() {
        btnUploadFiles.setOnClickListener(this);
        bntSelectImage.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == btnUploadFiles) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile("Data you want to sent");
                }
            });
            thread.start();
        } else if (v == bntSelectImage) {
            selectImage();
        }
    }

    private void selectImage() {
        selected = 1;
        Intent intent = new Intent();
        intent.setType("Image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_TAKE_GALLERY_VIDEO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {

            if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
                Log.d(TAG, "Called-->onActivityResultCalled");
                Uri selectedImageUri = data.getData();
                Log.d(TAG, "selectedImageUri-->" + selectedImageUri);
                selectedImagePath = selectedImageUri.toString().replace("file://", "");
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public String uploadFile(String req) {
        // TODO Auto-generated method stub
        String serverResponseMessage = "";
        String response_return = "";
        Log.d("first str is:", req);
        String urlString = "http://192.168.1.32/TestUpload/upload.php";
        URL imageUrl = null;
        try {
            imageUrl = new URL(urlString); // get WebService_URL
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        // generating byte[] boundary here

        HttpURLConnection conn = null;
        DataOutputStream outputStream = null;

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 10 * 1024 * 1024;

        try {
            int serverResponseCode;
            conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            outputStream = new DataOutputStream(conn.getOutputStream());

            //////////////////////////////////////////////////////
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"json\"" + lineEnd);
            outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
            outputStream.writeBytes("Content-Length: " + req.length() + lineEnd);
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(req + lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            try {
                FileInputStream fileInputStream = new FileInputStream(selectedImagePath);
                String lastOne = "temp";
                /////////////////////////////////////////////
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: attachment;  name=\"imageKey" + "\";" + " filename=" + lastOne +".jpg" + lineEnd); // pass key & value of photo
                    /*outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);*/
                outputStream.writeBytes(lineEnd);
                bytesAvailable = fileInputStream.available(); // photo size bytes
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                while (bytesRead > 0) {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }
                outputStream.writeBytes(lineEnd);
                Log.d("posttemplate", "connection outputstream size is " + outputStream.size());
                fileInputStream.close();
            } catch (OutOfMemoryError o) {
            }
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            serverResponseCode = conn.getResponseCode();
            serverResponseMessage = conn.getResponseMessage();
            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response1 = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response1.append(line);
                response1.append('\r');
            }
            rd.close();
            response_return = response1.toString();

            Log.d("posttemplate", "server response code " + serverResponseCode);
            Log.d("posttemplate", "server response message "
                    + serverResponseMessage);
            outputStream.flush();
            outputStream.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            Log.d("posttemplate", "malformed url", e);
        } catch (IOException e) {
            Log.d("posttemplate", "ioexception", e);
        }
        Log.d("response--->", "****" + response_return);
        return response_return;
    }
}

Layout File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.materialexample.UploadMultipleFile.UploadMultipleFile">
    <android.support.v7.widget.AppCompatButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnUploadFiles"
        android:text="Upload Files" />
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:orientation="vertical"
        android:layout_below="@id/btnUploadFiles"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/bntSelectImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Select Image" />

    </LinearLayout>

</RelativeLayout>

PHP Code For Understanding
<?php
$file_path = "uploads/";

    $file_path = $file_path . basename( $_FILES['imageKey']['name']);
    if(move_uploaded_file($_FILES['imageKey']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
if(isset($_REQUEST['json'])){
    echo "text is-->".$_REQUEST['json'];
}

?>


text:
Q: printing array in a for loop in matlab i have the following code:
 I=0;
 L=0;
for i=1:20

   m=[I;L];
   hold on
   plot(1:20,m(1:2),'*');

   I=I+1;
   L=5+I;
end

The purpose of this code is in the beggining of each one of the 20 iterations, the table m, to change the values. after this part i want to print the I,L with different plot in the same figure.After that there is code which change again the values of I,L,M. The result i want to be a plot for each one of the I,L.But i don't know how to do this. Any ideas?

A: Do you mean something like that?
 I_value=0;
 L_value=0;
 I = [];
 L = [];
 for i=1:20
     I_value = I_value + 1;
     L=[5,I];
     I=[I,I_value+1];
 end

 figure;
 plot([I;L]','*');


text:
Q: Echo multiple strings from a function in PHP I have tried to create a function that will take two arguments and in theory, echo out the result.  After doing some Googling, I got the impression that this should be accomplished using an array, however I'm not too sure on the logic.
I was hoping I could call the function like so - kb_article("How to do something", "Q12345"), to get the formatting of:

Related KB Article(s): How to do something - Q12345

    function kb_article($title, $code)
{
    echo "
Related KB Article(s):

";
    echo $title + " - " + $code;
}

How can this be achieved?

A: String concatenation is performed using . ( instead of + ). Here's the corrected version of your function:
function kb_article($title, $code)
{
    echo '
Related KB Article(s):

';
    echo $title . " - " . $code;
}

A: You can just enclose the whole string in double quotes...
function kb_article($title, $code)
{
    echo "
Related KB Article(s):

";
    echo "$title  -  $code";
}

kb_article("title","code");

// outputs the expected title - code

Or as previously posted, do string concatenation properly.
function kb_article($title, $code)
{
    echo "
Related KB Article(s):

";
    echo  $title . " - " . $code;
}

kb_article("title","code");

A: You need to use . instead of + to concatenate in php. Like so:
echo $title." - ".$code;


text:
Q: Is it possible to return to Emerald Isle? Is it possible to return to Emeral Isle after leaving it? I already completed the tournament there.
Two of my party members don't know how to use bows so I wanted to teach it to them and it seems that you can only learn it on Emerald Isle...

A: According to some threads (this and this), it is impossible to return to the Emerald island. The accepted answer by unor is theoretically correct, but practically, it has one caveat:

*

*The dragon which the party encounters in Emerald island's Dragon cave is Morcarack, a unique version of "common" Red Dragon, but without resistances.

*The treasure Morcarack drops is 400d10 gold + Level 6 item.

*However, Scroll of Lloyd's Beacon can only appear as a Level 4 & 5 treasure, according to MM7 random item generation tables.

*This means that Scroll of Lloyd's Beacon cannot be dropped by Morcarack.

*And since there is no other monster powerful enough to drop Level 4 or 5 items, Scroll of Lloyd's Beacon cannot be obtained on Emerald isle.

Thus practically, returning to Emerald isle is impossible.
The only possible way to get back to Emerald island seems to be by using the Maestro MOD.

A: I guess there is only one (hard) way to come back to Emerald Isle:

*

*Kill the dragon on Emerald Isle.

*Hope to loot a Lloyd's Beacon scroll.
(I guess that this is the English name; it's Leuchtfeuer in German)

*Cast it somewhere on Emerald Isle.

*Leave the island. Now you can cast Lloyd's Beacon to get back to Emerald Isle (but note that it doesn't last very long if unskilled).

However, you can learn Bow also in Tularean Forest and in Avlee.


text:
Q: On login, I am only given the Guest user option. How do I log into my account? I tried to add a guest account to my laptop and when I restarted the computer, the only login option I have is the Guest Account.  Choosing this account restarts the computer into the Safari-only configuration.  There is no Systems Preferences available in this mode.
I did not unchoose my administrator account.  How did this happen?  And how do I get it back?

A: I think safe mode would work better. Here are the instructions, from the Apple Support website

To start up into Safe Mode (to Safe Boot), do this:

*

*Be sure your Mac is shut down.

*Press the power button.

*Immediately after you hear the startup tone, hold the Shift key. The Shift key should be held as soon as possible after the startup
  tone, but not before the tone.

*Release the Shift key when you see the gray Apple icon and the
  progress indicator (looks like a spinning gear).

Once your in, go to System Preferences and disable Find My Mac (iCloud settings) and Guest User (Users and Groups). Reboot. You should be able to login normally. If you would still like a guest user, just go back and enable Find My Mac.

A: Try restarting the computer by clicking at the Apple logo () in the upper left screen corner and choosing Restart.


text:
Q: Nodejs mssql and PreparedStatement, excute not getting called I have included the mssql module into our node configuration.  The version of node is: 0.12.0, mssql is version 2.1.1 by Patrik Simek.
I can connect to our database I have prepared a statement but execute never gets called.  Before the code is executed, I know that a connection is estabilished to the database.
//The client object contains the user name eg. "First Last"
var aryNames = objClient['usr'].split(" ");

if ( !(aryNames && aryNames.length) ) {
    return;
}
var strSQL = "SELECT" +
             " MIN(EventID)" +
             ",MAX(EventID)" +
             ",MIN(EventTime)" +
             ",MAX(EventTime)" +
             ",FirstName" +
             ",Surname" +
             " FROM" +
             " [Net2].[sdk].[EventsEx]" +
             " WHERE" +
             " CAST(EventTime AS Date) BETWEEN @bow AND @eow" +
             " AND FirstName=@firstname" +
             " AND Surname=@surname" +
             " GROUP BY" +
             " CONVERT(VARCHAR(10), EventTime, 102)" +
             ",FirstName" +
             ",Surname",
  objParams = {bow       : objClient['tk_bow']
              ,eow       : objClient['tk_eow']
              ,firstname : aryNames[0]
              ,surname   : aryNames[aryNames.length-1]},
  ps = new mssql.PreparedStatement();
ps.input("bow",       mssql.DateTime2);
ps.input("eow",       mssql.DateTime2);
ps.input("firstname", mssql.VarChar);
ps.input("surname",   mssql.VarChar);
ps.prepare(strSQL, function(err) {
  console.log("prepare");
  if ( err ) {
    console.log(err);
    return;
  }
  ps.execute(objParams, function(err, recordset)     {
    console.log("execute");
    console.log(err);
    console.dir(recordset);
    ps.unprepare(function(err) {
    });
  });
});

When this code is executed, the debug statement prepare is displayed, but I never see the execute statement.
I've looked at numerous examples and I cannot see what I am doing wrong.

A: I modified my connection routine, this fixed it.


text:
Q: PHP Mysql database fields I'm in development of a movie statistics website and i'm trying to figure out what the best way to go is for the database.
The website is about movies. But each movie will have different fields. I need help to figure out the best way to store this data.
For example. I have one table called "movies". This will have all the general information. But for some movies, I want them to have their own fields with other information.
I could create a table for each movie, but after the amount of movies build up, its going to make the database look very messy and unorganised, which I don't want. I could then build placeholder fields for the "movies" table, but I may need one or two, or I may need 10 or 20 extra fields.
Would anyone be able to recommend what way I should approach this?
Thank you

A: One simple way to handle your situation is to create a movie attributes table, where every record in that table represents a single attribue for a certain movie.  A table definition like the following might make sense:
CREATE TABLE movie_attribute (
    movie_attr_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    movie_id NOT NULL
    attr_name VARCHAR(255) NOT NULL,
    attr_value VARCHAR(255) NOT NULL,
    FOREIGN KEY fk_movie(movie_id) REFERENCES movies(id)
)

Using this design, any number of attributes can be added for a given movie without requiring a big design change.  Database tables were designed to comfortably grow row-wise, not column-wise.


text:
Q: Request Times Out while uploading large size files to the server using ASIFormDataRequest I have developed an ios app and for making server requests I am using ASIHTTPRequest. The issue which I am facing is the server Request times out when I try to upload large size files. I have tried both the SetData and SetFile methods for it but the issue is the same on both of them. I an unable to resolve it. It has eaten my four days. My code is given below. Thanks in advance.
- (void)syncTaskOnTheServer:(Tasks *)task ofTheUser:(NSString *)userId{

    __block unsigned long long uploaded = 0;
    ASIFormDataRequest *syncTask = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@tasks",baseurl]]];
    syncTask.shouldAttemptPersistentConnection = NO;
    [syncTask addPostValue:userId forKey:@"UserId"];
    [syncTask addPostValue:appId forKey:@"AppId"];
    [syncTask addPostValue:[NSString stringWithFormat:@"%@",task.taskTitle]    forKey:@"Title"];
    [syncTask addPostValue:[NSString stringWithFormat:@"%@",task.notes]        forKey:@"Description"];
    [syncTask addPostValue:[NSString stringWithFormat:@"%@",task.priority]     forKey:@"Priority"];
    [syncTask addPostValue:[NSString stringWithFormat:@"%@",task.taskCategory] forKey:@"TaskCategory"];
    [syncTask addPostValue:[NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",task.creationDate]] forKey:@"CreationDate"];
    syncTask.shouldUseRFC2616RedirectBehaviour = YES;

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    if (![task.imagePath isEqualToString:@"No Image Attached"]) {
        NSString *imageFilePath =  [NSString stringWithFormat:@"%@/%@_image.jpg",path,task.taskurlSubPart];
        UIImage *image          =  [UIImage imageWithContentsOfFile:imageFilePath];
        NSData *imageData       =  UIImageJPEGRepresentation(image, 1.0);
        NSLog(@"\n%@\n",task.taskurlSubPart);
        [syncTask setData:imageData withFileName:[NSString stringWithFormat:@"%@.jpg",task.taskurlSubPart ] andContentType:@"image/jpeg" forKey:@"Image"];
        /*
         [syncTask setFile:imageFilePath withFileName:[NSString stringWithFormat:@"%@.jpg",task.taskurlSubPart] andContentType:@"image/jpeg"  forKey:@"Image"];
         */
    }

    if (![task.audioURL isEqualToString:@"No Audio File"]) {
        NSMutableString *audioFileName = [NSMutableString stringWithString:task.audioFileName];
        [audioFileName appendString:@".caf"];
        NSString *audioFilePath = [NSString stringWithFormat:@"%@/%@.caf",path,task.audioFileName];
        NSData *audioData     = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:audioFilePath]];
        [syncTask setData:audioData withFileName:audioFileName andContentType:@"audio/x-caf" forKey:@"Audio"];
    }

    [syncTask setRequestMethod:@"POST"];

    [syncTask setStartedBlock:^{
        NSLog(@"start block");
    }];
    [syncTask setFailedBlock:^{
        NSLog(@"\n%@\n",[syncTask error]);
        NSString *serverResponse = [syncTask responseString];
        WLParseServerResponse *parseResponse = [[WLParseServerResponse alloc] init];
        [parseResponse parseSyncTaskResponse:serverResponse forTask:task];
        [parseResponse release];

    }];
    [syncTask setCompletionBlock:^{
        NSString *serverResponse = [syncTask responseString];
        NSLog(@"\nserver response: %@\n",serverResponse);
        WLParseServerResponse *parseResponse = [[WLParseServerResponse alloc] init];
        [parseResponse parseSyncTaskResponse:serverResponse forTask:task];
        [parseResponse release];
    }];
    [syncTask setHeadersReceivedBlock:^(NSDictionary *responseHeaders) {
        NSLog(@"%@", responseHeaders);
    }];
    [syncTask setBytesSentBlock:^(unsigned long long size, unsigned long long total) {
        uploaded += size;
        NSLog(@"%llu, %llu", uploaded, total);

    }];
    [syncTask startAsynchronous];
}

A: Add this,
[syncTask setTimeOutSeconds:45];  // 45 seconds, it may differ according to the file size
set your maximum seconds that you needed.

A: The problem may occur under different circumstances, You might find it useful by trying the  following steps
Step 1 - If your using PHP backend service (Check your PHP INI file)

Of upload_max_filesize and post_max_size in your php.ini :
; Maximum allowed size for uploaded files.
upload_max_filesize = 50M

; Must be greater than or equal to upload_max_filesize
post_max_size = 50M

Step 2 - Test the same upload file via rest client

Mozilla Add-ons RestClient
Chrome Advanced REST client


text:
Q: CSS (selector) not working on a WAMP server (W10) I was a lot of time busy, with learning HTML, and i decided to make wamp server. Everything whent OK and i started to code the HTML. But when i started to code te CSS the selector will not show in the webpage on my local domain(rolfweb.net:8080). But in localhost it shows all CSS correctly!
Code:
<DOCTYPE html>

    <title> RolfWeb </title>

<link type="text/css" rel="stylesheet" href="/css/indexss.css"/>

 Home

 Video's

 Games

 Contact en informatie

 Over mij

 Test

And the CSS:
p {
    color: blue;
}
/* This is not working! */
nav ul {
    list-style-type: none;
    background-color: #3f875f;
    border: 3px solid #3a756c;
    text-align: center;
}

So it shows good on localhost but on rolfweb.net:8080 not.
PS: Sorry for my bad english i'm dutch :P

A: Move your css link within the head tags:-
<DOCTYPE html>

<title> RolfWeb </title>
<link type="text/css" rel="stylesheet" href="/css/indexss.css"/>

 Home

 Video's

 Games

 Contact en informatie

 Over mij

 Test


text:
Q: Outlook Addin can't send request to the AppDomain I have an Outlook Web Addin. We deployed it on several hundreds of accounts for a customer with Microsoft 365 E3 licenses.
For most accounts the addin loads, and a call is sent to our backend server.
The domain of the backend and of the storage (two different domains) are declared in AppDomain in the manifest.
For a few others, the addin appears in the ribbon, but the web HTTPS call never arrives. We made a simple Hello World Addin with just one web call to be sure it does not come from our code - with the same results. But in both cases : our addin do work on Outlook on the web, from the same computer and account. We opened our backend domain with IE 11 and it works.
What else can block a web addin in Outlook to communicate with an external domain ? As it is supposed to use the IE11 engine, how an addin can work on IE11 and not on Desktop. What parameters (GPO ? Trusted sites / domains ?) should I investigate ?
Update

*

*We moved the addin to the same domain of the backend, to check if it could be linked to Cross Domains requests. Same result : call never ends.

*We checked the customer proxy : all used domains are accessible.
** Update **
Screenshot of message :


text:
Q: 'System.Configuration.ConfigurationErrorsException: The requested database WebBank is not defined in configuration Can please some tell me when does the above written error occurs. I just wanted to get more information on this.

A: Check the config file where you mentioned the connection string and correct it...
The database mentioned might not be a valid one, or the server name might not be valid.
Your connection string should look like this
Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;

A: *

*Place your connection string to the host library or the start up project.

*It is clear that you are trying to access the config entry and it is not found thus this error thrown by the Configuration Manager/accessor.

*Give us some code to diagnose the issue its hard to guess what causing the error.


text:
Q: Computing the cohomology groups of the Klein bottle as a $\Delta$-complex I am currently working on how to compute the cohomology and ring structure of certain surfaces who are given as $\Delta$-complexes such as the Kein bottle pictured below.

For this i encountered this particular answer:
https://math.stackexchange.com/a/877083/543570
Unfortunately, i do not understand why it holds that
$\operatorname{Im}\delta:C^1 \rightarrow C^2=\langle \mu+\lambda, \mu- \lambda\rangle=\langle2\mu, \mu+\lambda\rangle=\langle\mu +\lambda\rangle$
and
$\ker \delta:C^1 \rightarrow C^2=\langle\beta+\gamma,\alpha +\beta\rangle$
where $\alpha,\beta,\gamma$ are the dual basis elements of $a,b,c$ respectively and $\mu,\lambda$ the dual basis elements for $U,L$ respectively.
Could someone help me understand why $\operatorname{Im}\delta = \langle\mu +\lambda\rangle$ and $\ker \delta = \langle\beta+\gamma,\alpha +\beta\rangle$ ?
Unfortunately i can't provide any own attempts since i got stuck at these two computations and do not know how to continue.
Thanks for any help!

A: In the linked question, with $\alpha$ dual to $a$, etc., and $\mu, \lambda$ dual to $U, L$, the author says [I've added sequence numbers]

*

*To compute cohomology we need the homology groups of the chain complex: $0 \rightarrow C^0 \rightarrow C^1\rightarrow C^2 \rightarrow 0\rightarrow ...$, so we compute the coboundary map.

*$\delta(\phi)(a)=\phi(\partial(a))=\phi(v)-\phi(v)=0=\delta(\phi)(b)=\delta(\phi)(c)$, so $\delta:C^0 \rightarrow C^1$ is the zero map.

*$\delta(\alpha)(U)=\alpha(\partial(U))=\alpha(a)+\alpha(b)-\alpha(c)=1+0-0=1$.

*Similarly, $\delta(\beta)(U)=1$ and $\delta(\gamma)(U)=-1$. And $\delta(\alpha)(L)=1$, $\delta(\beta)(L)=-1$, $\delta(\gamma)(L)=1$.

*So $\delta:C^1 \rightarrow C^2$ takes $\alpha \rightarrow \mu +\lambda$, $\beta \rightarrow \mu -\lambda$, and $\gamma \rightarrow -\mu +\lambda$. Thus:

*Im $\delta:C^1 \rightarrow C^2=<\mu+\lambda, \mu- \lambda>=<2\mu, \mu+\lambda>=<\mu +\lambda>$ since we are over $\mathbb{Z}_2$.

Now let's recall that $a,b,c$ generate $C_1$, and $\alpha, \beta, \gamma$ generate $C^1$, etc. Item 4 says that $\delta(\alpha)$ can be determined, as an element of $C^2$, by what it does to generators (i.e.  $U$ and $L$) for $C_2$. From item 3, we have that $\delta(\alpha)(U) = 1$; item 4 says $\delta(\alpha(L)) = 1$. Now the question is "what linear combination of the basis elements $\lambda$ and $\mu$ also has these properties, for every element of $C^2$ is a combination of the basis elements. The answer is that $\lambda + \mu$ does. Hence
$$
\delta(\alpha) = \lambda + \mu.
$$
You can use the same process to figure out what delta does to the other two generators for $C^1$. When you're done, you've got three elements of $C^2$ which span the image of $\delta$. That's what items 5 says.
Item 6 then computes a reduced form of this span, using the fact that you're working over the integers mod 2 to get rid of some stuff.
So...exactly which of the items in the proof is confusing you?
Post-comment addition
$$\newcommand{\two}{{\Bbb Z/2\Bbb Z}}
$$
$C^1$ is a 3-dimensional vector space over $\two$, with basis $\alpha, \beta, \gamma$; $C^2$ is a 2-dimensional vectorspace over $\two$, with basis $\mu, \lambda$. The function $\delta$ is a linear transformation from the first to the second, and hence can be represented (in these two bases) by matrix multiplication with a $2 \times 3$ matrix, which is
$$
A = \pmatrix{
1 & 1& -1 \\
1 & -1& 1
}
$$
(where do each column's entries come from? Make sure you know!)
but since we're talking about mod-2 stuff, that might as well be
$$
A = \pmatrix{
1 & 1& 1 \\
1 & 1& 1
}
$$
The kernel of $T(v) = Av$ is the same as that of $T(v) = A'v$, where $A'$ is the row-reduced version of $A$, which is
$$
A' = \pmatrix{
1 & 1& 1 \\
0 & 0& 0
}
$$
which you get by subtracting the first row from the second. The first column (corresponding to $\alpha$) contains a leading "1" for some row, but the others do not; they can therefore be treated as free variables. So looking at $x\alpha + y\beta + z\gamma$, $y$ and $z$ are free variables. By assigning $y = 1, z = 0$, we find $x = 1$, i.e., that $\alpha + \beta$
is one generator for the kernel. By assigning $y = 0, z = 1$, we again find $x = 1$, so that $\alpha + \gamma$ is another generator for the kernel. So the kernel is spanned by these two elements. (Of course, there are many other pairs of elements that span it too).

A: Following the answer that you link, recall that the dual $\mu\in C^2(K,\mathbb{Z}_2)$ of $U$ is the linear map defined to be $1$ at $U$ and $0$ at $L$ (since $C_2(K,\mathbb{Z}_2)$ is spanned by $U$ and $L$). Similarly, $\lambda$ is the dual of $L$, so it is $1$ at $L$ and $0$ at $U$.
Image
In the answer, $\delta(\alpha)$, $\delta(\beta)$ and $\delta(\gamma)$ are computed, i.e. the image of the generators of $C^1$ are computed. In particular $\delta(\alpha)(U)=1=\delta(\alpha)(L)$. Since $\delta(\alpha)$ is a linear combination of $\lambda$ and $\mu$, and its values at $U$ and $L$ are both $1$, it follows that $\delta(\alpha)=\mu+\lambda$.
Kernel
An element of $C^1$ that belongs to the kernel of $\delta$ is a combination of $\alpha$, $\beta$ and $\gamma$ that is sent to $0$ by $\delta$. Since we have the images $\delta(\alpha)$, $\delta(\beta)$ and $\delta(\gamma)$, and since we are over $\mathbb{Z}_2$ we can simply check which combinations yield $0$. For instance, $\delta(\alpha)(U)=\delta(\beta)(U)$ and $\delta(\alpha)(L)=\delta(\beta)(L)$ (equalities in $\mathbb{Z}_2$), so $\delta(\alpha+\beta)=0$ because $\delta(\alpha+\beta)(V)=0$ for all $V\in C_2$, since $C_2$ is spanned by $U$ and $L$, both on which $\delta(\alpha+\beta)$ vanishes.
Can you follow from here?


text:
Q: Planes of a dodecahedron divide the space $\mathbb R^3$ In how many disjunct parts divide the planes of a regular dodecaheadron the space $\mathbb R^3$?
I encountered this task at university where we discussed it a lot, but nobody found a solution.
Does anybody know the solution? May it work with graph theory?

A: Here's a graphical count, based on intersecting the configuration with spheres of different sizes -- though in order to make things visible actually I'm normalizing the size of the spheres, such that the images here actually shows a sphere intersected by the planes of a dodecahedron of increasing size.
The 12 planes of the dodecahedron come in 6 parallel pairs, and in the figures, the regions of each sphere are color-coded according to (and labeled with) the number of pairs where the region is between the two parallel planes.

The first image shows a sphere far from the dodecahedron. Each of the 6 pairs of planes become a narrow band around the sphere, and the bands create the graph of an icosidodecahedron. Each face, edge, and vertex of the icosidodecahedron corresponds to an unbounded region of space -- there are $12$ of type 0, $20$ of type 0', $60$ of type 1, and $30$ of type 2.
As we zoom in towards the dodecahedron (or the dodecahedron become larger), the edges of each band move away from each other. The first change that happens is that the the 0' regions disappear and are replaced by $20$ cells of type 3. These new cells are the triangular spires of the great stellated dodecahedron.

Nothing new happens in the first of these pictures, except that the bands keep growing wider.
In the second picture the bands have just met in groups of five, and the last of the 0 and 1 regions disappear. Instead we get cells that are between 4 and 5 pairs of parallel planes.

The new yellow regions of type 4 merge, and we can see there are $30$ such cells, just as there were thirty 2s before, corresponding to the edges of either an icosahedron or a dodecahedron. In fact each of these cells is an irregular tetrahedron that shares one edge with the central dodecahedron, and the opposite edge with a great dodecahedron (whose edge figure looks like an icosahedron).
Removing the yellow tedrahedra from the great dodecahedron leaves a small stellated dodecahedron, whose pentagonal spires are the $12$ magenta 5 cells that came into being together with the 4s.

Finally a single red 6 cell appears: the original dodecahedron in the middle.
So how many regions were that? Summing everything we get
$$ \underbrace{(12+20)+60+30}_{\text{unbounded}}+\underbrace{20+30+12+1}_{\text{bounded}} = 185 $$

A: There is a nice combinatorial formula for the number of regions in a hyperplane arrangement in $\mathbb{R}^d$.
$$r(\mathcal{A}) = (-1)^d\chi_\mathcal{A}(-1)$$
Where $r(\mathcal{A})$ denotes the number of regions and $\chi_\mathcal{A}(t)$ is the characteristic polynomial of the underlying poset of flats.
In this case we get that $\chi_\mathcal{A}(t) = t^3-12t^2+60t-112$, so $$r(\mathcal{A}) = (-1)^3(-1-12-60-112)= 185$$
This setup also lets you read off the number of bounded regions by the formula:
$$b(\mathcal{A}) = \pm\chi_\mathcal{A}(1)$$
So we get 63 bounded regions.
For a reference on all this I'll recommend Richard Stanley's lecture notes on hyperplane arrangements available here: http://www.cis.upenn.edu/~cis610/sp06stanley.pdf

A: OK, Henning Makholm did the explanation, and did it good, but I'll do my part anyway.
First we extend the faces of our dodecahedron just a bit beyond the edges, until it grows nice little spikes on all 12 faces and thus becomes a small stellated dodecahedron.

Then we grow them a bit further, until each valley between the two neighboring spikes is filled. There were as many valleys as edges in a dodecahedron, so this gives us 30 more regions and creates the thing known as great dodecahedron.

Now we grow them further yet until we see new, sharper spikes where the depressions used to be. These correspond to the vertices of the original guy, so we add 20 of them and behold, here is your great stellated dodecahedron.

All in all, this gives us $1+12+30+20=63$ bounded regions.
So it goes.

A: I found 432 in the book
"Les nombres remarquables" by Francois Le Lionnais (Herman, 1983)
(which is a list of interesting numbers), but there is no reference or proof. Among these 432 parts 192 are bounded.