text:
Q: Wait for JavaScript condition in Nightwatch.js I am new to Nightwatch.js and am moving some tests over from the WD.js library. One nifty feature of WD.js is .waitForConditionInBrowser(), which waits for an arbitrary JavaScript snippet to be truthy. I am however unable to figure out how to interact with the JavaScript this way in Nightwatch.js, or if it's even possible (after perusing the docs). Here is an example of what I want to do:
Let's say I am loading a page where after about 3 seconds my_js_var becomes 5. In WD.js, it would look like this (wait max. 5 seconds):
.get(my_page_url)
.waitForConditionInBrowser('my_js_var === 5', 5000)
// continue if my_js_var === 5 within 5 s

I even tried doing something more dirty in Nightwatch, but I am probably misunderstanding how interaction with page JS works at all:
.url(my_page_url)
.pause(5000)
.execute(function() {
    return (my_js_var === 5);
})
// continue if my_js_var === 5 within 5 s

But it just continues no matter what is returned, and it's unclear where the result goes to.
Is there a proper waitFor function in Nightwatch, and if not, how do I run basic assertions on evaluated JavaScript code?

A: It's been a while, but I used to do something like this:
exports.command = function(callback) {
  var self = this;
  this.timeoutsAsyncScript(5000, function() {
    this.executeAsync(function(done) {
        if(my_js_var === 5) {
          return my_js_var === 5
        }
        else {
          done();
        }
      },
      [],
      function(result) {
        if(typeof(callback) === "function") {
          callback.call(self, result);
        }
      });
  });
  return this;
};

The timeout in timeoutsAsyncScript lets you assure a reasonable wait time so that the test can fail accordingly when it should fail.


text:
Q: BootstrapValidation is not working for me please see this code I'm trying to add bootstrapvalidation to my website signup form but I'm not getting it to work need help please.
Here is the form code:
If any one can help me fix this I will be really greatful, Thanks.

$(document).ready(function() {
    $('#tryitForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            firstName: {
                validators: {
                    notEmpty: {
                        message: 'The first name is required and cannot be empty'
                    }
                }
            },
            lastName: {
                validators: {
                    notEmpty: {
                        message: 'The last name is required and cannot be empty'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: 'The email address is required'
                    },
                    emailAddress: {
                        message: 'The input is not a valid email address'
                    }
                }
            },
            gender: {
                validators: {
                    notEmpty: {
                        message: 'The gender is required'
                    }
                }
            }
        },
        submitHandler: function(validator, form, submitButton) {
            var fullName = [validator.getFieldElements('firstName').val(),
                            validator.getFieldElements('lastName').val()].join(' ');
            alert('Hello ' + fullName);
        }
    });
});

<form id="tineyForym2" name="form1" method="post" action="#" enctype="multipart/form-data">
    <input type="hidden" value="" name="user_id">
        <input type='hidden' name='action' value='edit' >

                        *First Name

                        <input name="FirstName" class="form-control" value="" type="text" id="firstname" data-toggle="tooltip" data-placement="bottom" title="Enter your First name!">

                            *Last Name

                            <input name="LastName" class="form-control" value="" type="text" data-toggle="tooltip" data-placement="bottom" title="Enter your last name!">

                                *Username

                                <input name="Username" class="form-control" value="" type="text" data-toggle="tooltip" data-placement="bottom" title="Username will be used for login purpose!">

(Choose Your username. Use letters, or numbers, but don't use spaces.)

                                        *Password

                                        <input class="form-control" name="Password" value="" type="password" id="password" data-toggle="tooltip" data-placement="bottom" title="Enter Login Password!">

                                            *Confirm Password

                                            <input class="form-control" name="Password2" type="password" value="" id="password2" data-toggle="tooltip" data-placement="bottom" title="Enter Matching password">

                                                *Your E-mail

                                                <input class="form-control" name="Email" type="email" id="email" value="" id="email" data-toggle="tooltip" data-placement="bottom" title="Your Email Address">

                                                Receive Newsletter

                                                        <input name="Newsletter" type="radio" value="1"  >Yes

                                                            <input name="Newsletter" type="radio" value="0" >No

                                                        Auto Notification on new Jobs

                                                                <input name="Notification1" type="radio" value="1" >Yes

                                                                    <input name="Notification1" type="radio" value="0" >No

                                                            <input class="btn btn-primary btn-lg" type="submit" name="dede" value="Submit">

 By clicking
                                                                Submit, you agree to the
                                                                Terms and Conditions set out by this site, including our Cookie Use.

                                                    </form>

And here is the jsfiddle link: http://jsfiddle.net/eo5t48rw/5/

A: *

*You should to use equal names for control names and for validator names.Ex.
fields: {  firstName: { ...}, LastName { ...}, USERNAME {...} }
and controls should be named as name="firstName", name="LastName", name="USERNAME". Names are case sensitive!

*for right using bootstrap validators you should use bootstrap document structure, like:
<form id="tineyForym2" name="tineyForym2" method="post" class="form-vertical">

     First Name

      <input name="firstName" class="form-control" value="" type="text"  title="Enter your First name!" />

     Last Name

      <input name="lastName" class="form-control" value="" type="text"  title="Enter your Last name!" />

...

*I had js error "too much recursion" in your code . in line
name="Email" type="email" id="email"
Rename this input control . it should not equal a type name (type="email")

*in you example you init bootstrapValidator on nonexistent form element
$('#tryitForm').bootstrapValidator
should be
$('#tineyForym2').bootstrapValidator

redpajama_set_name: RedPajamaStackExchange


text:
Q: UI Elements not affected by light I'm trying to make a menu screen in which all the UI elements (buttons, text...) are completely dark and by touching the screen you create a fire (or just an area light) that makes the UI elements visible.
Sort of like this
I read that the default shader for the UI elements isn't affected by light, but i can't seem to change it.
How do I go about doing this?

A: The UI elements by default use a unlit shader and are also rendered directly to clip space. so you'll need to do two things, first put a lit shader onto the elements, the unity standard shader should do fine, then you should change the canvas render mode to world space. with the canvas in world space you can move it around like it was a sprite. i would also recommend creating a second higher priority camera for the UI with culling turned off. with the canvas in view of the UI camera, you should be able to place a light source near it and see the resulting lighting on the UI.


text:
Q: Javascript: String search for regex, starting at the end of the string Is there a javascript string function that search a regex and it will start the search at the end?
If not, what is the fastest and/or cleanest way to search the index of a regex starting from the end?
example of regex:
/<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi

A: Maybe this can be useful and easier:
str.lastIndexOf(str.match(<your_regex_here>).pop());

A: Perhaps something like this is suitable for you?
Javascript
function lastIndexOfRx(string, regex) {
    var match = string.match(regex);

    return  match ? string.lastIndexOf(match.slice(-1)) : -1;
}

var rx = /<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi;

console.log(lastIndexOfRx("", rx));
console.log(lastIndexOfRx("itbo", rx));

jsFiddle
And just for interest, this function vs the function that you choose to go with. jsperf
This requires that you format your regex correctly for matching exactly the pattern you want and globally (like given in your question), for example /.*(<\/?([a-z][a-z0-9]*)\b[^>]*>?)/i will not work with this function. But what you do get is a function that is clean and fast.

A: You may create a reverse function like:
function reverse (s) {
  var o = '';
  for (var i = s.length - 1; i >= 0; i--)
    o += s[i];
  return o;
}

and then use
var yourString = reverse("Your string goes here");
var regex = new Regex(your_expression);
var result = yourString.match(regex);

Another idea: if you want to search by word in reverse order then
function reverseWord(s) {
   var o = '';
   var split = s.split(' ');

  for (var i = split.length - 1; i >= 0; i--)
    o += split[i] + ' ';
  return o;
}

var yourString = reverseWord("Your string goes here");
var regex = new Regex(your_expression);
var result = yourString.match(regex);

A: Andreas gave this from the comment:
https://stackoverflow.com/a/274094/402037
String.prototype.regexLastIndexOf = function(regex, startpos) {
    regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
    if(typeof (startpos) == "undefined") {
        startpos = this.length;
    } else if(startpos < 0) {
        startpos = 0;
    }
    var stringToWorkWith = this.substring(0, startpos + 1);
    var lastIndexOf = -1;
    var nextStop = 0;
    while((result = regex.exec(stringToWorkWith)) != null) {
        lastIndexOf = result.index;
        regex.lastIndex = ++nextStop;
    }
    return lastIndexOf;
}

Which gives the functionality that I need, I tested my regex, and it is successful. So I'll use this

A: It depends what you exactly want to search for. You can use string.lastIndexOf or inside the regexp to use $ (end of the string).
Update:
try the regexp
/<\/?([a-z][a-z0-9]*)\b[^>]*>?[\w\W]*$/gi

A: var m = text.match(/.*(<\/?([a-z][a-z0-9]*)\b[^>]*>?)/i);
if (m) {
    textFound = m[1];
    position = text.lastIndexOf(textFound);
}

Use .* to skip as much text as posible, capture the text found and search it with lastIndexOf
EDIT:
Well, if text is found, no need to search with lastIndexOf. m[0] contains the full coincidence (including all the initial padding), and m[1] the searched text. So position of found text is m[0].length - m[1].length
var m = text.match(/.*(<\/?([a-z][a-z0-9]*)\b[^>]*>?)/i);
if (m) {
    textFound = m[1];
    position = m[0].length - m[1].length;
}

A: Assuming you're looking for a string 'token', then you need the position of 'token' that has no other 'token' following until the end of the string.
So you should compose your regex something like that:
$token = 'token';
$re = "/(?:$token)[^(?:$token)]*$/";

This will find your 'token' where no further 'token' can be found until string end. The "(?:" grouping simply makes the group non-storing, slightly speeding up performance and saving memory.


text:
Q: Select Item from Listview using iteminvoke in Javascript I have a ListView with items. I am trying get clicked item from Listview using "iteminvoked".
    <div id="listView_Id" data-win-control="WinJS.UI.ListView"
     data-win-options="{
            itemTemplate: select('#smallListIconTextTemplate'),
            selectionMode: 'single',
            tapBehavior: 'none',
            layout: { type: WinJS.UI.GridLayout }
        }">
   </div>

Here ListArray is array of values with filenames picked using 'FilePicker'
        dataList = new WinJS.Binding.List(listArray);
        var listControlDiv = document.getElementById("listView_Id");
        var listControl = listControlDiv.winControl;
        listControl.itemDataSource = dataList.dataSource;

I set ListView dataSource from JS file rather than HTML file by fallowing this question.
I created handler like this.
document.getElementById("listView_Id").addEventListener("iteminvoked", doClickItem, false);

But unfortunately, My doClickItem handler doesn't call at any way. While in same manner select item from Listview which is working Fine.
I guess I set Listview datasource using Javascript(The items source will be Change repeatedly). What is the wrong I did here.
Here is my complete project to try
Thanks

A: Try this..
 var listControl = document.getElementById("listView_Id").winControl;
 listControl.addEventListener("iteminvoked", doClickItem, false);


text:
Q: In Python: Why does a Numpy array returned in a method have to be stored in the instance? The issue is a bit complicated so I need to give you the full story:
I'm trying to create basic sound using the package pyaudio.
The pyaudio module asks for a callback function that reads audio data.
It basically looks like this:
def callback():
    return sound.readframes()

I have a class that provides audio data. It creates a signal by indexing a numpy array that contains a wave length of a basic wave form. It basically looks like this:
class Wave(object):
    data = [] # one wavelength of a basic waveform like a sine wave will be stored here

    def readframes(self):
        indices = # the indices for the next frames
                  # based on a frequency and the current position
        return self.data[indices]

class SineWave(Wave):
    data = # points of a sine wave in a numpy array

sound = SineWave()

# pyaudio now reads audio data in a non-blocking callback mode

Now to the problem:
There was noise between each call to readframes or each block of audio data. The sound itself was still intact, but there was an additional clicking. Increasing the size of the returned data block also increased the time between each click. I still don't quite know what caused the noise, but I fixed it by storing the returned numpy array in the instance instead of returning it directly.
This causes noise:
return self.data[indices]

This does not cause noise:
+ self.result = self.data[indices]
+ return self.result

It can't be an alteration of the data that causes the noise or else this wouldn't fix it. Why does the result have to be stored in the instance?
Update:
I also have to mention that the noise doesn't occur everytime I run the script. It occurs randomly about 50% of the runs. Either the noise appears right at the start and won't go away or it doesn't appear at all.
It looks like an issue with the initialization of the sound device, but how that could be related to my fix is a mistery.
Here is code that reproduces the noise problem:
import pyaudio
import time
from numpy import sin, linspace, arange, pi, float32, uint32

SR = 44100  # sampling rate
FPB = 2048  # frames per buffer

class SineWave(object):
    """A sine wave"""

    data_size = 2**10
    data = sin(linspace(0, 2*pi, data_size, endpoint=False, dtype=float32))

    def __init__(self, frequency):
        self.pos = 0
        self.fq = frequency
        self.ppf = self.data_size * self.fq / SR  # points per frame

    def readframes(self):
        size = FPB
        pos = self.pos
        indices = (arange(pos, size+pos)*self.ppf).astype(uint32) & (self.data_size-1)
        self.pos = (self.pos + size) % SR
        self.result = self.data[indices]
        return self.data[indices]

def callback(in_data, frame_count, time_info, status):
    return sound.readframes(), pyaudio.paContinue

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(4),
                channels=1,
                rate=SR,
                output=True,
                stream_callback=callback,
                frames_per_buffer=FPB)

sound = SineWave(440)
stream.start_stream()
time.sleep(2)
stream.stop_stream()
stream.close()
p.terminate()

On my system the noise appears in about 90% of the runs.
Changing
return self.data[indices]

to
return self.result

fixes it.

A: There shouldn't be a difference whether you store the intermediate array in the instance or not. I suspect there is some other problem going on that causes the error you're experiencing. Can you provide code that actually runs and exhibits the problem?
If you want to see a (hopefully!) working implementation, have a look at the play() function of the sounddevice module, especially at the loop argument. With this, you should be able to play your waveform repeatedly.
The only thing you need to store in the instance, is the frame index where you left off, just to continue with the following frame index in the next callback (and of course wrap around in the end). You should also consider the case where your wave form is shorter than an audio block. It might even be much shorter. I solved that by using a recursive function call, see the code.

UPDATE:
It's indeed quite strange that assigning to self "solves" your problem. I think this has something to do with how PyAudio interprets the returned array as Python buffer.
You should rewrite your code using the sounddevice module, which properly supports NumPy arrays and has a sane API for the callback function.
It's easy, just use this callback function:
def callback(outdata, frames, time, status):
    if status:
        print(status)
    outdata[:, 0] = sound.readframes()

And start the stream with:
import sounddevice as sd
stream = sd.OutputStream(
    channels=1, samplerate=SR, callback=callback, blocksize=FPB)

Apart from that, your code is flawed since it doesn't do any interpolation when reading from the wavetable.


text:
Q: data received on server from android app always null I am trying to connect from a android emulator to a application on my desktop and send a line of text.
My app is able to connect to the server, but when ever i try to read data its always null
Server application running on my desktop:
ServerSocket ss = new ServerSocket(9001);
Socket cs = ss.accept();
if (cs.isConnected()) {
    System.out.println("Client connected.");
}

BufferedReader reader = new BufferedReader(new InputStreamReader(cs.getInputStream()));

String str = reader.readLine();
System.out.println("Data:" + str);

Client application running in android app emulator:
    InetAddress addr = InetAddress.getByName("10.0.2.2");
    Socket socket = new Socket(addr, 9001);

    if (socket.isConnected()) {
        Log.d("APP", "socket connected");
    }

    PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    String str = "this is a sample";
    pw.write(str);

I can see that the isConnected function of the socket on both the client and server turns true.
But the Data printed on the server is always null.
Thanks

A: Try adding a flush call after the 'pw.write(str)' statement:
pw.flush();


text:
Q: geometry question in HK IMO prelim 2018 2018 IMO prelim in HK, Q.3:
In triangle ABC, ∠ BAC = 18° and angle ∠BCA = 24°. D is a point on AC such that ∠BDC = 60°. If the bisector of ∠ADB meets AB at E, find ∠BEC.
Any form of help will be appreciated.

A: Also, there is a nice geometric solution.
Indeed, let $F\in BC$ such that $B$ placed between $C$ and $F$.
Thus, since $$\measuredangle DBA=\measuredangle ABF=42^{\circ}$$ and
$$\measuredangle BDE=\measuredangle ADE=60^{\circ},$$ we obtain that $CE$ is a bisector of $\angle ACB$, which gives $\measuredangle ACE=12^{\circ},$ which says
$$\measuredangle BEC=12^{\circ}+18^{\circ}=30^{\circ}.$$

A: Let $BD\cap CE=\{P\}$ and $\measuredangle BEC=x$.
Thus, $$\measuredangle CDB=\measuredangle BDE=\measuredangle ADE=60^{\circ},$$
which says that $DP$ is a bisector of $\angle CDE$.
Also, easy to see that $\measuredangle DCE=x-18^{\circ},$ $\measuredangle BCE=42^{\circ}-x,$ $\measuredangle CBP=96^{\circ},$ $\measuredangle PBE=42^{\circ}$ and $\measuredangle PED=78^{\circ}-x.$
Id est, by law of sines we obtain:
$$\frac{\sin(x-18^{\circ})}{\sin(78^{\circ}-x)}=\frac{ED}{CD}=\frac{EP}{PC}=\frac{\frac{EP}{BP}}{\frac{PC}{BP}}=\frac{\frac{\sin42^{\circ}}{\sin{x}}}{\frac{\sin96^{\circ}}{\sin(42^{\circ}-x)}},$$ which gives
$$\sin96^{\circ}\sin(x-18^{\circ})\sin{x}=\sin42^{\circ}\sin(42^{\circ}-x)\sin(78^{\circ}-x)$$ or
$$2\sin48^{\circ}\left(\cos18^{\circ}-\cos(2x-18^{\circ})\right)=\cos36^{\circ}-\cos\left(120^{\circ}-2x\right)$$ or
$$\sin66^{\circ}+\sin30^{\circ}-\sin(30^{\circ}+2x)-\sin(66^{\circ}-2x)=\cos36^{\circ}+\cos\left(60^{\circ}+2x\right)$$ or
$$\cos24^{\circ}-\cos36^{\circ}+\sin30^{\circ}-\sin(66^{\circ}-2x)-\cos\left(60^{\circ}-2x\right)-\cos\left(60^{\circ}+2x\right)=0$$ or
$$\sin6^{\circ}+\sin30^{\circ}-\sin(66^{\circ}-2x)-\cos2x=0$$
$$\sin6^{\circ}-\sin(66^{\circ}-2x)+\cos60^{\circ}-\cos2x=0$$ or
$$\sin(x-30^{\circ})\cos(36^{\circ}-x)+\sin(x-30^{\circ})\sin(x+30^{\circ})=0$$ or
$$\sin(x-30^{\circ})(\cos(36^{\circ}-x)+\sin(x+30^{\circ}))=0$$ and since $18^{\circ}<x<42^{\circ},$ we obtain $$\sin(x-30^{\circ})=0$$ or
$$x=30^{\circ}.$$


text:
Q: Read a csv that has non delimited text and blank lines above column headers and the bottom of the file using Pandas I am trying to read a pipe delimited file using Pandas read_csv. However the files may or may not come with non delimited text either on the top or the bottom of the file.
I have tried:
pd.read_csv('file_sample.csv', sep='|', error_bad_lines=True)

However that does not work.
I am aware that I can read the file using the csv library and read line by line to confirm that the row is valid. Unfortunately I need a non looping solution, preferably using Pandas.
Thank you for your help
(60084 row(s) affected)

(30723 row(s) affected)

(41701 row(s) affected)

(171209 row(s) affected)

(17348 row(s) affected)

ProductId|ModelId|ProgramId|BranchId|AdvisorId|TotalAssets|NewAssets|AdditionAssets|ConversionNewAssets|TerminatedAssets
102abc|1|100|xyz|vbd|100|1900|0|10|0
103abc|1|100|xyz|vbd|150|1905|0|10|0
104abc|1|100|xyz|vbd|200|1910|0|10|0
102abc|1|100|xyz|vbd|250|1915|0|10|0
103abc|1|100|xyz|vbd|300|1920|0|10|0
104abc|1|100|xyz|vbd|350|1925|0|10|0
102abc|1|100|xyz|vbd|400|1930|0|10|0
103abc|1|100|xyz|vbd|450|1935|0|10|0

(1648248 row(s) affected)

A: *

*comment = '(' it ignore lines start with ( and consider its as comment.

*skip_blank_lines = True Blank line is by default ignored. As skip_blank_lines default value is True.

See here more optional parameters here
>>> df = pd.read_csv('file_sample.csv', sep='|', comment='(')
>>> df
  ProductId  ModelId  ...  ConversionNewAssets TerminatedAssets
0    102abc        1  ...                   10                0
1    103abc        1  ...                   10                0
2    104abc        1  ...                   10                0
3    102abc        1  ...                   10                0
4    103abc        1  ...                   10                0
5    104abc        1  ...                   10                0
6    102abc        1  ...                   10                0
7    103abc        1  ...                   10                0

[8 rows x 10 columns]


text:
Q: React-Native ScrollView inside PanResponder: onStartShouldSetPanResponderCapture and onMoveShouldSetPanResponderCapture ignored for fast gestures I have a React-Native component consisting of a View with an attached PanResponder that wraps a ScrollView:
import React from "react";
import { PanResponder, ScrollView, StyleSheet, View, Text } from "react-native";

const TestPanResponder = () => {
    const panResponder = React.useRef(
        PanResponder.create({
            onStartShouldSetPanResponder: () => true,
            onStartShouldSetPanResponderCapture: () => true,
            onMoveShouldSetPanResponder: () => true,
            onMoveShouldSetPanResponderCapture: () => true,
            onPanResponderTerminationRequest: () => {
                console.log("Termination request.")
                return false;
            },
            onPanResponderTerminate: () => {
                console.log("Terminated.")
            },
            onShouldBlockNativeResponder: () => false,
        })
    ).current;

    return (
        <View style={styles.container} {...panResponder.panHandlers}>
            <ScrollView style={styles.list}>
                {[...Array(10).keys()].map((item, index) =>
                    <View style={styles.sections} key={index}>
                        <Text>This is some text.</Text>
                    </View>
                )}
            </ScrollView>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        backgroundColor: "#aaa",
        flex: 1,
    },
    list: {
        flex: 1,
    },
    sections: {
        height: 100,
        backgroundColor: "#fff",
        margin: 10,
        borderRadius: 5,
        alignItems: "center",
        justifyContent: "center"
    }
});

export default TestPanResponder;

Android 12, react: 18.1.0, react-native: 0.70.5, expo: 47.0.0
I want the PanResponder to remain in charge of handling all touches (i.e. in this case, I want to prevent scrolling of the ScrollView altogether; later I want to hand over control to the ScrollView if certain conditions about the gesture are met).
To my understanding, the RN Gesture Responder System consists of two phases:

*

*an capturing phase that recursively calls on*ShouldSetPanResponderCapture starting with parent components, where each component can "decide" whether it wants to remain the responder,

*a second phase where on*ShouldSetPanResponder methods are called following a bubbling pattern, i.e. starting at the most deeply nested component.

I would therefore expect that by setting on*ShouldSetPanResponderCapture to true the ScrollView should never respond to touches. This is indeed what happens if I scroll slowly. However, if the upward swipe gesture is performed quickly, the list starts scrolling. Looking at the console logs, I noticed that onPanResponderTerminate gets fired, but not onPanResponderTerminationRequest.
Can anyone explain why this is the case (esp. why does the velocity of the gesture matter?) and suggest a fix?
I do realize that I could set scrollEnabled on the ScrollView, but I want to avoid re-rendering the list if possible in the more complicated end scenario.


text:
Q: jQuery - use of a global function In an HTML page, having two buttons (EDIT, DELETE), I do an AJAX call then I parse the returned JSON and I do perform an EDIT or a DELETE based on the returned ID. All this inside of a
$( document ).ready(function() {
    ...
    $('button.icons8.icons8-edit-file').on("click", function(){
        var key = $(this).attr('key');
        $.ajax({
            url: '/ede/' + key + '/json',
            method: 'POST',
            success: function (response) {
                // PARSING THE JSON, EXTRACTING THE ID FROM IT
                // AND PERFOMING THE EDIT
            }
        });
    })
    ...
    $('button.icons8.icons8-delete-file').on("click", function(){
        var key = $(this).attr('key');
        $.ajax({
            url: '/ede/' + key + '/json',
            method: 'POST',
            success: function (response) {
                // PARSING THE JSON, EXTRACTING THE ID FROM IT
                // AND PERFOMING THE DELETE
            }
        });
    })
    ...
});

What I would like to have is a global function what gets the key value, does the AJAX call and returns a value according to a pattern.
$( document ).ready(function() {
    ...
    $('button.icons8.icons8-edit-file').on("click", function(){
        var key = $(this).attr('key');
        var value = GLOBAL_FUNCTION(key, pattern_edit);
        // PERFOMING THE EDIT
    })
    ...
    $('button.icons8.icons8-delete-file').on("click", function(){
        var key = $(this).attr('key');
        var value = GLOBAL_FUNCTION(key, pattern_delete);
        // PERFOMING THE DELETE
    })
    ...
});

Where sould I put that GLOBAL_FUNCTION(p_key, p_pattern) fuction? Inside or outside of the ready function? How do I return the response from this global function? What if the result of parsing the response produces a list of values?

A:
Where should I put that GLOBAL_FUNCTION(p_key, p_pattern) function? Inside or outside of the ready function?

You can put it anywhere in scope of all the places you want to call it. Global is one possibility but should be avoided where possible. Instead, I'd suggest namespacing your common functions in to their own object. This way you can then extract them to a separate JS file for easy re-use.

How do I return the response from this global function?

If the function is making an AJAX request you can't return anything, as the call should be asynchronous. You can work around this by providing a callback function to execute when the request completes.
With those points in mind, the code would look something like this:
// common.js
var common = (function() {
  return {
    global_function: function(key, callback) {
      $.get('/ede/' + key + '/json', function(response) {
        // perform common actions here, if needed..
        callback && callback(response);
      }
    }
  };
})();

// in your page:
$('button.icons8.icons8-edit-file').on("click", function() {
    var key = $(this).data('key');
    common.global_function(key, function(response) {
      // Edit response.id...
    });
});

$('button.icons8.icons8-delete-file').on("click", function() {
    var key = $(this).data('key');
    common.global_function(key, function(response) {
      // Delete response.id...
    });
});

It would also make sense to extract the delete and edit logic to the common library, but I'll leave that to you based on your own logic.
Finally, note the use of data() here, as creating your own non-standard attributes will make your HTML invalid. Use data-key instead.

A: You can put a function just in the jQuery ready state and use them in both callbacks. It's not really global, but it's in the right scope to use in both.
But GLOBAL_FUNCTION function can't return the value, because $.ajax is async. But you can pass a callback to the function, executed after finish.
And you can tell jQuery that the response is in JSON format, so it will parse it automatically for you.

$( document ).ready(function() {
    function GLOBAL_FUNCTION(key, type, callback) {
        $.ajax({
            url: '/ede/' + key + '/json',
            method: 'POST',
            dataType: 'json,
            success: function (response) {
                // EXTRACTING THE ID FROM RESPONSE
                var id = response.id;

                if (type === 'edit') {
                  // PERFOMING THE EDIT
                }

                if (type === 'delte') {
                  // PERFOMING THE DELETE
                }

                // EXECUTE CALLBACK ON FINISH
                callback(id, type);
            }
        });
    };

    $('button.icons8.icons8-edit-file').on("click", function(){
        var key = $(this).attr('key');
        GLOBAL_FUNCTION(key, 'edit', (id, type) => {
            console.log(type + ' of id #' + id + ' finished');
        });
    })

    $('button.icons8.icons8-delete-file').on("click", function(){
        var key = $(this).attr('key');
        GLOBAL_FUNCTION(key, 'delete', (id, type) => {
            console.log(type + ' of id #' + id + ' finished');
        });
    })

});


text:
Q: Tomcat JNDI error I get this error
Jun 23, 2009 4:49:10 PM org.apache.catalina.startup.Catalina start INFO: Server
   startup in 5265 ms
0 [http-8080-Processor25] ERROR Could not load security-xss-regex.txt file. [at
   app.sparx.navigate.AppNavigationControllerServlet.init(AppNavigationControllerServlet.java:45)]
   Unable to register any web resource locators (/resources/sparx, /sparx were not found).
   Please use the SparxResourcesServlet for serving Sparx resources.
2328 [http-8080-Processor25] ERROR Name jdbc is not bound in this Context [at
   net.sf.hibernate.util.JDBCExceptionReporter.logExceptions(JDBCExceptionReporter.java:58)]
2328 [http-8080-Processor25] ERROR net.sf.hibernate.exception.GenericJDBCException: Cannot
   open connection [at app.security.AppLoginAuthenticator.isUserValid(AppLoginAuthenticator.java:89)]
   and this is what I have in my server.xml file
Resource name="sparx"
   auth="Container" type="javax.sql.DataSource"
   driverClassName="com.ibm.db2.jcc.DB2Driver"
   url="jdbc:db2://192.168.0.131:50000/MAX"
   username="db2admin" password="!!!!!!!!!"

Anyone know what the exact name of the resource should be
Thanks

A: This link might help you.  The JNDI name should be "jdbc/sparx".
Looks like you can't open the connection because the file security-xss-regex.txt can't be found.
That stuff doesn't belong in server.xml.  (You can't always depend on being able to edit that file, anyway.)  The proper place is META-INF/context.xml
Did you declare the resource in your web.xml as well?  You must have that, you know.
The JDBC driver JAR has to be in the common/lib for Tomcat 5.x or /lib for Tomcat 6.x.
You're using a very old version of Hibernate - that package name starting with "net.sf.hibernate" is ancient.  Time for an upgrade?
If you're still having problems, I'd try swapping in another database to stand in for DB2, just to get the connection working.  MySQL, Hypersonic - ANYTHING other than an IBM product.  If you get that to work, you'll know that DB2 specific things are the issue.


text:
Q: Changing some values in an Array Source array:
$source_array = array("email"=>"email@email.com", "name"=>"adem", "last_name"=>"genc", "username"=>"ademgenc", "age"=>"40", "issue"=>"php", "version"=>"12,50", "user_group"=>"2", "created"=>"2020-09-02 10:58:54");

Values to be changed array:
$values_to_be_changed_array = array("email"=>"adem@email.com", "issue"=>"asp", "username"=>"genc");

The number of values to change may vary.

A: You need to replace the value by this :
$a1=array($source_array["name"],"<old_name>");
$a2=array($source_array["name"],"<new_name>");
print_r(array_replace($a1,$a2));

Check this..

A: You can use array_replace
  $source_array = ["email"=>"email@email.com", "name"=>"adem", "last_name"=>"genc", "username"=>"ademgenc", "age"=>"40", "issue"=>"php", "version"=>"12,50", "user_group"=>"2", "created"=>"2020-09-02 10:58:54"];

  $values_to_be_changed_array = array("email"=>"adem@email.com", "issue"=>"asp", "username"=>"genc");

  $new_array = array_replace($source_array,$values_to_be_changed_array);

  print_r($new_array);

Output with :
  Array
    (
        [email] => adem@email.com
        [name] => adem
        [last_name] => genc
        [username] => genc
        [age] => 40
        [issue] => asp
        [version] => 12,50
        [user_group] => 2
        [created] => 2020-09-02 10:58:54
    )


text:
Q: Managing mega Arrays in PHP I'm doing a data-mine on millions of old log entries for someone and really want to use PHP in this matter to present the materials a link them easily to the existing PHP system.
I run this code in the PHP 5.4.4 in the Terminal (OSX 10.8):
// Settings
ini_set('error_reporting', E_ALL); // Shows all feedback from the parser for debugging
ini_set('max_execution_time', 0); // Changes the 30 seconds parser exit to infinite
ini_set('memory_limit', '512M'); // Sets the memory that may be used to 512MegaBytes

echo 'Start memory usage: '.(memory_get_usage(TRUE) / 1024)."\n";

$x = Array();
for ($i = 0; $i < 1e7; $i++) {
    $x[$i] = 1 * rand(0, 10);
    //unset($x[$i]);
}

echo 'End memory usage: '.(memory_get_usage(TRUE) / 1024)."\n";
echo 'Peak memory usage: '.(memory_get_peak_usage(TRUE) / 1024)."\n";

This is a simple test with ten-million cycles. The leakage is really bad compared to using dictionaries in Python :(.
When I unquote the unset() function to test the usage, it's instantly all unicorns and rainbows. So forcing the release of the memory seems to go well.
Is there any way I can still maintain 10-50 million array entries within that 512M memory limit?
I can't imagine when I would do some regex with these kind of loops either..

A: Use SplFixedArray because you really need to see How big are PHP arrays (and values) really? (Hint: BIG!)
$t = 1e6;
$x = array();
for($i = 0; $i < $t; $i ++) {
    $x[$i] = 1 * rand(0, 10);
}

Output
Start memory usage: 256
End memory usage: 82688
Peak memory usage: 82688

and
$t = 1e6;
$x = new SplFixedArray($t);
for($i = 0; $i < $t; $i ++) {
    $x[$i] = 1 * rand(0, 10);
}

Output
Start memory usage: 256
End memory usage: 35584
Peak memory usage: 35584

But better still i think you should consider a memory based database like REDIS

A: If the SplFixedArray doesn't work for you I would strongly recomend the use of RabbitMQ -> http://www.rabbitmq.com/tutorials/tutorial-one-php.html
RabbitMQ is more simple to configure and use than normally people think and it has a good library for PHP.
With RabbitMQ your script can be ten, twenty, hundred times faster (depending the number of consumers you set) and you also can manage any amount of data.
I had use RabbitMQ to import milions of rows to retrieve information about all cars registered in Denmark imagine how big this can be.


text:
Q: Check Ip Against Server Issue C# So i have some code that will check if a user is on a ip blacklist list and this is the code i have come up with
string externalip = new WebClient().DownloadString("http://icanhazip.com");
bool checkipagainstserver = !new WebClient().DownloadString("https://ringarang.github.io/ipchecker.html").Contains(externalip);

then it is
if (checkagainstserver)
it shows a message box and quits the application
This code builds fine and works. If I change the url, it will catch out but when I add my ip to that list, it doesn't block execution and show message box even though my ip is clearly on that server text file
(the server files are there for testing and will be moved to the domain when done)

A: I fixed it the code needed too be
 string externalip = new WebClient().DownloadString("http://icanhazip.com");
 WebClient tempWebClient = new WebClient();
 bool checkipagainstserver =

then i needed to convert it


text:
Q: The only compact subgroups $G$ of the multiplicative complex numbers $\Bbb C^{\times}$ are the unit circle $S^{1}$ and the $n$th roots of unity I am new to abstract algebra and also topology and I struggling to understand this problem. What is the group of the multiplicative complex numbers? What does compact mean here? Why is the unit circle a compact subgroup of this group? Or the nth roots of unity. I will come up with the proof - but I wanted some direction on how to proceed.

A: By Heine-Borel theorem, any subset of $\mathbb R^n$ is compact if and only if it's bounded and closed.
Let $G$ be a compact subgroup of $\mathbb C^{\times}$, and assume $G$ has an element $x$ such that $|x|\neq 1$. We can assume $|x|<1$, instead we can use $x^{-1}$ to replace $x$. Then $x, x^2, x^3,\cdots$ is a sequence in $G$ that converges to 0, but $0 \notin G$, so $G$ is not compact.
Then $G \subseteq S^1$. Assume there is an element $Q=\exp(2\pi i q) \in G$ and $q$ is an irrational number, then for all $a \in [0,1]$, there is a sequence with elements in $G$ that converges to $A=\exp{2\pi i a} \in \mathbb C^{\times}$. We can prove it using rational approximation.
Let $q_n$ be an integer sequence such that $\lim\limits_{p\rightarrow\infty}\frac{q_p}{p}=Q$ where $p$ run through the sequence of prime numbers, and $\lim\limits_{p\rightarrow\infty}\frac{a_p}{p}=A$. Then $\lim\limits_{p\rightarrow\infty}x^{a_p \cdot (q_p^{-1} \mod p)}=a$.
So if there is such an ``irrational" element then the group is equal to $S^1$; if there is not the group is $n$-th root of unity.


text:
Q: How make an outgoing call from my app? i develop a calling program in the below way.
my main aim is enter the number in textfield and whenever i press the call button it convert
into the integer and then perform calling action.in xcode is there any possibility to create a
code for outgoing call?
And is there any possibility to block the incoming calls?
i am writing the code below way.
my .h file is
@interface mytextViewController : UIViewController
{
  IBOutlet UILabel *enterphonenumber;
    int currentNumber;
}

@property(nonatomic,retain)IBOutlet UILabel *enterphonenumber;

-(IBAction)call;

-(IBAction)press:(id)sender;

@end

my .m file is
-(IBAction)press:(id)sender
{
    currentNumber = currentNumber*10 + (int)[sender tag];

    enterphonenumber.text = [NSString stringWithFormat:@"%i",currentNumber];
}

-(IBAction)call

{
    int x =[enterphonenumber.text intValue];

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:x]];
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"%tel:9963610177"]];
    NSLog(@"sample %@",[NSURL URLWithString:@"my phone number is calling"]);
}

And also how to examine it performs a calling
please any one help because i am the new to develop this application
Thanking you,

A: Try using the tel protocol.
if ([[[UIDevice currentDevice] model] isEqualToString:@"iPhone"])
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%d", number]]];
}

You cannot block any incoming calls.

A: You can't block any incoming calls in your app.


text:
Q: ASP.NET Custom Pricipal and Cookies (tickets) If i create a custom principal with five custom properties (example, phoneNumber), does the principal data get trasmitted inside of the cookie or does the data stay in the server?
void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    // Get Forms Identity From Current User
                    FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                    // Get Forms Ticket From Identity object
                    FormsAuthenticationTicket ticket = id.Ticket;
                    // Create a new Generic Principal Instance and assign to Current User
                    IFGPrincipal siteUser = new IFGPrincipal(Context.User.Identity, new string[] { }, 2);

                    HttpContext.Current.User = siteUser;
                }
            }
        }

    }


text:
Q: Table completely ignoring variable Private Sub Form_Current()
Dim bytoffcut As Byte
Dim strCriteria
strCriteria = "[WOID] = " & Forms![frmAddStockBooking]![MouldWO]

bytoffcut = Nz(DMax("OffcutNo", "dbo_tblOffcuts", strCriteria), 0) + 1
MsgBox bytoffcut
Me.txtOffcut.Value = bytoffcut

Me.WOID.Value = Forms![frmAddStockBooking]![MouldWO]
Me.txtdate.Value = Now()

End Sub

Can anyone tell me why this is not working? The variable is behaving as expected where bytoffcut increments by one when i create a new record. But when I check the table the field bound to txtOffcut the field reads 1 instead of the incremented value.
EDIT: This code is being used in the On current property of the form. When I create a new record using a button on the form Dmax is used to find the highest offcut No value in a table and add one to it.
This appear to work in the form as the offcut no txtbox increments. But when i look at the table instead of having records with an increasing offcut no Instead all records read 1

A: Try sending your where clause in the DMax like this, assuming the WOID field in the table is an number type and not text or date.
"[WOID] = " & Forms![frmAddStockBooking]![MouldWO]

A: It would be better to evaluate your DMax() expression only once, especially if dbo_tblOffcuts is a large linked table without a usable index on [WOID].
If your DMax() expression can return a Null, use Nz() to transform the Null to zero.  Then add one.
Dim bytoffcut As Byte
Dim strCriteria
strCriteria = "[WOID] = " & Forms![frmAddStockBooking]![MouldWO]
'Debug.Print strCriteria '
bytoffcut = Nz(DMax("OffcutNo", "dbo_tblOffcuts", _
    strCriteria), 0) + 1
MsgBox bytoffcut
Me.txtOffcut.value = bytoffcut

This may not give you what you want when other users are editing dbo_tblOffcuts.

A: I have managed to solve the issue of multiple records being updated by creating a primary key for the table I am writing to.
I think that because Access could not uniquely identify the record it would edit all the records that met the criteria or something of the ilk. I am not entirely sure myself.


text:
Q: Excess elements in scalar initializer in byte create in iOS In my project, I create a byte:
Byte bytes = {0x7E, 0x7F};

But there comes a warning:

Excess elements in scalar initializer

What this mean? does it effect me?

A: You are trying to create single dimensional array where you are not declaring size of it there's no memory set aside for an array so that's why the compiler is generating a warning which may cause an runtime error ahead.
Set array size:
// single dimen
Byte bytes[2] = {0x7E, 0x7F};

// double dimen
Byte bytes[1][2] = {{0x7E, 0x7F}, {0x7E, 0x7F}};

A: how stupid! I create a byte array should be like this:
Byte bytes[] = {0x7E, 0x7F}
I did not write the [].


text:
Q: How Do I Create a Dynamic Keyname Using Php AWS S3 API Have been testing the latest Php AWS S3 API and I not sure how to dynamically name a keyname when a user uploads a new book, reason being I need to be able to retrieve the uploaded book by XYZ customer.  Thanks in advance!
 <?php
  require 'aws/aws-autoloader.php';

  use Aws\S3\S3Client;
  use Aws\S3\Exception\S3Exception;

  //AWS S3 SHITE BELOW
  $bucket = 'acmebooks';
  //CREATE DYNAMIC KEYNAME??
  $keyname = 'RANDOM KEYNAME';
  $secret = 'FOOBAR1345';

  $credentials = new Aws\Credentials\Credentials($keyname, $secret);

  $s3 = new Aws\S3\S3Client([
  'version'     => 'latest',
  'region'      => 'us-east-2',
  'credentials' => $credentials
  ]);

  try {
  // Upload data.
   $result = $s3->putObject([
    'Bucket' => $bucket,
    'Key'    => $keyname,
    //Body'   => 'Hello, world!',
    'Body'   => 'https://booksrun.com/image-loader/350/https:__images-na.ssl-images-amazon.com_images_I_41sYJq3nAWL.jpg',
    'ACL'    => 'public-read'
]);

// Print the URL to the object.
echo $result['ObjectURL'] . PHP_EOL;
print_r($result['Body']);
} catch (S3Exception $e) {

    echo $e->getMessage() . PHP_EOL;

}
?>

A: Was overlooking and confusing $keyname which is my unique AWS S3 "Key", for the "Key name" of what is PUT into the AWS S3 Bucket.
FIX BELOW
<?php
 require 'aws/aws-autoloader.php';

 use Aws\S3\S3Client;
 use Aws\S3\Exception\S3Exception;

 //TEST FOR AWS S3
 $key_input = 'jaybookcover1';

 //AWS S3 SHITE BELOW
 $bucket = 'acmebooks';
 //UNIQUE AWS S3 KEYNAME??
 $keyname = ' my unique AWS S3 key';
 $secret = 'FOOBAR1345';

 $credentials = new Aws\Credentials\Credentials($keyname, $secret);

 $s3 = new Aws\S3\S3Client([
 'version'     => 'latest',
 'region'      => 'us-east-2',
 'credentials' => $credentials
 ]);

 try {
 // Upload data.
 $result = $s3->putObject([
'Bucket' => $bucket,
'Key'    => $key_input,
//Body'   => 'Hello, world!',
'Body'   => 'https://booksrun.com/image-loader/350/https:__images-na.ssl-images-amazon.com_images_I_41sYJq3nAWL.jpg',
'ACL'    => 'public-read'
]);

// Print the URL to the object.
echo $result['ObjectURL'] . PHP_EOL;
print_r($result['Body']);
} catch (S3Exception $e) {

echo $e->getMessage() . PHP_EOL;

}
?>


text:
Q: Pine Script "strategy.position_size" is delayed by a candle The function --strategy.position_size-- is not updated to the order.
In this code I will have the position_size +1/-1, but change the candle after my order.
Offset=1 to view the position value.
Is there a way to keep the position updated?
//@version=4
strategy("RSI Strategy", overlay=true, process_orders_on_close=true)

length = input( 3 )
overSold = input( 40 )
overBought = input( 60 )
price = close
vrsi = rsi(price, length)
co = crossover(vrsi, overSold)
cu = crossunder(vrsi, overBought)
if (not na(vrsi))
    if (co)
        strategy.entry("RsiLE", strategy.long, comment="RsiLE")
    if (cu)
        strategy.entry("RsiSE", strategy.short, comment="RsiSE")

plot(strategy.position_size, title="position", color=color.red, linewidth=2, style=plot.style_linebr, offset=1)

A: One solution might be the argument you're using in the strategy() function. Perhaps your strategy would give you the desired output if you set process_orders_on_close to false. I would then remove the offset from the plot of position size, else set it to 0.
Another consideration is that the price variable is fetching price at candle close and calculating the entry and exit based on closing price which is being fed into the rsi function. As such, the strategy script would only detect entry and exit condition within the price action of a historical candle at the candle close. As this is the candle which triggered the trade signal, it's the candle marked on the chart as an entry or exit. The order is actually placed at candle close and the position size is then changed to reflect the new position in the new opening candle, which you might be interpreting as a delay of one bar, which it really isn't.
Real-time candles with strategies that place orders based on current price of live data are treated differently, however, and require other considerations.
If you just want to move the position size plot back one candle, then the plot strategy argument would be offset = -1, but I believe the plot for the current candle would be NA until the close of the candle.


text:
Q: How can I stop Visual Studio 2010 from auto generating controls in a template? I'm creating a UserControl which contains a ListView. I'm declaring it as follows, I've tried other ways with the ParseChildren and PersistChildren attributes.
[AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level=AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal),
Designer(typeof(ListViewItem)),
ParseChildren(false), PersistChildren(false)]
public partial class CustomListView : System.Web.UI.UserControl, IPaneControl, INamingContainer
{

Inside it I have the following code to set the ItemTemplace of the ListView
[Browsable(false),
    DefaultValue(null),
    PersistenceMode(PersistenceMode.InnerProperty),
    TemplateContainer(typeof(ListViewDataItem), BindingDirection.TwoWay)]
public virtual ITemplate ItemTemplate
{
    get { return _lvChild.ItemTemplate; }
    set { _lvChild.ItemTemplate = value; }
}

Now inside that template on the consumer of that control I'll use
<ItemTemplate><asp:HiddenField runat="server" ID="ShippingAddressID" Value='<%#Eval("AddressID") %>' /></ItemTemplate>

In Visual Studio 2008 this led to the designer file not auto-generating a HiddenField ShippingAddressID, but upon going to Visual Studio 2010 it does. How can I stop it from auto-generating it in 2010?

A: If you don't need to reference it anywhere in the code-behind couldn't you just remove the "runat=server"?


text:
Q: DataTables warning: table id=tblList - Requested unknown parameter. For more information about this error, please see http://datatables.net/tn/4 C#
[WebMethod]
public string loadLeaveRequests(int empID, int StatID, int isOwn)
{
    List<lstLeaveRequest> mylist = new List<lstLeaveRequest>();
    using (SqlConnection connection = new SqlConnection(connectionString()))
    {
        connection.Open();
        SqlCommand cmd = new SqlCommand("spLoadLeaveRequest", connection);
        cmd.Parameters.Add("@empID", SqlDbType.Int).Value = empID;
        cmd.Parameters.Add("@Stat", SqlDbType.Int).Value = StatID;
        cmd.Parameters.Add("@Own", SqlDbType.Int).Value = isOwn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandTimeout = 0;
        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            mylist.Add(new lstLeaveRequest
            {
                reqID = dr["reqID"].ToString(),
                dateFiled = dr["save_date"].ToString(),
                fname = dr["first_name"].ToString(),
                leaveType = dr["leaveAlias"].ToString(),
                dateFrom = dr["DateFrom"].ToString(),
                fromWhen = dr["FromWhen"].ToString(),
                dateTo = dr["DateTo"].ToString(),
                toWhen = dr["Towhen"].ToString(),
                reason = dr["Reason"].ToString(),
                remarks = dr["Remarks"].ToString(),
                sStatus = dr["sStatus"].ToString(),
                dateApprove = dr["approve_date"].ToString(),
                totalDays = dr["totalDays"].ToString(),
                grpID = dr["groupID"].ToString(),
            });
        }
        dr.Close();
        connection.Close();
    }
    JavaScriptSerializer jss = new JavaScriptSerializer();
    string jsn = jss.Serialize(mylist);
    return jsn;
}

JavaScript
function loadLeaveRequest(isOwn) {

    if ($('#tblList').hasClass('dataTable')) {
        $('#tblList').dataTable().fnDestroy();
        $('#tblList').removeClass('dataTable');
    }

    var xdata = "{'empID':'" + STATUS.USER_ID   //sa pgfifilter ng group kailang grpID lang ang makuha sa DB
                + "','StatID':'" + $('#cboStatus option:selected').val() //hindi na kailangan gumamit ng stored Procedure.
                + "','isOwn':'" + isOwn                                     //gumawa ng CommandType.Text sa bagong SELECT Clause
            + "'}";

    $.ajax({
        type: 'POST',
        url: '../WebService/wsLeaveRequest.asmx/loadLeaveRequests',
        dataType: 'json',
        data: xdata,
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            $('#tbodyList').empty();
            var cells = eval("(" + response.d + ")");
            for (var i = 0; i < cells.length; i++) {

                var txtFromWhen;
                var txtToWhen;
                var disable = '';

                if (cells[i].fromWhen == 2) {
                    txtFromWhen = "(AM)";
                }
                else if (cells[i].fromWhen == 3) {
                    txtFromWhen = "(PM)";
                }
                else {
                    txtFromWhen = "";
                }

                if (cells[i].toWhen == 2) {
                    txtToWhen = "(AM)";
                }
                else if (cells[i].fromWhen == 3) {
                    txtToWhen = "(PM)";
                }
                else {
                    txtToWhen = "";
                }

                var sStat; //Convertion of int to String
                if (cells[i].sStatus == 1) {
                    sStat = "Approved";
                    disable = '';
                }
                else if (cells[i].sStatus == 2) {
                    sStat = "Denied";
                    disable = '';
                }
                else if (cells[i].sStatus == 3) {
                    sStat = "Cancelled";
                    disable = 'disabled'
                }
                else {
                    sStat = "Pending";
                    disable = '';
                }

                $('#tbodyList').append('
'
                    + '<input type="checkbox" ' + disable + '>	'
                    + '' + cells[i].reqID + '	'
                    + '' + cells[i].fname + '	'
                    + '' + cells[i].leaveType + '	'
                    + '' + cells[i].dateFrom.substring(0, 10) + txtFromWhen + '~' + '
' + cells[i].dateTo.substring(0, 10) + txtToWhen + '	'
                    + '' + cells[i].totalDays + '	'
                    + '' + cells[i].reason + '	'
                    + '' + cells[i].remarks + '	'
                    + '' + cells[i].dateFiled + '	'
                    + '' + sStat + '	'
                    + '' + cells[i].dateApprove + '	'
                    + '' + cells[i].grpID+ '	'

                + '
');
            }
        },
        error: function (error) {
            console.log(error);
        },
        complete: function () {
            $('#tblList').dataTable({

                "order": [],
                "destroy": true,
                "columnDefs": [{
                    "targets": 'no-sort',
                    "orderable": false,
                }]
            }).end();
            $('#tblList').css('width', '100%');
        }
    });
}

HTML

            <input type="checkbox" id="cbAll"/>
            Request No.
            Employee
            Leave Type

            Date of Leave
            Total Days
            Reason
            Remarks
            Date Filed
            Status
            Date Approved/Cancelled

Stored Procedure
CREATE PROCEDURE [dbo].[spLoadLeaveRequest]
    @empID INT = 101,
    @Stat INT = 99,
    @Own INT = 0
AS
BEGIN

    DECLARE @SqlStr VARCHAR(1000)
    DECLARE @SqlWhere VARCHAR(500)

    SET @SqlStr = 'select a.reqID, a.save_date, b.first_name, c.leaveAlias, d.groupID, CONVERT(VARCHAR(10),a.DateFrom,101) DateFrom, a.FromWhen,
                    CONVERT(VARCHAR(10),a.DateTo,101) DateTo, a.ToWhen, a.totalDays, a.Reason,a.Remarks, a.sStatus,
                    a.approve_date, a.sStatusAdmin,a.approve_dateAdmin
                from tblLeaveRequest a
                    join userinfo b on a.Save_User = b.empID
                    join tblLeaveType c on a.typeOfLeave=c.leaveID
                    join tblGroup d on b.groupNo = d.groupID
                WHERE YEAR(a.save_date) = YEAR(GETDATE()) '

    IF (SELECT userType FROM userinfo WHERE empID = @empID) = 1
        BEGIN
            SET @SqlWhere = ' AND b.empID = ' + CAST(@empID AS VARCHAR) + ''
        END
    ELSE IF (SELECT userType FROM userinfo WHERE empID = @empID) = 2
        BEGIN
            IF  @Own = 1
                BEGIN
                    SET @SqlWhere = ' AND b.empID = ' + CAST(@empID AS VARCHAR) + ''
                END
            ELSE
                BEGIN
                    SET @SqlWhere = ' AND b.groupNo = ' + CAST((SELECT groupNo FROM userinfo WHERE empID = @empID) AS VARCHAR) + ' AND b.empID <> ' + CAST(@empID AS VARCHAR) + ''
                END
        END
    ELSE IF (SELECT userType FROM userinfo WHERE empID = @empID) = 3
        BEGIN
            IF  @Own = 1
                BEGIN
                    SET @SqlWhere = ' AND b.empID = ' + CAST(@empID AS VARCHAR) + ''
                END
            ELSE
                BEGIN
                    SET @SqlWhere = ' AND b.empID <> ' + CAST(@empID AS VARCHAR) + ''
                END
        END

    IF @Stat = 99
        BEGIN
            SET @SqlWhere = @SqlWhere
        END
    ELSE
        BEGIN
            SET @SqlWhere = @SqlWhere + ' AND a.sStatus=' + CAST(@Stat AS VARCHAR) + ''
        END

    EXEC(@SqlStr + @SqlWhere + ' ORDER BY a.reqID DESC')

END

Can someone help me with this one. My code doesn't return all the values in the data table.
can someone find the bug in my code? it has an output but not all the database fields was returned, the Last item "grpID" is not shown in the table.
i know someone out there has a capability to solve this, so please help me guys Guys..


text:
Q: Creating a loop for optimization using random numbers I'm trying to do optimization using random numbers (with specified range of values). My code is below:
x_1 = np.random.uniform(100,1200)
x_2 = np.random.uniform(-5,3)
x_3 = np.random.uniform(20,300)
x_4 = np.random.uniform(1.1,2.9)

params = { 'X1': x_1, 'X2': x_2, 'X3': x_3 , 'X4': x_4 }
states = { 'production_store': 0.60 * params['X1'], 'routing_store': 0.70 * params['X3'] } # Production store = S; Routing Store = R
rainfall = dataframe['RAINFALL']
potential_evap = dataframe['PE or ETP or Evapotrans (mm)']
simulated_flow = gr4j(rainfall, potential_evap, params, states)

True_Y = df_3 ['Flows (m3/s)']
Simulated_Y = simulated_flow
NSE = 1 - np.sum((Simulated_Y-True_Y)**2)/np.sum((True_Y-np.mean(True_Y))**2)
IA = 1 -(np.sum((True_Y-Simulated_Y)**2))/(np.sum((np.abs(Simulated_Y-np.mean(True_Y))+np.abs(True_Y-np.mean(True_Y)))**2))
LMI = 1-(np.sum(np.abs(Simulated_Y-True_Y))/(np.sum(np.abs(True_Y--np.mean(True_Y)))))

for i in range(1,len(df_3)):
    if 1 < NSE:
        print (NSE)
        if NSE > 0.5:
            print (NSE)
            if 1 < IA:
                print (IA)
                if IA > 0.5:
                    print (IA)
                    if 1 < LMI:
                        print (LMI)
                        if LMI > 0.5:
                            print (LMI)
                        else:
                            x_1 = np.random.uniform(100,1200)
                            x_2 = np.random.uniform(-5,3)
                            x_3 = np.random.uniform(20,300)
                            x_4 = np.random.uniform(1.1,2.9)
                            params = { 'X1': x_1, 'X2': x_2, 'X3': x_3 , 'X4': x_4 }
                            states = { 'production_store': 0.60 * params['X1'], 'routing_store': 0.70 * params['X3'] } # Production store = S; Routing Store = R
                            rainfall = dataframe['RAINFALL']
                            potential_evap = dataframe['PE or ETP or Evapotrans (mm)']

                            simulated_flow = gr4j(rainfall, potential_evap, params, states)
                            observed_flow = rainfall
                            True_Y = rainfall
                            Simulated_Y = simulated_flow
                            NSE = 1 - np.sum((Simulated_Y-True_Y)**2)/np.sum((True_Y-np.mean(True_Y))**2)
                            IA = 1 -(np.sum((True_Y-Simulated_Y)**2))/(np.sum((np.abs(Simulated_Y-np.mean(True_Y))+np.abs(True_Y-np.mean(True_Y)))**2))
                            LMI = 1-(np.sum(np.abs(Simulated_Y-True_Y))/(np.sum(np.abs(True_Y--np.mean(True_Y)))))
                    else:
                        x_1 = np.random.uniform(100,1200)
                        x_2 = np.random.uniform(-5,3)
                        x_3 = np.random.uniform(20,300)
                        x_4 = np.random.uniform(1.1,2.9)
                        params = { 'X1': x_1, 'X2': x_2, 'X3': x_3 , 'X4': x_4 }
                        states = { 'production_store': 0.60 * params['X1'], 'routing_store': 0.70 * params['X3'] } # Production store = S; Routing Store = R
                        rainfall = dataframe['RAINFALL']
                        potential_evap = dataframe['PE or ETP or Evapotrans (mm)']

                        simulated_flow = gr4j(rainfall, potential_evap, params, states)
                        observed_flow = rainfall
                        True_Y = rainfall
                        Simulated_Y = simulated_flow
                        NSE = 1 - np.sum((Simulated_Y-True_Y)**2)/np.sum((True_Y-np.mean(True_Y))**2)
                        IA = 1 -(np.sum((True_Y-Simulated_Y)**2))/(np.sum((np.abs(Simulated_Y-np.mean(True_Y))+np.abs(True_Y-np.mean(True_Y)))**2))
                        LMI = 1-(np.sum(np.abs(Simulated_Y-True_Y))/(np.sum(np.abs(True_Y--np.mean(True_Y)))))

                else:
                    x_1 = np.random.uniform(100,1200)
                    x_2 = np.random.uniform(-5,3)
                    x_3 = np.random.uniform(20,300)
                    x_4 = np.random.uniform(1.1,2.9)
                    params = { 'X1': x_1, 'X2': x_2, 'X3': x_3 , 'X4': x_4 }
                    states = { 'production_store': 0.60 * params['X1'], 'routing_store': 0.70 * params['X3'] } # Production store = S; Routing Store = R
                    rainfall = dataframe['RAINFALL']
                    potential_evap = dataframe['PE or ETP or Evapotrans (mm)']

                    simulated_flow = gr4j(rainfall, potential_evap, params, states)
                    observed_flow = rainfall
                    True_Y = rainfall
                    Simulated_Y = simulated_flow
                    NSE = 1 - np.sum((Simulated_Y-True_Y)**2)/np.sum((True_Y-np.mean(True_Y))**2)
                    IA = 1 -(np.sum((True_Y-Simulated_Y)**2))/(np.sum((np.abs(Simulated_Y-np.mean(True_Y))+np.abs(True_Y-np.mean(True_Y)))**2))
                    LMI = 1-(np.sum(np.abs(Simulated_Y-True_Y))/(np.sum(np.abs(True_Y--np.mean(True_Y)))))
            else:
                x_1 = np.random.uniform(100,1200)
                x_2 = np.random.uniform(-5,3)
                x_3 = np.random.uniform(20,300)
                x_4 = np.random.uniform(1.1,2.9)
                params = { 'X1': x_1, 'X2': x_2, 'X3': x_3 , 'X4': x_4 }
                states = { 'production_store': 0.60 * params['X1'], 'routing_store': 0.70 * params['X3'] } # Production store = S; Routing Store = R
                rainfall = dataframe['RAINFALL']
                potential_evap = dataframe['PE or ETP or Evapotrans (mm)']

                simulated_flow = gr4j(rainfall, potential_evap, params, states)
                observed_flow = rainfall
                True_Y = rainfall
                Simulated_Y = simulated_flow
                NSE = 1 - np.sum((Simulated_Y-True_Y)**2)/np.sum((True_Y-np.mean(True_Y))**2)
                IA = 1 -(np.sum((True_Y-Simulated_Y)**2))/(np.sum((np.abs(Simulated_Y-np.mean(True_Y))+np.abs(True_Y-np.mean(True_Y)))**2))
                LMI = 1-(np.sum(np.abs(Simulated_Y-True_Y))/(np.sum(np.abs(True_Y--np.mean(True_Y)))))
        else:
            x_1 = np.random.uniform(100,1200)
            x_2 = np.random.uniform(-5,3)
            x_3 = np.random.uniform(20,300)
            x_4 = np.random.uniform(1.1,2.9)
            params = { 'X1': x_1, 'X2': x_2, 'X3': x_3 , 'X4': x_4 }
            states = { 'production_store': 0.60 * params['X1'], 'routing_store': 0.70 * params['X3'] } # Production store = S; Routing Store = R
            rainfall = dataframe['RAINFALL']
            potential_evap = dataframe['PE or ETP or Evapotrans (mm)']

            simulated_flow = gr4j(rainfall, potential_evap, params, states)
            observed_flow = rainfall
            True_Y = rainfall
            Simulated_Y = simulated_flow
            NSE = 1 - np.sum((Simulated_Y-True_Y)**2)/np.sum((True_Y-np.mean(True_Y))**2)
            IA = 1 -(np.sum((True_Y-Simulated_Y)**2))/(np.sum((np.abs(Simulated_Y-np.mean(True_Y))+np.abs(True_Y-np.mean(True_Y)))**2))
            LMI = 1-(np.sum(np.abs(Simulated_Y-True_Y))/(np.sum(np.abs(True_Y--np.mean(True_Y)))))
    else:
        x_1 = np.random.uniform(100,1200)
        x_2 = np.random.uniform(-5,3)
        x_3 = np.random.uniform(20,300)
        x_4 = np.random.uniform(1.1,2.9)
        params = { 'X1': x_1, 'X2': x_2, 'X3': x_3 , 'X4': x_4 }
        states = { 'production_store': 0.60 * params['X1'], 'routing_store': 0.70 * params['X3'] } # Production store = S; Routing Store = R
        rainfall = dataframe['RAINFALL']
        potential_evap = dataframe['PE or ETP or Evapotrans (mm)']

        simulated_flow = gr4j(rainfall, potential_evap, params, states)
        observed_flow = rainfall
        True_Y = rainfall
        Simulated_Y = simulated_flow
        NSE = 1 - np.sum((Simulated_Y-True_Y)**2)/np.sum((True_Y-np.mean(True_Y))**2)
        IA = 1 -(np.sum((True_Y-Simulated_Y)**2))/(np.sum((np.abs(Simulated_Y-np.mean(True_Y))+np.abs(True_Y-np.mean(True_Y)))**2))
        LMI = 1-(np.sum(np.abs(Simulated_Y-True_Y))/(np.sum(np.abs(True_Y--np.mean(True_Y)))))

What i'm trying to do here is,  NSE, LMI and IA have to be from 0.5 to 1...if not, another random values of x_1, x_2, x_3 and x_4 should be generated and NSE, LMI and IA should be recomputed until it reaches 0.5 to 1 (for all NSE, LMI and IA).
I noticed that x_1, x_2, x_3 and x_4 or NSE, LMI and IA do not change (or probably not doing the loops). Anyone who would like to help me revise this code?
Apologies for using a long code, I'm still not used to functions or classes.

A: Just changing your loop structure, I think this does what you are asking for:
while True:
    x_1 = np.random.uniform(100,1200)
    x_2 = np.random.uniform(-5,3)
    x_3 = np.random.uniform(20,300)
    x_4 = np.random.uniform(1.1,2.9)

    params = { 'X1': x_1, 'X2': x_2, 'X3': x_3 , 'X4': x_4 }
    states = { 'production_store': 0.60 * params['X1'], 'routing_store': 0.70 * params['X3'] } # Production store = S; Routing Store = R
    rainfall = dataframe['RAINFALL']
    potential_evap = dataframe['PE or ETP or Evapotrans (mm)']
    simulated_flow = gr4j(rainfall, potential_evap, params, states)

    True_Y = df_3 ['Flows (m3/s)']
    Simulated_Y = simulated_flow
    NSE = 1 - np.sum((Simulated_Y-True_Y)**2)/np.sum((True_Y-np.mean(True_Y))**2)
    IA = 1 -(np.sum((True_Y-Simulated_Y)**2))/(np.sum((np.abs(Simulated_Y-np.mean(True_Y))+np.abs(True_Y-np.mean(True_Y)))**2))
    LMI = 1-(np.sum(np.abs(Simulated_Y-True_Y))/(np.sum(np.abs(True_Y--np.mean(True_Y)))))

    if 0.5 < NSE < 1 and 0.5 < LMI < 1 and 0.5 < AI < 1:
        # Conditions are met
        print(NSE, LMI, AI)
        break


text:
Q: Nginx Http Upload Progress Module: Hide X-Progress-ID in URL I'm using Nginx Http Upload Progress Module(http://wiki.nginx.org/HttpUploadProgressModule) for my video upload page(upload.php). Everything works fine, but after the video uploaded successfully, the URL display:
upload-success.php?X-Progress-ID=9040ccc12eb610ecb0362d5312e1b2fa

For some reason, i want to hide:
?X-Progress-ID=9040ccc12eb610ecb0362d5312e1b2fa

I've tried passing "X-Progress-ID" via hidden input in the form but it still display in the URL:
<input type="hidden" id="X-Progress-ID" name="X-Progress-ID" />

Any idea?

A: My way
<?php
if(isset($_POST['file_name'])) {
    header("Location: /index.php");
    exit();
}
?>


text:
Q: Wordpress wp_query() multiple post-types with specific taxonomy terms I'm trying to create a Wordpress query that includes all the standard blog posts and also the custom-post-type 'podcast' which have the taxonomy of 'series' and term 'video-blogs'. So far I've got:
$custom_query_args = array(
'post_type' => array('post', 'podcast'),
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'series',
            'term' => 'video-blogs'
        ),
        array(
            'taxonomy' => 'category',
        ),
    ),
'post_status' => 'publish',
'posts_per_page' => 4,
    'orderby' => 'date',
    'order' => 'DESC'
);

But it keeps triggering an error "Notice: Trying to get property of non-object".
If I pull the 'tax_query' out it works as expected, pulling in all posts from both post and podcast post-types but I can't find a way to make the selection I'm after.
Any ideas? Thanks in advance!

A: The issue is with 'term' => 'video-blogs' - the correct key is terms (plural) not term (singular)


text:
Q: Show dropdown menu in Angular2 z-index not working I am showing a dropdown menu when the user types in a query into the search bar. The dropdown is loaded on page load and the items are populated by an ngFor loaded in the template. My only issue is the element with a z-index of 9999 is the parent div for the dropdown, it also has a position of absolute but still shows under everything.
Here is the HTML for dropdown menu:

    <form #f="ngForm" (ngSubmit)="onSubmit(f.value)" class="form-inline row">

            <input type="text" class="form-control" required ngControl="query" (keyup)="onKey(f.value)">

        <button type="submit" class="btn btn-primary col-xs-1"></button>
    </form>

 0">

{{term[0]}}

Here is the CSS for the object:
  #search-suggestions {
    border: 1px solid $gray-lighter;
    width: 100%;
    height: auto;
    position: absolute;
    text-align: left;
    border-radius: $border-radius;
    background-color: rgba(255,255,255,.8);
    z-index: 99999;
    opacity:1;
    position: absolute;

    ul {
      padding: 2px;
      margin-bottom: 0;

      li {
        list-style: none;
        line-height: 1.5rem;
        border-radius: $border-radius;
        padding: 5px 10px;

        &:hover {
          background: $gray-lighter;
          cursor: pointer;
        }
      }
    }
  }

Here is a screenshot of what happens:


text:
Q: GWT, how to make i18n for @DefaultStringArrayValue messages I am trying to make my app run on multiple locales and I read from here
How to make static texts work in different locales. But anyone knows how to do this @DefaultStringArrayValue one work with i18n locales.
ie if I have following:
@DefaultStringArrayValue({"RDY", "Ready", "HLD", "Held", "RUN", "Run", "FIN", "Finished", "MSG", "Message", "END", "End", "ERR", "Error"})
String[] jobStatuses();

How to create an entry in property file for this?
Thanks.

A: Doesn't the Javadoc say it all?

Note that in the corresponding properties/etc file, commas are used to separate elements of the array unless they are preceded with a backslash.

jobStatuses=RDY,Ready,HLD,Held,RUN,Run,FIN,Finished,MSG,Message,END,End,ERR,Error


text:
Q: Firebase + Node: Updating two refs results in 304 errors What I have is a function that resets a ref when called. It works when updating only one ref.
This is the code for that part of the function:
if (streakVal !== 0) {
   //reset
   const uid = item.child('uid').val();
   ref.child(uid).update({ streak: 0 }).catch(err => {
      res.status(500).send(err);
   });
}

I also want to update another ref in a different part of the database. I've included it in the same function, as the only difference is the ref location. The part then looks like this:
if (streakVal !== 0) {
    //reset
    const uid = item.child('uid').val();

    ref.child(uid).update({ streak: 0 }).then(() => {
        boardRef.child(uid).update({ score: 0 }).catch(err => {
           res.status(500).send(err);
        });
    }).catch(err => {
       res.status(500).send(err);
    });
}

The first snippet works. However, the second results in the error Function execution took 800 ms, finished with status code: 304 I'm wondering why this is and how to fix it. Maybe I'm not structuring it correctly as I'm new to Node. I'm sure that's the correct path to both refs. Here is the full function:
export const resetStreak = functions.https.onRequest((req, res) => {
  const ref = db.ref('users');
  const boardRef = db.ref('streakLeaderboard');

  ref.once('value').then(snap => {
    snap.forEach(item => {
        const streakVal = item.child('streak').val();
        const lastQuestTimestamp = item.child('lastQuest').val();

        const today = new Date();
        const d = new Date(lastQuestTimestamp);

        if (sameDay(today, d) === false) {
          if (streakVal !== 0) {
           //reset
           const uid = item.child('uid').val();

           ref.child(uid).update({ streak: 0 }).then(() => {
            boardRef.child(uid).update({ score: 0 }).catch(err => {
              res.status(500).send(err);
            });
           }).catch(err => {
             res.status(500).send(err);
           });
          }
        }
    })

  }).catch(err => {
    res.status(500).send(err);
  });

Thank you!

A: You should return your Promise in your HTTPS functions (docs). Your code should become:
export const resetStreak = functions.https.onRequest((req, res) => {
  const ref = db.ref('users');
  const boardRef = db.ref('streakLeaderboard');

  return ref.once('value').then(snap => {
    const promises = []
    snap.forEach(item => {
      const streakVal = item.child('streak').val();
      const lastQuestTimestamp = item.child('lastQuest').val();

      const today = new Date();
      const d = new Date(lastQuestTimestamp);

      if (sameDay(today, d) === false) {
        if (streakVal !== 0) {
         //reset
         const uid = item.child('uid').val();

         promises.push(ref.child(uid).update({ streak: 0 }).then(() => {
           return boardRef.child(uid).update({ score: 0 });
         }));
        }
      }
    })
    return Promise.all(promises);
  }).then(() => {
    res.sendStatus(200);
  }).catch(err => {
    res.status(500).send(err);
  });


text: Q: Android Studio is not capturing error log when errors/exceptions thrown from coroutines/scope funtions only for Xiaomi device I have tried multiple things but still not able to find the issue why Logcat is not capturing/showing errors/exceptions for xiaomi device. Now the problem is, to debug the issue I need to run application code on any other device then logcat shows the correct error then only I am able to fix issue.


text:
Q: collection of objects to bytes format and then vice versa in java I have a collection of objects which i need to store in byte format and then afterwards i have to convert the data which in bytes back into collection of objects.I need the answer in java.
For eg I have an array of objects(any type) then i have to convert this array to byte array in java and then vice versa.
Please if possible suggest me the collection to use and the methods which support it.

A: Assuming that Foo implements Serializable, just do
List<Foo> list = createItSomehow();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);

try {
    oos.writeObject(list);
} finally {
    oos.close();
}

byte[] bytes = baos.toByteArray();
// ...

And the other way round:
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
List<Foo> list = null;

try {
    list = (List<Foo>) ois.readObject();
} finally {
    ois.close();
}

// ...

Instead of ByteArrayOutputStream and ByteArrayInputStream you can of course also supply FileOutputStream and FileInputStream respectively to write/read it to/from file.
See also:

*

*The Java Tutorials - Essential Classes - Basic I/O - Object Streams


text:
Q: Is $f_1(X,c)=\mathbb{P} \left(\frac{X}{c} > \tau \right)$ is an increasing function of $c$? Let $f(X,c)= f_{1}(X,c) \, \mathcal{A}_1(X,c) + f_{2}(X,c) \, \mathcal{A}_ {2}(X,c)$ with
$$
f_{1}=\mathbb{P} \left(\frac{X}{c} > \tau \right),
\quad
f_{2}=\mathbb{P} \left( c X > \tau \right),
\quad
\mathcal{A}_1 =\mathbb{P} \left(  \frac{X}{c} > 1  \right),
\quad \text{and} \quad
\mathcal{A}_2 = 1-\mathcal{A}_1.
$$
where $X$ is a random variable and $c>0$ is a constant.
Is $f(X,c)$ is an increasing function of $c$? Can we tell without computing the probabilities?

Note This question is a shortened version of this.


text:
Q: How to add elements in Vec like a binary tree's leaf nodes? assuming n = 2^x elements in Vec,
adding elements in Vec using
vec.reduce(_ +& _)

will end up with element width = w + 2^x - 1
if adding them for every two elements like a tree, the width will be w + x
seems
vec.par.reduce(_ +& _)

works for 4 elements, but not for 8 or 16.
Any workaround?

A: I suggest you take a look at the experimental Interval type in chisel3. There's some limited documentation here. Intervals were designed for just this situation. You shouldn't even have to change everything, just map the elements of your Vec to Intervals and then reduce them.

A: chisel3.Vec has a reduceTree method that will do what you want:
class Example extends MultiIOModule {
  val in = IO(Input(Vec(8, UInt(8.W))))
  val out = IO(Output(UInt())) // Infers width to be 11

  out := in.reduceTree(_ +& _)
}

Scastie link: https://scastie.scala-lang.org/rhm4je13T0ykEtRS7P7mfQ
Also see the Vec API docs: https://www.chisel-lang.org/api/latest/chisel3/Vec.html


text:
Q: How to parse variable length command line arguments with regex? I have a large number of files that each contain a bash command with a variable amount of parameters. I need to replace these with a corresponding API call.
Example bash command in file (Note: number of '-p' arguments vary, some have none):
./some_script.sh http://some.server.com -p a=value -p b=value -p c=value

Example corresponding API call
http://some.server.com/api/some/endpoint?a=value&b=value&c=value

My issue is I can't seem to group each parameter, given that the number of parameters is variable.
Basic regex (this will match above example, but only group first parameter):
.\/some_script.sh\s([\w\/:\.]*)(\s-\w\s[\w=]*)

And I tried:
.\/some_script.sh\s([\w\/:\.]*)(\s-\w\s[\w=]*)*

However, this seems to only group the last parameter.
(tested with regex101)
Ideally, I would like this regex to be able to group an indefinite number of arguments in these files so that I can easily rebuild the command as an API call.
If more detail is required please let me know, any suggestions are welcome.

A: You need to use the \G anchor
/(?|\.\/some_script\.sh\s([\w\/:.]*)|(?!^)\G())\s-(\w)\s([\w=]*)/

https://regex101.com/r/0151qC/1
Expanded
 (?|                           # Branch reset
      \. /some_script \. sh         # First, find the script name
      \s
      ( [\w/:.]* )                  # (1), url

   |                              # or,
      (?! ^ )
      \G                            # Start where last left off
      ( )                           # (1), blank url

 )

 \s -
 ( \w )                        # (2), - 'p'
 \s
 ( [\w=]* )                    # (3), 'a=value'

A: Here, maybe we could find another approach, and step by step collect our desired data from our inputs. We would then likely start with an expression similar to:
.+\.sh.+?(https?:\/\/[^\s]*)|\s+-[a-z]+\s+([\w=]+)

which has our link in here:
(https?:\/\/[^\s]*)

and our variables in:
([\w=]+)

altered with a logical OR.
We can also modify and add other boundaries or reduce our boundaries, if that might be desired.
DEMO
Test
This snippet just shows that how the capturing groups work:

const regex = /.+\.sh.+?(https?:\/\/[^\s]*)|\s+-[a-z]+\s+([\w=]+)/gm;
const str = `./some_script.sh http://some.server.com -p a=value -p b=value -p c=value
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx Circuit
jex.im visualizes regular expressions:


text:
Q: TestMain multiple definitions found If I define, two tests, each with its own TestMain method, go test errors: "multiple definitions found of TestMain".
I can understand and was expecting this behaviour actually, because, there should not be more than one TestMain in the same package. However, I don't know what to do now. Each test suite has its own needs. I need to create distinct TestMains to setup the tests, of course, without renaming my packages.
I could do that easily in other languages with setup methods like before, after, which is unique to a test class.
I'll probably go and use testify's suites. Sad that this is not supported in stdlib.
Do you have any suggestions?

A: You can use M.Run.
func TestMain(m *testing.M) {
    setup()
    code := m.Run()
    close()
    os.Exit(code)
}

See subtest for additional info.
More detailed example:
package main

import (
    "testing"
)

func setup()    {}
func teardown() {}

func setup2()    {}
func teardown2() {}

func TestMain(m *testing.M) {
    var wrappers = []struct {
        Setup    func()
        Teardown func()
    }{
        {
            Setup:    setup,
            Teardown: teardown,
        },
        {
            Setup:    setup2,
            Teardown: teardown2,
        },
    }

    for _, w := range wrappers {
        w.Setup()
        code := m.Run()
        w.Teardown()

        if code != 0 {
            panic("code insn't null")
        }
    }
}


text:
Q: Acceleration goes to zero when opposite direction is quickly pressed in succession to last one. This is my code in my Hero class (the one the player controls) that runs every update:
self.speedx += ((self.dirx * self.maxspeed) - self.speedx) * self.acc
self.x+=self.speedx
self.speedy += ((self.diry * self.maxspeed) - self.speedy) * self.acc
self.y+=self.speedy

This is my event getterizer code:
if event.type == KEYUP:
            if event.key == K_RIGHT:
                active.dirx=0
            if event.key == K_LEFT:
                active.dirx=0
            if event.key == K_UP:
                active.diry=0
            if event.key == K_DOWN:
                active.diry=0
        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                active.dirx=1
            if event.key == K_LEFT:
                active.dirx=-1
            if event.key == K_UP:
                active.diry=-1
            if event.key == K_DOWN:
                active.diry=1

The problem is that when I go right for awhile (or up) and then let go and quickly press the opposite direction (left, down) my acceleration for that direction goes to zero. This would not be much of a problem if the game did not involve a lot of reflex and I can't have players crapping out in the middle of a fight.
Any solutions? If I was not clear enough just say.

A: It may be that the opposite KEYDOWN event is being received before the KEYUP.  I would guard the KEUP event handling to make sure the opposite KEYDOWN has not occurred.  Something like:
if event.key == K_RIGHT and active.dirx == 1:
      active.dirx=0

...


text:
Q: Split an array-object into multiple array objects I'm trying to split an array-object that has an array as attribute into multiple objects, each one with one element of the previous array. I'm working in a js class The idea is coded below:
class Example {

  async ArraySplitter(){

    this.Array=[
      { name:something,
        features:[feature1,feature2,...]
      }]

      //Which becomes:

    this.Array=[
      { name:something,
        features:feature1
      },
      { name:something,
        features:feature2
      }''
      ...
    ]
  }
}

A: We can use a reduce over our original array.
Inside that reduce we will map the sub array and emit the desired object.

const arr = [{
  name: "test1",
  values: ["t1", "t2"]
},
{
  name: "test2",
  values: ["t3", "t4"]
}];

const flat = arr.reduce((a, {name, values}) => {
   a.push(
     values.map(
       value => ({ name, value })
    )
  );
  return a;
}, []).flatMap(x => x);

console.log(`Flat: ${JSON.stringify(flat)}`);

A: Assuming you are trying to do a 1-n mapping. It can be done via looping, or via mapping.
Here is a sample code to help with (believe it is self-explanatory):

// Entity representing an element, with its own features
class Element {
  constructor(name, features) {
    this.name = name;
    this.features = features;
  }

  get featureMap() {

    // Option 1: Looping
    const map = [];
    this.features.forEach((feature) => {
      map.push({
        name: this.name,
        feature: feature
      });
    });
    return map;

    // Option 2: Map
    return this.features.map(feature => {
      return {
        name: this.name,
        feature: feature
      }
    });
  }
}

// Test 1: Get element mapped to its features
const candleElement = new Element("Candle", ["Small", "Medium", "Large"]);
console.log(candleElement.featureMap);

// Test 2: Get element mapped to its features
const roseElement = new Element("Rose", ["Red", "Green"]);
console.log(roseElement.featureMap);


text:
Q: Ajax won't call controller method mvc I am trying to do inline editing by cell, not by row, upon a double click. This much works but it won't update the record- the "SaveCustomer" call to controller isn't made. What is it that I'm doing wrong?
here is my index view file (part of it, the rest is irrelevant)
   @foreach (var item in Model.Drivers)
        {

                     @Html.DisplayFor(modelItem => item.ID)

                    @Html.DisplayFor(modelItem => item.LastName)

                    @Html.DisplayFor(modelItem => item.FirstName)

                  @if (item.Seniority != null) {@Convert.ToDateTime(item.Seniority).ToShortDateString()}

                 //more go here

Then here is the javascript file- sorry for the formatting, happens everytime I copy&paste
 $("td").dblclick(function () {
if (!$(this).hasClass("edit")) {
    var value = jQuery.trim($(this).html());
    $(this).html("<input id=\"txtEdit\" type=\"text\" class=\"textbox\" value=\"" + value + "\" onblur=\"SaveValue(this, '" + value + "')\" onfocus=\"PutCursorAtEnd(this)\" />");
    $(this).addClass("edit");
    $("#txtEdit").focus();
}
});

 function PutCursorAtEnd(obj) {
if (obj.value == obj.defaultValue) {
    $(obj).putCursorAtEnd(obj.length);
}
}

function SaveValue(obj, oldValue) {
var value = $(obj).val();
$(obj).parent().removeClass("edit");
if (value != oldValue) {
    var property = $(obj).parent().attr("id");
    var id = $(obj).parent().parent().attr("id");

    $.ajax({
        type: "POST",
        url: '@Url.Action("SaveCustomer", "save")',
        data: { ID: id, Property: property, Value: value },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: SaveCustomer_Success,
        error: Error
    });
 }
else {
    $(obj).parent().html(oldValue);
}
}

function SaveCustomer_Success(data, status) {
$(data.d.ID).parent().html(data.d.NewValue);
}

and lastly here is the controller method
    public object SaveCustomer(int ID, string Property, string Value)
    {
        Driver driver = unitOfWork.DriverRepository.GetByID(ID);
        switch(Property) {
            case "id":
                driver.ID = Convert.ToInt32(Value);
                break;
            case "firstName":
                driver.FirstName = Value;
                break;
            case "lastName":
                driver.LastName = Value;
                break;
            case "seniority":
                driver.Seniority = Convert.ToDateTime(Value);
                break;
        }
        unitOfWork.DriverRepository.Update(driver);
        unitOfWork.Save();

        return new
        {
            ID = ID,
            NewValue = Value
        };
    }

Much help appreciated, thanks!

A: Remove following line from your ajax options because you are not sending json type data.
contentType: "application/json; charset=utf-8"

Since you are sending a POST request you have to add HttpPost attribute to controller. And also you are expecting json result, so your controller should be like below.
[HttpPost]
public JsonResult SaveCustomer(int ID, string Property, string Value)
{
    /// ...
    return Json(new { ID = 1, NewValue = 1 }, JsonRequestBehavior.AllowGet);
}

A: Try removing data, contentType and dataType from Ajax call and change the url to:
url: 'save/SaveCustomer?ID=' + id + '&Property=' + property + '&Value=' + value,

put a break point in the controller to see if the call hits it.  There is no reason why it will not.
Use Chrome browser and open JavaScript console.  You will see why it doesn't work, if it doesn't work after this change.


text:
Q: D2R auto map discovering algorithm I'm trying (for technical challenge) to create an autonomous bot able to play D2R alone.
Of course, it would be an offline bot, just used for my personnal satisfaction ;)
I manage to overcome most of my first technical challenges :

*

*Screen detection / Menu and game creation handling (screen patterns)

*Monster detection : Deep learning based algorithm is working really fine (even without GPU training, first attempts are great !)

*Item and fixed spots detection : Handled by screen pattern recognition

But there is another issue that I don't managed to get rid off :
how to manage the movement of my character ? A* and so on won't be working because in D2R there are no nodes and links or anything like that. And moreover We don't know before discovering the maps where is the output of the map.
Checking the minimap i can get with pattern recognition the entrance/output of a level but I don't see how I could handle the movements !
Here some example of screen in this one the entrance is in pink on minimap, but we cannot see the output of this level, it has to been discovered:

And this one is already full discovered:

I would like my bot to be a pixel bot and using only screen information. I don't want to inject into memory of anything like this (if possible).
Anyone with an idea of algorithm or technicals possibilities how I could make that?
I thought of map reconstruction while discovering it but how to get walls information (another deep learning model ? seems not the best, perhaps trying to isolate the minimap information?)
Thanks really all for your ideas and help !
P.S. : Working with python, OpenCV and imageai


text:
Q: WPF ComboBox SelectedItem property is not working I have this combo box:
<DataGridTemplateColumn SortMemberPath="Mod.Code" Header="Mod" Width="100*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox ItemsSource="{Binding Mode=OneWay, Source={StaticResource modViewSource}}" SelectedItem="{Binding Mod}" IsSynchronizedWithCurrentItem="True"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Here is the data source:
<CollectionViewSource x:Key="modViewSource" d:DesignSource="{d:DesignInstance {x:Type AutoPBW:Mod}, CreateList=True}">
    <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="Code"/>
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

And here is the model property:
/// <summary>
/// The mod used for this game.
/// </summary>
public Mod Mod { get; set; }

My problem is that the SelectedItem binding is not working - I always get the first item in the list, instead of the Mod object that belongs to the game data bound to the item in the DataGrid. How can I display the correct Mod?
edit: here is Mod.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace AutoPBW
{
    /// <summary>
    /// A game mod, or the stock game.
    /// </summary>
    public class Mod
    {
        public Mod(string code, string engineCode)
        {
            Code = code;
            Engine = Engine.Find(engineCode);
            IsUnknown = true;
        }

        /// <summary>
        /// A unique code name for this mod. Used in PBW URLs.
        /// </summary>
        public string Code { get; set; }

        public override string ToString()
        {
            return Code;
        }

        /// <summary>
        /// The game engine that this mod uses.
        /// </summary>
        public Engine Engine { get; set; }

        /// <summary>
        /// The path to the mod's root directory, relative to the engine's root directory.
        /// </summary>
        public string Path { get; set; }

        /// <summary>
        /// The path to the mod's savegame directory, relative to the engine's root directory.
        /// </summary>
        public string SavePath { get; set; }

        /// <summary>
        /// The path to the mod's empire setup directory, relative to the engine's root directory.
        /// </summary>
        public string EmpirePath { get; set; }

        /// <summary>
        /// Is this an unknown mod?
        /// </summary>
        public bool IsUnknown { get; set; }

        public static Mod Find(string code, string defaultEngineCode = null)
        {
            if (code == null)
                return null;
            var old = Config.Instance.Mods.SingleOrDefault(x => x.Code == code);
            Mod nu;
            if (old == null || old.IsUnknown)
            {
                // load from default if present
                var d = Config.Default.Mods.SingleOrDefault(x => x.Code == code);
                if (d != null)
                    nu = d;
                else
                    nu = new Mod(code, defaultEngineCode); // let the user know what the code is so he can find the mod
            }
            else
                nu = old;
            if (nu != old)
            {
                if (old != null)
                    Config.Instance.Mods.Remove(old);
                Config.Instance.Mods.Add(nu);
            }
            return nu;
        }
    }
}

A: You should implement INotifyPropertyChanged in your ViewModel to make sure SelectedItem Mod is updated in UI thread


text:
Q: How to overcome difference bewteen jQuery hide() and jQuery UI hide() I am writing a very simple slideshow and I was using the "regular" hide() like so:
jQuery("#featured li:nth-child(1)").hide('slow');

This not only hides the li, but it also slowely moves the other li's into position, which is great.
But, now I wanted to use a nicer effect and have changed it to:
jQuery("#featured li:nth-child(1)").hide('slide', 'slow');

This slides the li out of view with a nice effect, but now the remaining li's no longer move into position with it, but they "wait" until the effect is done and then they suddenly "jump" into place.
How do I fix this?

A: You could use a different effect like this:
$("#featured li:nth-child(1)").hide('fold','slow');

I think it depends on your layout because slides goes from right to left so if you have another element below it it will just "pop" in.
Look at the fiddle http://jsfiddle.net/F8XcW/


text:
Q: Is it possible to open ViewController from background mode or when app is killed? I am trying to open ViewController on received push notification. I am doing it like this
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType) {
    guard let aps = payload.dictionaryPayload[AnyHashable("aps")] as? NSDictionary else {
        return
    }
    startCustomCallController(apnData: app)
}

func startCustomCallController(apnData: NSDictionary) {
    let storyBord = UIStoryboard(name: "PrivateUi", bundle: nil)
    guard let controller = storyBord.instantiateViewController(withIdentifier: "NewIncomingCallViewController") as? NewIncomingCallViewController else{
        print("Error instantiating view controller")
        return
    }
    controller.apnData = apnData
    guard let appdelegate = UIApplication.shared.delegate as? AppDelegate else {
        print("appdelegate is missing")
        return
    }
    UIView.transition(with: appdelegate.window!, duration: 0.5, options: .transitionCrossDissolve, animations: {
        appdelegate.window!.rootViewController = controller
    }, completion: nil)
}

It is working when app is open (In Foreground) But not working when is in background or killed.
Is it not possible or do I need to make some changes?

A: It is not possible to start ViewController from background model I think. If you want to open viewcontroller for call related task batter to use callkit
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType) {
    // report new incoming call
}```