text:
Q: listing contents of a jar file package soundcliptest;
// development environment(NetBeans 8.0)
//
// NetBeansProjects
//     SoundClipTest
//         Source Packages
//             resources
//                ding.wav
//             soundcliptest
//                SoundClipTest.java
//

// unZipped jar file
//
// SoundClipTest
//    META-INF
//    resourses
//        ding.wav
//    soudcliptest
//        SoundClipTest.class
//

I'm still learning how to use this tool, folks.  I can't seem to get the imports where they belong.
I need to know how to look into the jar file from the code.  The File methods can't  crack it.  There must be some way of finding the contents of a resource 'directory'. What I want to do is make a menu of the sound files under /resources/. I can make it work in the development environment,, but not from the jar file. Maybe some 'zip' methods? But I haven't found them.  Thanks in advance.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;

public class SoundClipTest extends JFrame {

    JTextPane myPane;
    String title;
    String showIt;

    public SoundClipTest() {

        // get something to write on
        this.myPane = new JTextPane();
        this.myPane.setPreferredSize(new Dimension(700, 100));
        this.myPane.setBorder(new BevelBorder(BevelBorder.LOWERED));

        try {
            // Open an audio input stream.
            URL dingUrl = getClass().getResource("/resources/ding.wav");

            // show the path we got
            String path = dingUrl.getPath();

            //trim 'ding.wav' from file path to get a directory path
            String dirPath = path.substring(0, path.length()-"ding.wav".length());

            // now get a Url for the dir from getResource and show THAT path
            URL dirUrl = getClass().getResource("/resources/");
            String urlPath = dirUrl.getPath();

            // the dirUrl path is just like the trimmed 'ding' file path
            // so use  urlPath to get a file object for the directory
            try {
                File f = new File(urlPath);  //works fine in dev environment
                String filePath = f.getPath();  // but not from jar file
                title = f.list()[0]; // from jar, null pointer exception here

                // whan things go right (HA HA) we display this
                showIt = ("                >>>>> IT WORKED!! <<<<<!"
                        + "\n path to file:        "+ path
                        + "\n path to dir:        " + dirPath
                        + "\n path from URL: " +  urlPath
                        + "\n path from file:  "+ filePath + "\n " + title);

            } catch (Exception e) {
                // you get this on display when executing the jar file
                showIt = ("          PHOOEY"
                        + "\n the ding  " + path
                        + "\n trimmed path " + dirPath
                        + "\n the URL path " + urlPath
                        + "\n could not create a File object from path");

                 // the stack trace shows up only if you run from the terminal
               e.printStackTrace();
            }

            // We get a nice little 'ding', anyway
            AudioInputStream ais = AudioSystem.getAudioInputStream(dingUrl);
            Clip clip = AudioSystem.getClip();
            clip.open(ais);
            clip.start();

            //but nuttin else good -  show the disapointing results
            myPane.setText(showIt);

        } catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            System.out.println("Ouch!!! Damn, that hurt!");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SoundClipTest me = new SoundClipTest();
        JFrame frame = new JFrame("Sound Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(me.myPane, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }
}

A: OK, not a full answer but since that part is not very well documented (Oracle's page on it is obsolete), here is how to use a ZIP FileSystem over a jar file:
final Path pathToJar = Paths.get(...).toRealPath();
final String jarURL = "jar:file:" + pathToJar;
final Map<String, String> env = new HashMap<>();

final FileSystem jarfs = FileSystems.newFileSystem(URI.create(jarURL), env);

final Path rootPath = jarfs.getPath("/resources");

Then you can use Files.newDirectoryStream() over rootPath to get a list of files inside a "directory" within the jar. If you want to list recursively, use Files.walkFileTree() and write your own FileVisitor (most of the time, extending SimpleFileVisitor is enough).
NOTE: a FileSystem implements Closeable; you should ensure to .close() it once you're done with it. And so does a DirectoryStream for that matter.

A: Caveat Emptor
This is assuming that you have not fiddled with classloaders, this will work with the URLClassLoader but is an implementation detail of that class, not part of the public API.
If you load a classpath directory resource then you will get a line for each resource in that directory.
Lets assume you have this structure:
/resources
    /test1.txt
    /test2.txt

If we do the following:
try (final Scanner scanner = new Scanner(getClass().getResourceAsStream("/resources"))) {
    while (scanner.hasNextLine()) {
        final String line = scanner.nextLine();
        System.out.println(line);
    }
}

This will output:
test1.txt
test2.txt

So you can use this to return a list of names of files:
List<String> readClassPath(final String root) {
    final List<String> resources = new LinkedList<>();
    try (final Scanner scanner = new Scanner(getClass().getResourceAsStream(root))) {
        while (scanner.hasNextLine()) {
            final String line = scanner.nextLine();
            System.out.println(line);
            resources.add(root + "/" + line);
        }
    }
    return resources;
}

This returns:
[/resources/test1.txt, /resources/test2.txt]


text:
Q: Get value attribute from an li element I have an unordered list with li elements in it. When I click on that particular item in the list, I want to extract the value of that li item and use it. In the example below I would want to extract the value "9".
How can I do this in jQuery?

        Category 1

A: Firstly, there is no value attribute available on an li element, and adding non-standard attributes will mean that your page is invalid. Instead, use data-* attributes.
You can then hook to the click event of the a element and get that data attribute from its parent li, like this:

$('li a').click(function(e) {
  e.preventDefault();
  var value = $(this).closest('li').data('value'); // = 9
  console.log(value);

  // do something with the value here...
});

       Category 1

       Category 2

A: li doesn't have value attribute. use data-value instead like below:

Category 1

Then use:
$('li.liEllipsis').click(function(e) {
    e.preventDefault();
    var value = $(this).attr('data-value');
});

A: Do not use value on
. It is not valid! Instead you can use data-value or something like that. Use this way:
$("li").click(function () {
  alert($(this).attr("value"));
});

Snippet

$(function () {
  $("li").click(function () {
    alert($(this).attr("value"));
  });
});

    Category 1

A: Little late but this can be helpful to few.
li tag does not have value attribute sewn already, but still you can use dataset feature provided. For example:

        Category 1

To extract li's value:
$('li').click(function(){
    alert($(this).dataset.value);
})

I have been using this in vanilla javascript, should work fine for jquery as well.

A: You can write a click handler for li element and then get its attribute value. also value is not valid attribute for li elements. however HTML5 allows you to  use custom attribute that starts with data-. you can use value attribute like data-value.

     Category 1

and then get them using .data():
$('li').click(function(){
    alert($(this).data('value'));
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding ItemAdding event I am trying to understand as to when this ItemAdding event fires.
Does it fire when user has clicked new document button to upload a document library?
Or
Does it fire when user uploads document library, then a form is shown where he enters Title etc., so before he presses Save button, this event is fired?
My aim of asking this question is to do some form validation after user presses Save button but before item is added. If there is some error in validation then I want to display error message on screen.

A: ItemAdding event is fired when a file is uploaded to the library. ItemUpdating is fired when custom properties in the form are saved.

A: -ing events e.g Item Adding or Updating are the most suitable events for validation.
In your case Item Adding is the event you are looking for.
In addition have in mind that this event is synchronous.


text:
Q: How to handle mm/dd/yyyy and dd-mm-yyyy in one character vector in R Studio I have a panel data set that has a column with date entries, though they are in class "character", with some as mm/dd/yyyy, and others with dd-mm-yyy. I want to format these into a Date vector, so that I can subset the data according to a cutoff date. However, as.date does not work, since the formatting of the entries varies.
df$OPdate <- as.Date(OPdate, format = "%Y-%M-%D")
dfnew = subset(df,OPdate < "2021/3/29")
df_age14 = subset(dfnew, age > 13)
list14 = unique(df_age14$postID)
finaldf = subset(df, postID %in% list14)

This is the code I am trying to run once the dates are formatted correctly. Any suggestions?
Thanks in advance

A: If you're sure you only have the two formats you can try as.Date with tryFormats in sapply because tryFormats is not vectorized. strftime returns the desired character string.Using toy data.
dates
[1] "02/23/2021" "11/03/2021" "22-03-2021" "23-04-2020" "29-06-2021"

sapply(dates, function(x)
  strftime(as.Date(x, tryFormats=c("%d-%m-%Y","%m/%d/%Y"))))
  02/23/2021   11/03/2021   22-03-2021   23-04-2020   29-06-2021
"2021-02-23" "2021-11-03" "2021-03-22" "2020-04-23" "2021-06-29"

Working with the data
dates_new <- sapply(dates, function(x)
  strftime(as.Date(x, tryFormats=c("%d-%m-%Y","%m/%d/%Y"))))

dates_new > "2021-04-14"
02/23/2021 11/03/2021 22-03-2021 23-04-2020 29-06-2021
     FALSE       TRUE      FALSE      FALSE       TRUE

# or
as.Date(dates_new) - 23
[1] "2021-01-31" "2021-10-11" "2021-02-27" "2020-03-31" "2021-06-06"

A: you can use the package "lubridate" from tidyverse to change the format of date in a specific one: i.e. mdy("4/1/17") will output "2017-04-01", dmy("14/10/2021")
will output "2021-10-14".


text:
Q: Pandas coarsen categorical variable Let's say I have a categorical variable with the following values, given by calling unique() on the column in the dataframe:
Categories (7, object): [0-2, 6-8, 9-11, 3-5, 15-17, 12-14, 24-26]
and that I have the following occurrences for each of these categories given by calling value_counts():
0-2      209
3-5       34
6-8       17
9-11       7
15-17      6
12-14      3
24-26      1
what would be a good way to coarsen/compress these categories into two new categories "high" and "low"?

A: This is using pd.cut with the right value of the range, and cut them into two , also you can using qcut to get different cut result
groupkey=pd.cut(s.index.str.split('-').str[-1].astype(int),2,labels=['low','high'])
s.groupby(groupkey).sum()
low     270
high      7
Name: v, dtype: int64


text:
Q: Spring data elasticsearch query on multiple indices I have multiple indices for every day in elasticsearch and I am using ElasticsearchRepository to query my documents. Documents definition:
@Getter
@Setter
@Document(indexName = "fraud-hub-digital-transactions-#{T(java.time.LocalDate).now().toString()}", createIndex = false)
@TypeAlias("fraud-hub-digital-transactions")
public class FraudDigitalTransactions {

    @Id
    @Field(name = "transaction_key",type = FieldType.Long)
    private Long transactionId;

    @Field(name = "client_no",type = FieldType.Integer)
    private Integer clientNo;
}

My index will create dynamically for every day with this definition
@Document(indexName = "fraud-hub-digital-transactions-#{T(java.time.LocalDate).now().toString()}"

My Repository definition:
@Repository
public interface FraudDigitalTransactionsRepository extends ElasticsearchRepository<FraudDigitalTransactions,String> {
    List<FraudDigitalTransactions> findByClientNo(Integer clientNo);
}

When I query by client no just returning current day values.
@Test
public void testFindByClientNo() {
    List<FraudDigitalTransactions> fraudDigitalTransactions = fraudDigitalTransactionsRepository.findByClientNo(88019237);
    Assert.assertNotEquals(fraudDigitalTransactions.size(),0);
}

Test failed. Current day values returned not searched all indices.
Probably Spring data searching a document in current day indexes. Is there any way with spring data to search all indexes? I can do it with elasticsearch high-level client but I want to do with spring data features

A: You will need to search with a wildcard or alias and when writing use the index name produced by the bean.
I recently wrote a blog post how to do this with Spring Data Elasticsearch 4.1 using index templates.


text:
Q: how to watch Internet Explorer local cookies I want to check whether my session cookies are secure or not in IE11. I am able to check it in chrome and Mozilla but unable to find anything in IE11.
chrome--> DevTools>Application>Storage>Cookies
Mozilla--> DevTools>Storage>Cookies
Edge--> DevTools>Debugger>Cookies

Note: I don't want to check cookie request header inside network tab in developer tools
thanks
Edit: I think I found the answer.
IE 11 cookies in Developer tools

A: I found out that Microsoft has removed cookie view feature from IE11.
IE 11 cookies in Developer tools


text:
Q: mongodb update causes extremly slow reads I am relatively new to mongoDB.
I set up a shard mongo cluster with 2 Replica Sets; each set in a shard. -> 4 mongo deamons
The deamons are distributed on 2 WIN server with 8gb ram each.
I have a Test Collection with 10 mio documents (~ 600bytes / doc) and using the c# driver to connect to the mongos (primaryPreferred)
Now if i run some thousands single read-queries on the shard key I can see that mongo eats up more and more memory and stalls at around 7,2GB. Almost no more page faults and the queries are extremly fast. Good!
The same with more complex queries on different document properties
(Combined Index for those queries exists)
BUT
If I execute just a couple of update queries, I got a huge drop in memory usage... like mongo frees up 3GB of RAM just in no time and the so fast read queries are getting very slow.
It gets worse if i launch like 500k upserts (Save) in a row.
A complex query that was taking like 2sec to run takes now 22minutes.
I get the same behavior for Count-Queries with the same query parameters.
Is that a rather normal mongoDB behaviour or is there something that I missed to set up?
--- UPDATE @hwatkins

*

*MongoDB version: 2.2.2

*1 document scanned for a single upsert

*I Have quite high disk activity during the bulk-upsert

explain() for a complex count- query before upsert
Count Explain: { "clusteredType" : "ParallelSort", "shards" : { "set1/xxxx:1234,yyyy:1234" : [{ "cursor" : "BtreeCursor AC", "isMultiKey" : false, "n" : 20799, "nscannedObjects" : 292741, "nscanned" : 292741, "nscannedObjectsAllPlans" : 294290, "nscannedAllPlans" : 294290, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 2, "nChunkSkips" : 0, "millis" : 2382, "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] }, "allPlans" : [{ "cursor" : "BtreeCursor AC", "n" : 20795, "nscannedObjects" : 292741, "nscanned" : 292741, "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] } }, { "cursor" : "BasicCursor", "n" : 4, "nscannedObjects" : 1549, "nscanned" : 1549, "indexBounds" : { } }], "oldPlan" : { "cursor" : "BtreeCursor AC", "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] } }, "server" : "xxxx:1234" }], "set2/xxxx:56789,yyyy:56789" : [{ "cursor" : "BtreeCursor AC", "isMultiKey" : false, "n" : 7000, "nscannedObjects" : 97692, "nscanned" : 97692, "nscannedObjectsAllPlans" : 98941, "nscannedAllPlans" : 98941, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 729, "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] }, "allPlans" : [{ "cursor" : "BtreeCursor AC", "n" : 6996, "nscannedObjects" : 97692, "nscanned" : 97692, "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] } }, { "cursor" : "BasicCursor", "n" : 4, "nscannedObjects" : 1249, "nscanned" : 1249, "indexBounds" : { } }], "oldPlan" : { "cursor" : "BtreeCursor AC", "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] } }, "server" : "yyyy:56789" }] }, "cursor" : "BtreeCursor AC", "n" : 27799, "nChunkSkips" : 0, "nYields" : 2, "nscanned" : 390433, "nscannedAllPlans" : 393231, "nscannedObjects" : 390433, "nscannedObjectsAllPlans" : 393231, "millisShardTotal" : 3111, "millisShardAvg" : 1555, "numQueries" : 2, "numShards" : 2, "millis" : 2384 }

explain() after upsert for the same query
{ "clusteredType" : "ParallelSort", "shards" : { "set1/xxxx:1234,yyyy:1234" : [{ "cursor" : "BtreeCursor AC", "isMultiKey" : false, "n" : 20799, "nscannedObjects" : 292741, "nscanned" : 292741, "nscannedObjectsAllPlans" : 294290, "nscannedAllPlans" : 294290, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 379, "nChunkSkips" : 0, "millis" : 391470, "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] }, "allPlans" : [{ "cursor" : "BtreeCursor AC", "n" : 20795, "nscannedObjects" : 292741, "nscanned" : 292741, "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] } }, { "cursor" : "BasicCursor", "n" : 4, "nscannedObjects" : 1549, "nscanned" : 1549, "indexBounds" : { } }], "server" : "xxxx:1234" }], "set2/xxxx:56789,yyyy:56789" : [{ "cursor" : "BtreeCursor AC", "isMultiKey" : false, "n" : 7000, "nscannedObjects" : 97692, "nscanned" : 97692, "nscannedObjectsAllPlans" : 98941, "nscannedAllPlans" : 98941, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 910, "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] }, "allPlans" : [{ "cursor" : "BtreeCursor AC", "n" : 6996, "nscannedObjects" : 97692, "nscanned" : 97692, "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] } }, { "cursor" : "BasicCursor", "n" : 4, "nscannedObjects" : 1249, "nscanned" : 1249, "indexBounds" : { } }], "oldPlan" : { "cursor" : "BtreeCursor AC", "indexBounds" : { "f.14.b" : [["A", "A"]], "f.500.b" : [[10, 50]] } }, "server" : "yyyy:56789" }] }, "cursor" : "BtreeCursor AC", "n" : 27799, "nChunkSkips" : 0, "nYields" : 379, "nscanned" : 390433, "nscannedAllPlans" : 393231, "nscannedObjects" : 390433, "nscannedObjectsAllPlans" : 393231, "millisShardTotal" : 392380, "millisShardAvg" : 196190, "numQueries" : 2, "numShards" : 2, "millis" : 391486 }

Btw:
*One single upsert (one affected doc) lets the memory usage drop by around 600MB. --> ~ 4,5GB mem usage reached only after some queries.

*

*if i take the query from above and i use the mongoCursor to loop on the result-set it just takes ages... (query still running as i type) :(

UPDATE II @Daniel
Here you got a sample doc stored in the mongoDB-Cluster.
The Shard Key is the b -Property of my doc (it corresponds to a telephone number)
Upsert:
I search back existing docs by the shard-key and update some properties of the f- array. Then I call Save on the mongoDB driver for all those docs one by one (like 500k times).
There is an index: { "f.14.b" : 1,  "f.500.b" : 1 }
This index is used for complex queries. Like described above those queries are fast before the bulk-update and extremely slow after the update.
   {
  "_id" : ObjectId("51248d6xxxxxxxxxxxxx"),
  "b" : "33600000000",
  "f" : {
    "500" : {
      "a" : ISODate("2013-02-20T08:45:38.075Z"),
      "b" : 91
    },
    "14" : {
      "a" : ISODate("2013-02-20T08:45:38.075Z"),
      "b" : "A"
    },
    "1501" : {
      "a" : ISODate("2013-02-20T08:45:38.141Z"),
      "b" : ["X", "Y", "Z"]
    },
    "2000" : {
      "a" : ISODate("2013-02-20T08:45:38.141Z"),
      "b" : false
    }
  }
}

Thanks a lot,
Blume

A: *

*What version of mongodb are you on?

*When you do the upsert can you do an .explain() on it to see how
    many documents it's scanning.

*What does the disk io look like during the upserts

A: This is interesting. It looks like first, your data is not very evenly distributed. Your explain shows nscanned: 292741 on the first set and nscanned: 97692 on the second set. Pretty big difference. It also shows on the first set nyields:379 and on the second set nyields:0. This implies that only are you reading unevenly from your sets, you are probably writing unevenly to them. You will get more out of your cluster if you choose a shard key that has a more even distribution.
As to why specifically this is happening with your upserts, are you adding more data to your existing documents? If so you are probably a victim of document movement. In your mongodb logs do you see any queries with moved: 1? This means the slow query in the log also had a document movement on disk which causes lots of havok with indexes into arrays/subdocuments. Mongodb I believe still will essentially have to do an index rebuild on the entire document if it moves and will have to do some heavy updating of all indexes into subdocuments/arrays.
The workaround for document movement is to preallocate extra data on document at creation then immediately remove it from the document. Mongo allocates all documents with a fixed space + padding factor on the disk. If they outgrow their space, they must be moved on the disk to a larger area. If you created your documents with already extra data then remove it, you will give yourself a lot of extra padding on disk to accomodate your document growth. This can be a waste of space for sure but it will be a big saver of performance.


text:
Q: TensorFlow: prediction not working properly I am having a few issues with the model that I've made.
1) Sometimes the prediction returns an array of 0s (But that might be normal).
2) If I repeat the prediction multiple times (using loops) I always get the same result.
3)  Strangely enough, if I stop the program and rerun it, the prediction changes (point 2 still applies).
4) The results are wrong. I insert the same exact query as the training (the response predicted is correct while training), but I get a very different response.
Now, the weird thing is that while training I can see that it is improving and that it is working fine.
Here is the piece of code that displays the correct results (training):
decoder_prediction = tf.argmax(decoder_logits, 2) # This line isn't actually here, I put it here to give context
saver.save(sess, MODEL_LOCATION)
fd = next_feed()
predict_ = sess.run(decoder_prediction, fd) # fd stands for feed_dict. This provides {encoder_inputs: .., encoder_inputs_lenghts: .., decoder_targets: ..}
for i, (inp, pred) in enumerate(zip(fd[encoder_inputs].T, predict_.T)): # This is useless but I did not change it as I dont quite understand it (the zip(fd...) part)
    index = random.randint(0, len(fd[encoder_inputs].T)-1) # This is used to pick a random query/prediction
    print('     sample {}'.format(i + 1))
    print('     Query                  > {}'.format(batch_to_words(fd[encoder_inputs].T[index])))
    print('     Predicted Response     > {}'.format(batch_to_words(predict_.T[index])))
    if i >= 2:
        break

And this is the part that I'm having trouble with (prediction):
saver.restore(sess, MODEL_LOCATION)
batch__ = []
query = get_formatted_sentence(sentence)
batch__.append(words_to_batch(query))
batch, batch_len = batch_method(batch__)
for x in range(0,10): # This is the loop I was talking about
    prediction = sess.run(decoder_prediction, feed_dict={encoder_inputs: batch, encoder_inputs_length: batch_len}) # Notice that here I do not give decoder_targets ( If I understand them correctly they are the 'wanted' result. In this case I have no 'wanted' result, I just want to get a prediction
    print(prediction.T)
    print(batch_to_words(prediction.T[0]))

That's it. I don't know why this happens. Any help is appreciated. I've also included the other methods for even more context.

This is next_feed():
def next_feed():

    encoder_inputs_, encoder_input_lengths_ = batch_method(batches_query)
    decoder_targets_, _ = batch_method(
        [sequence + [EOS] + [PAD] for sequence in iter(batches_response)]
    )
    #print(encoder_inputs_)
    #print(encoder_input_lengths_)
    return {
        encoder_inputs: encoder_inputs_,
        encoder_inputs_length: encoder_input_lengths_,
        decoder_targets: decoder_targets_,
    }

And this is batch_method:
def batch_method(inputs, max_sequence_length=None):
    """
    Args:
        inputs:
            list of sentences (integer lists)
        max_sequence_length:
            integer specifying how large should `max_time` dimension be.
            If None, maximum sequence length would be used

    Outputs:
        inputs_time_major:
            input sentences transformed into time-major matrix
            (shape [max_time, batch_size]) padded with 0s
        sequence_lengths:
            batch-sized list of integers specifying amount of active
            time steps in each input sequence
    """

    sequence_lengths = [len(seq) for seq in inputs]
    batch_size_ = len(inputs)

    if max_sequence_length is None:
        max_sequence_length = max(sequence_lengths)

    inputs_batch_major = np.zeros(shape=[batch_size_, max_sequence_length], dtype=np.int32)  # == PAD

    for index, seq in enumerate(inputs):
        for j, element in enumerate(seq):
            inputs_batch_major[index, j] = element

    # [batch_size, max_time] -> [max_time, batch_size]
    inputs_time_major = inputs_batch_major.swapaxes(0, 1)

    return inputs_time_major, sequence_lengths


text:
Q: How to update a field of a table that is inner join of another table in MySQL? I have two tables: tablea and tableb. Both of them have three columns called columna, columnb ,columnc.
Now I want to do this:
If tablea.columnb equals tableb.columnb,then set tablea.columnc = tableb.columnc. I have written the sql and it works well, but I think that there must be a better way to do this? Can anyone help me to optimize my sql statement, or is there any other way?
UPDATE tablea ta
SET
ta.columnc = (
              SELECT columnc FROM tableb
              WHERE ta.columnb = tableb.columnb
             )
WHERE ta.columnb IN (
                     SELECT columnb FROM tableb
                     WHERE ta.columnb = tableb.columnb
                    )

A: You can try this simple query
Update tablea ta,table tb set ta.columnc=tb.columnc where ta.columnb =tb.columnb;


text:
Q: PicoPluginExtensionInitializationException: Can't find bundle for base name org.jetbrains.plugins.cucumber.CucumberBundle, locale en_US I am setting up BDD testing in my application using Cucumber. Since I installed the Gherkin plugin for recognizing feature files and scripts I have been receiving this error that reads
PicoPluginExtensionInitializationException: Can't find bundle for base name org.jetbrains.plugins.cucumber.CucumberBundle, locale en_US

It occurs each time that I open a feature file.
Any experience with this error in the past?


text:
Q: MSAccess database with Basic - accessing fields First time I'm touching both access and basic, but I'm doing a favor for my sister.
I have to retrieve data from a table and some headings have a % character in them and changing the headings is not and option. what does msaccess replace % with?
Let Entitlement = rc![Entitlement% pozitia 1]
rc is the recordset :P

A: I have no Access db handy to test at the moment,
but you might try displaying the field names: (code from here)
Public Sub GetTableObjects()
   Dim db As Database
   Dim tbl As TableDef
   Dim Fld As Field
   Set db = CurrentDb
   For Each tbl In db.TableDefs
     Debug.Print "Table: " & tbl.Name & " ***"
       For Each Fld In tbl.Fields
         Debug.Print Fld.Name
       Next Fld
   Next tbl
End Sub


text:
Q: Python backtracking I have a basic problem in Python where I have to verify if my backtracking code found some solutions (I have to find all sublists of 1 to n numbers with property |x[i] - x[i-1]| == m). How do I check if there is some solution? I mean the potentially solutions I find, I just print them and not save them into memory. I have to print a proper message if there is no solutions.

A: As I suggested in comment, you might want to dissociate computing from I/O printing, by creating a generator of your solutions of |x[i] - x[i-1]| == m
Let's assume you defined a generator for yielding your solutions:
def mysolutions(...):
    ....
    # Something with 'yield', or maybe not.
    ....

Here is a generator decorator that you can use to check if an implemented generator has a value
from itertools import chain
def checkGen(generator, doubt):
    """Decorator used to check that we have data in the generator."""
    try:
        first = next(generator)
    except StopIteration:
        raise RuntimeError("I had no value!")
    return chain([first], generator)

Using this decorator, you can now define your previous solution with :
@checkGen
def mysolutions(...):
    ....

Then, you can simply use it as is, for dissociating your I/O:
try:
    for solution in mysolutions(...):
        print(solution) #Probably needs some formatting
except RuntimeError:
    print("I found no value (or there was some error somewhere...)")


text:
Q: Showing content of String Arrays I have this in my OnItemClick method.
final String[] links = getResources().getStringArray(R.array.pokemon_stats);
               String content = links[position];
               Intent showContent = new Intent(getApplicationContext(),
               PokedexViewActivity.class);
               showContent.setData(content);
               startActivity(showContent);

It doesn't like that I have .setData(content). I believe setData is for URI's. What do I do for a string array? This is the exact error when I hover. The method setData(Uri) in the type Intent is not applicable for the arguments (String)
I switched it to this and I can't get the pokemon stats:
 public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
           final String[] links = getResources().getStringArray(R.array.pokemon_stats);
           String content = links[position];
           Intent showContent = new Intent(getApplicationContext(),
           PokedexViewActivity.class);
           Bundle extras = getIntent().getExtras();
           String pokeStats = extras.getString("MarcsString");
           showContent.putExtra(pokeStats, content);
           startActivity(showContent);

A: Use showContent.putExtra("key", value);


text:
Q: Are you allowed to make an unlimited number of XMLHTTP request objects? In regards to concurrent ajax requests, i have looked at this page:
How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?
But what if onload i have js script creating many http objects with the code:
// JavaScript Document
//declare xmlhttp object
var xmlhttp = false;
var xmlhttp2 = false;

//determine browser/connection type

if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
    xmlhttp2 = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}

I have about 6 different js scripts which are all tailored to perform slightly different ajax functions.
My question is if i have 6-10 different xmlhttp objects being created on pageload, will it somehow be an issue?
Furthermore, even if i have 20 different tailored ajax scripts, aside from what i mentioned above, as long as i dont have more than 3 running at the same time they can all exist toegther, as long as they use different global variables, correct?

A: The number of such objects you can create is only limited by the available memory, i.e. for all practical purposes it is unlimited. As mentioned in the question you reference, the ones that aren't being served immediately are queued up. In practice that means that your application might need a long time to load.
I would try to keep the number of concurrent connections as low as possible (<5). More connections will make the user experience worse. If you have a very large number of connections, the server might block you as well.


text:
Q: How to use jquery globalize with jquery validate unobtrusive in mvc 5 i use mvc 5 but the jquery validate unobtrusive validates the date as MM/dd/yyyy and when i searched how to make it validates dd/MM/yyyy
i found jquery globalize to achieve this but i dont find any examples for the current version Globalize v1.1.2
All the examples i found is for the versions less than 1.x
The view

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

        @Html.EditorFor(model => model.Date, "dd/MM/yyyy", new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })

The metadata specified the date to be dd/MM/yyyy
    [Required(ErrorMessage = " الحقل مطلوب ")]
    [DisplayName("تاريخ ")]
    [DisplayFormat(DataFormatString = "{dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime Date { get; set; }

although that jquery validate unobtrusive validates the date as MM/dd/yyyy

A: I had this problem before, you will need to overload jquery unobtrusive validation  date validation method (as answered here), for it to know entered value is a date. By doing this you wont need to use jquery globalize.
code
jQuery(function ($) {
    $.validator.addMethod('date',
    function (value, element) {
        if (this.optional(element)) {
            return true;
        }

        var ok = true;
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        }
        catch (err) {
            ok = false;
        }
        return ok;
    });

Otherwise if you set your application to use local culture you could then use this
 jQuery(function ($) {
        $.validator.addMethod('date', function (value, element) {
        var d = new Date();
        return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
        });
     });


text:
Q: How to setup firewall ports via logon script I work as IT suport for public service. We use domain controller and logon scripts. These scripts are pretty helpful, since they can automatically install printers and add network folders as local drives.
We use VNC to access user's computers so we can give them suport. In some cases their Windows Firewall is active, and the VNC inbound/outbound ports are configured and work pretty fine. In many other cases, we have to ask people to disable their firewall. That's the practice people do here, and they usually don't ask people to enable the firewall again. Since this is a hazard, I'd like to know if are there any commands we can run on these logon scripts so the ports are automatically configured in all machines and we don't have to ask people to run on network without firewall.
Best.

A: How do I setup firewall ports using a script
netsh can be used to configure the Windows firewall.
In particular netsh advfirewall ...

Enable and delete a port: One of the most common things you need to do with Windows Firewall is open ports that are used by different programs. The following examples show how to use netsh to create a rule to open and then close port 1433, which is used by Microsoft SQL Server:

Source NETSH (Network Shell) - Configure Network Interfaces, Windows Firewall, Routing & remote access.

Example  - Open/Close Ports
Open port:
 netsh advfirewall firewall add rule name="My App" dir=in action=allow protocol=TCP localport=1433

Close port:
 netsh advfirewall firewall delete rule name="My App" protocol=tcp localport=1433

Source Top 10: Windows Firewall Netsh Commands

Example - Enable/Disable Program
You can also add rule rules that use just the program path. In this case you don't need to specify the ports.
Enable Program:
netsh advfirewall firewall add rule name="My App" dir=in action=allow program="C:\MyApp\MyApp.exe" enable=yes

Disable Program:
netsh advfirewall firewall delete rule name="My App" program="C:\MyApp\MyApp.exe"

Source How to use the "netsh advfirewall firewall" context instead of the "netsh firewall" context to control Windows Firewall behavior in Windows Server 2008 and in Windows Vista


text:
Q: Установить позицию DevTools Сегодня обновил Chrome до последней версии, открыл DevTools (ПКМ - Просмотреть код), но внезапно он открылся в новом окне. (Скрин: Тык)
Что ж, подумал я, и попытался найти кнопку для перемещения DevTools в нижнюю часть окна браузера (как это сделано в firefox: Тык для просмотра скрина)
В предыдущих версиях хрома это можно было сделать в меню в правом верхнем углу, но открыв эту менюшку, кнопок для изменения позиции не оказалось: (Скрин: Тык, а должно быть так: Тык)
Вопрос: Куда делись эти кнопки? И как мне изменить позицию DevTools?

A: Попробуйте горячии клавиши в консоли CTRL + SHIFT + D.


text:
Q: Encrypting XML attribute value and an Element? I have working with C# Application. I have two sensitive data in my XML file that is Username and Password.
I want to:

Encrypt and Decrypt the username and password when login, save the file, and load xml. Can any one help me in this?
The xml file is
<Users>
  <user username="kelil2000">
    <password>123</password>
    <author>Home Owner</author>
    <name>Kelil</name>
    <mobile>0911</mobile>
  </user>
  <user username="usminuru">
    <password>1234</password>
    <author>Home Owner</author>
    <name>Ismail K.</name>
    <mobile>0910178976</mobile>
  </user>
 </Users>

Login :
 if (txtUserName.Text == "" || txtPassword.Text == "")
            {
                MessageBox.Show("Username or Passowrd field is empty, try again!");
                ClearTextBoxes();
                return;
            }

            int i = 0; // we use this variable to count if ther's a user with this name

            XmlDocument myXml=new XmlDocument();

            myXml.Load(Application.StartupPath + "/AppUsers/Users.xml");

            XmlNodeList userList = myXml.SelectNodes("Users/user");

            foreach(XmlNode user in userList)

            {

                string userName = user.Attributes["username"].Value;

                string userPassword = user["password"].InnerText;

                string userAuthor = user["author"].InnerText;

                if (userName == txtUserName.Text)

                {

                    ++i;

                    if (userPassword == txtPassword.Text)

                    {

                        Form panel;

                        this.Opacity = 0;

                        switch(userAuthor)

                        {

                            case "Home Owner":

                                panel = new MainWindow();

                                panel.Show();

                                break;

                            case "Member" :

                                panel = new Report();

                                panel.Show();

                                break;

                        }

                    }

                    else

                    {

                        MessageBox.Show("Wrong Password!");
                        ClearTextBoxes();

                    }

                }

              }

            if (i == 0)

                MessageBox.Show("No specified user with this name!");
            ClearTextBoxes();
        }

Save xml:
 private void AddUser()
        {
            if (txtUserName.Text == "" || txtPassword.Text == "" || cmbAuthor.Text == "" || txtName.Text == "" || txtMobile.Text == "")
            {
                MessageBox.Show("Filed is empty");
                return;
            }
            try
            {
                string _file = (Application.StartupPath + "/AppUsers/Users.xml");
                XDocument doc;

                if (!File.Exists(_file))
                {
                    doc = new XDocument();
                    doc.Add(new XElement("Users"));
                }
                else
                {
                    doc = XDocument.Load(_file);
                }

                doc.Root.Add(
                      new XElement("user",
                                   new XAttribute("username", txtUserName.Text),
                                   new XElement("password", txtPassword.Text),
                                   new XElement("author", cmbAuthor.Text),
                                   new XElement("name", txtName.Text),
                                   new XElement("mobile", txtMobile.Text)
                            )
                      );
                doc.Save(_file);

            }
            catch (Exception ex)
            {
                MessageBox.Show("Something Wrong!" + ex.ToString());
            }
        }

Load XML file
private void loadXmlData()
        {

            listView1.Items.Clear();
            XDocument doc = XDocument.Load(Application.StartupPath + "/AppUsers/Users.xml");
            doc.Descendants("user").ToList()
   .ForEach(x => listView1.Items.Add(
                 new ListViewItem(
                 new string[] {
                                 x.Attribute("username").Value,
                                 x.Element("password").Value,
                                 x.Element("author").Value,
                                  x.Element("name").Value,
                                 x.Element("mobile").Value}))
           );

        }

A: First of all you need to choose which encryption to use and where to save your key . once you've done that , you need to run the encryption / decryption method on the value that you are writing/reading from the XML file.


text:
Q: How to clear stack back fragment I have a problem with clean my stack back.
This method shows my fragment:
private fun showFragment(fragment: Fragment, titleTag: String) {

    supportFragmentManager.beginTransaction()
        .replace(R.id.container, fragment, titleTag)
        .addToBackStack(titleTag)
        .commit()

    if (drawer_layout.isDrawerOpen(GravityCompat.END)) {
        drawer_layout.closeDrawer(GravityCompat.END)
    }
}

I have no idea how to clear my stack.

A: FragmentManager manager = getFragmentManager();
FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);


text:
Q: Cannot assign Symfony\Component\VarDumper\Caster\CutStub to reference held by property App\Entity\AccountName::$accountType I am developing a project by Symfony 6.2. In this project one entity AccountType with many to one relationship another entity AccountCategory.
#[ORM\Entity(repositoryClass: AccountTypeRepository::class)]
class AccountType
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 255)]
    private ?string $name = null;

    #[ORM\Column(length: 255)]
    private ?string $code = null;

    #[ORM\Column(length: 255, nullable: true)]
    private ?string $remarks = null;

    #[ORM\OneToMany(mappedBy: 'accountType', targetEntity: AccountName::class)]
    private Collection $accountNames;

    #[ORM\ManyToOne(inversedBy: 'accountTypes')]
    #[ORM\JoinColumn(nullable: false)]
    private ?AccountCategory $accountCategory = null;

    public function __construct()
    {
        $this->accountNames = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getCode(): ?string
    {
        return $this->code;
    }

    public function setCode(string $code): self
    {
        $this->code = $code;

        return $this;
    }

    public function getRemarks(): ?string
    {
        return $this->remarks;
    }

    public function setRemarks(?string $remarks): self
    {
        $this->remarks = $remarks;

        return $this;
    }

    /**
     * @return Collection<int, AccountName>
     */
    public function getAccountNames(): Collection
    {
        return $this->accountNames;
    }

    public function addAccountName(AccountName $accountName): self
    {
        if (!$this->accountNames->contains($accountName)) {
            $this->accountNames->add($accountName);
            $accountName->setAccountType($this);
        }

        return $this;
    }

    public function removeAccountName(AccountName $accountName): self
    {
        if ($this->accountNames->removeElement($accountName)) {
            // set the owning side to null (unless already changed)
            if ($accountName->getAccountType() === $this) {
                $accountName->setAccountType(null);
            }
        }

        return $this;
    }

    public function getAccountCategory(): ?AccountCategory
    {
        return $this->accountCategory;
    }

    public function setAccountCategory(?AccountCategory $accountCategory): self
    {
        $this->accountCategory = $accountCategory;

        return $this;
    }
}

Another Entity:
#[ORM\Entity(repositoryClass: AccountCategoryRepository::class)]
class AccountCategory
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\ManyToOne(inversedBy: 'accountCategories')]
    #[ORM\JoinColumn(nullable: false)]
    private ?AccountReport $accountReport = null;

    #[ORM\Column(length: 255)]
    private ?string $name = null;

    #[ORM\Column(length: 255)]
    private ?string $code = null;

    #[ORM\Column(length: 555, nullable: true)]
    private ?string $remarks = null;

    #[ORM\OneToMany(mappedBy: 'accountCategory', targetEntity: AccountType::class)]
    private Collection $accountTypes;

    public function __construct()
    {
        $this->accountTypes = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getAccountReport(): ?AccountReport
    {
        return $this->accountReport;
    }

    public function setAccountReport(?AccountReport $accountReport): self
    {
        $this->accountReport = $accountReport;

        return $this;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getCode(): ?string
    {
        return $this->code;
    }

    public function setCode(string $code): self
    {
        $this->code = $code;

        return $this;
    }

    public function getRemarks(): ?string
    {
        return $this->remarks;
    }

    public function setRemarks(?string $remarks): self
    {
        $this->remarks = $remarks;

        return $this;
    }

    /**
     * @return Collection<int, AccountType>
     */
    public function getAccountTypes(): Collection
    {
        return $this->accountTypes;
    }

    public function addAccountType(AccountType $accountType): self
    {
        if (!$this->accountTypes->contains($accountType)) {
            $this->accountTypes->add($accountType);
            $accountType->setAccountCategory($this);
        }

        return $this;
    }

    public function removeAccountType(AccountType $accountType): self
    {
        if ($this->accountTypes->removeElement($accountType)) {
            // set the owning side to null (unless already changed)
            if ($accountType->getAccountCategory() === $this) {
                $accountType->setAccountCategory(null);
            }
        }

        return $this;
    }

}

When data retrieve for editing of Account Type form then shown below error.
"Cannot assign Symfony\Component\VarDumper\Caster\CutStub to reference held by property App\Entity\AccountCategory::$accountReport of type ?App\Entity\AccountReport"

A: Seems to be an issue related to php version. I had the same issue and just upgrade my php to 8.2 and the issue disapears.
See also --> https://github.com/symfony/symfony/issues/49091


text:
Q: Flash movie overlaps relatively positioned menu I've been working on a site and noticed a problem with the Flash slider (CU3ER) overlapping the menu bar. I've tried different z-index settings to keep the drop down menu on top, but nothing works.
The drop down menu is visible while the Flash movie loads, but after it finishes loading it gets pushed behind.
http://pivotpointconsulting.com.s139330.gridserver.com/
How It Should Look:
How It Looks:

A: You'll probably need to add param "wmode"->"opaque" to your Flash movie.
  params: {
    wmode: 'opaque',
    bgcolor : '#ffffff'

  }

A: follow these tutorial will fix the problem. see http://shivasoft.in/view_tutorial.php?id=132, it sees the mian point is:
#id{position:absolute; z-index:1;}

A: Hy,
did you add position:absolute; to both elements ? Because that is required for using z-index !

A: Add this under the object tag.
<param name="wmode" value="transparent" />

I got it from here. https://wiki.base22.com/pages/viewpage.action?pageId=37683366
It works!


text:
Q: How zip a file inside a docker contanier? I have exported a very large file inside mongo container in Ubuntu. I just wondering how I can zip a file inside a docker container?
Thanks

A: I suggest using mongoDump. First, enter your target container by docker exec -it containerName bash
Then, Inside the container run the following command to dump and zip the file:
mongodump --db somedb --collection yourCollectionName --out - | gzip > collectiondump.gz


text:
Q: Android Studio: Restart Error: No Android facet found for main I have upgraded my Android studio to 2.9 and I have been getting this error when I try to run my code.

Restart Error: No Android facet found for main

On surfing the web , I found this solution
No Android facet found, issues compiling with Android Studio 0.2
But the new Android studio does not have these options in the 'Project Structure'.
Can anybody suggest any fix?

A: Try to open Project Structure of your project (right click on project -> Open Module Settings), and check if in Facets is added your project, if not - " + " add it. Its worked for me...

A: There is already an update for AS 0.2.10. Try to update AS.
And if you still get the same error:
I don't know if this will help but you also could try to import your project instead of opening it (-> your *.iml files will be generated new by as). But be careful, you have to select the right file: settings.gradle.


text:
Q: Unknown database - [TypeOrmModule] Unable to connect to the database I'm writing my first project with Nestjs and I'm having trouble connecting to the database.
I installed mysql and set up the connection. TypeOrm creates the database itself? or do i have to do it with mysql?
Nest] 13684   - 07/24/2020, 12:44:50 AM   [TypeOrmModule] Unable to connect to the database. Retrying (1)... +42ms
Error: ER_BAD_DB_ERROR: Unknown database 'my-database'

app.module.ts
@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      username: 'root',
      password: 'password',
      database: 'my-database',
      entities: [User],
      synchronize: true,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})

A: First you should create the my-database database in your mysql server.
The TypeOrmModule create only tables (in in first time.)

*

*Create database in your mysql server: CREATE DATABASE myDatabase; (I recommend, use this format: myDatabase.)

*Restart the Nestjs.

That's it!

A:
TypeOrm creates the database itself?

nope

or do I have to do it with mysql?

yes


text:
Q: MVC IIS7 HttpContext.Current.Profile is null I'm trying to set up my site to work with IIS7 MVC 3.
At first HttpContext.Current.User was null,
Then I removed and added models: Session, FormsAuthentication
in system.webServer Models, now HttpContext.Current.User is not null.
But HttpContext.Current.Profile is null and I can't find a work around.
If I set <modules runAllManagedModulesForAllRequests="true"> it fixed the problem, But I don't want to use it because of performance issues.
What is the equivalent Model to FormsAuthentication for Profile in <models>?
Is there a way to get the profile without using runAllManagedModulesForAllRequests?
Web.Config:
 <system.webServer>
<handlers>
  <remove name="ASP.NET MVC" />
  <add name="ASP.NET MVC" path="*" verb="*" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" preCondition="classicMode,runtimeVersionv2.0,bitness64" />

  <remove name="MvcHttpHandler" />
  <add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler" />
  <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

</handlers>
<validation validateIntegratedModeConfiguration="false" />
<modules>
  <remove name="WindowsAuthentication" />
  <remove name="PassportAuthentication" />

  <remove name="UrlRoutingModule-4.0" />
  <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  <remove name="Session" />
  <remove name="FormsAuthentication" />
  <add name="Session" type="System.Web.SessionState.SessionStateModule" />
  <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />

</modules>

A: I found the models list:
http://msdn.microsoft.com/en-us/library/9b9dh535.aspx
and  ended up removing and adding all the modules I use.
Please let me know if you know a better way to get profile and Roles with MVC Routing on IIS 7.
 <remove name="UrlRoutingModule-4.0" />
      <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
      <remove name="Session" />
      <remove name="FormsAuthentication" />
      <remove name="Profile" />
      <remove name="RoleManager" />
      <remove name="OutputCache" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule" />
      <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
      <add name="Profile" type="System.Web.Profile.ProfileModule" />
      <add name="RoleManager" type="System.Web.Security.RoleManagerModule" />
      <add name="OutputCache" type="System.Web.Caching.OutputCacheModule" />


text:
Q: angular js data table pass row data into fucntion I am using angular js data table to my project. currently i am trying to pass value to my onclick function . Please check my below code
$scope.loadRequestApproval = function () {

        $scope.dtOptions = DTOptionsBuilder.newOptions()
            .withOption('ajax', {
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                url: appConfig.apiUrl + "/finalizedAllList?reqTraceId=" + $scope.requestApprovalId,
                xhrFields: { withCredentials: true },
                type: 'POST',
                data: function (d) {
                    return JSON.stringify(d);

                },
                error: function (response) {
                    ajaxErrorHandler.handle(response);
                }
            })

            .withDataProp('data')
            .withOption('processing', true)
            .withOption('serverSide', true)
            .withOption('scrollY', '400px')
            .withOption('scrollX', '100%')
            .withOption('scrollCollapse', true)

            .withOption('drawCallback', function (settings) {

            });
        $scope.dtOptions.withOption('fnRowCallback',
            function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                $compile(nRow, aData, iDisplayIndex, iDisplayIndexFull)($scope);
            });
        $scope.dtColumns = [
            DTColumnBuilder.newColumn('treaceId.traceId').withTitle('Trace ID'),
            DTColumnBuilder.newColumn('name').withTitle('Name'),
            DTColumnBuilder.newColumn('matchRatio').withTitle('Match Strength %'),
            DTColumnBuilder.newColumn('resultId').withTitle('Action').renderWith(function (data, type, full) {

                full.resultId= '500asdx';

                return '
' +
                    '  <button type="button" class="btn btn-flat btn-xs btn-success" ng-click="loadDataById(' + full.resultId+ ');">' +
                    '    ' +
                    '  </button>' +
                    '
';
            }).withClass('text-center').notSortable()
        ];

    };

I am trying to pass my resultId to my loadDataById function. But its not worked.
my function is as below
   $scope.loadDataById = function (requestID) {
            console.log(requestID)
        };

I found some points regarding my issue. When i use numbers, console log is printed. but if its string, console log did not print.
Ex:
full.resultId= 500;
    console log print correctly as 500

full.resultId= '500asdx';
console log did not print.

why i can not use string to do this. I think you can get the my problem. thanks

A: As discussed in the comments, the only thing missing are the inverted commas for strings in the ng-click function. Solution:
ng-click="loadDataById(\'' + full.resultId + '\');"
OR
ng-click="loadDataById(' + "'" + full.resultId + "'" + ');"
I would say go for the first one as it is cleaner


text:
Q: Why shared_pointer does not allow definition like ptr = new Object;
Possible Duplicate:
Why shared_ptr has an explicit constructor

It baffles me why std::shared_ptr<int> p1(new int(10)); is OK while, while std::shared_ptr<int> p2 = new int(10); fails? I think the two should be constructed in the same way.


text:
Q: Mapserver: trying to make a map with an annotation/label I'm trying to make an image with MapServer which only displays one layer with a label. I have written the following mapfile:
MAP
    NAME "TextLayer"
    IMAGETYPE PNG
    EXTENT -180 -90 180 90
    IMAGECOLOR 0 0 255
    PROJECTION
        "init=epsg:4269"
    END
    WEB
        METADATA
            "ows_title" "WMS service"
            "ows_onlineresource"    "XXX.XXX.XXX.XXX"
            "ows_enable_request"    "*"
            "ows_crs" "EPSG:4269"
        END
    END
    LAYER
        NAME "labellayer"
        STATUS ON
        TYPE POINT
        FEATURE
            POINTS 100 100 END
            TEXT "The text on the image"
        END
        CLASS
            LABEL
                SIZE 8
                ANTIALIAS true
                COLOR 255 0 0
                POSITION cc
            END
        END
    END
END

I am generating the image with PHP with ms_newMapObjFromString(). However, all I get is a transparent image without any text. What am I missing?
EDIT:
PHP Code:
public function PrintImage($request, $mapFileString)
{
    $mapServer_MapObject = ms_newMapObjFromString($mapFileString);

    ms_ioinstallstdouttobuffer();

    $mapServer_MapObject->owsdispatch($request);

    $contenttype = ms_iostripstdoutbuffercontenttype();

    ms_iostripStdoutBufferContentType();

    //If content type is 'image/png' the image is succesfully requested -> show the image
    if($contenttype == "image/png")
    {
        header('Content-type: image/png');

        echo ms_iogetstdoutbufferbytes();
    }
    //Else an error occured -> show the error
    else
    {
        header('Content-type: xml');

        echo ms_iogetstdoutbufferstring();
    }
}

$MapFileString is the string posted above.

A: Your map extent does not match the projection you are using. You probably mean the projection EPSG:4326, because -180 -90 180 90 is the maximal extension of this projection.
Another problem is that your point (POINTS 100 100) is outside the bounding box you request (EXTENT -180 -90 180 90)
Try putting the point on the center of the image with
POINTS 0 0

PS: if it does not work, post your php code as well

A: One way of doing this (there may be others) is in your LAYER config you need to add a LABELITEM to identify the attribute in your data to take the label text.
So for example in the below example, the Crude Oil label is the data in the Gen_Type attribute of the input data, and the class for the "Crude Oil" value includes LABEL instructions.

So in the map file we have:
LAYER
    CLASSITEM "Gen_Type"
    DATA "geom FROM public.energy_gen2016"
    EXTENT 29.62017 -1.31861 34.88271 3.69740
    GROUP "ENERGY-GEN"
    INCLUDE "generic-layer-config.map"
    LABELITEM "Gen_Type"
    METADATA
        "GML_FEATUREID" "fid"
        "OWS_ABSTRACT" "Energy generation sites (2016) classified by energy type. The data was downloaded from Data.Ug, and is acquired from the Ministry of Mining and Mineral Development."
        "OWS_DATAURL_HREF" "http://catalog.data.ug/dataset/generation-sites"
        "OWS_EXTENT" "29.62017 -1.31861 34.88271 3.69740"
        "OWS_KEYWORDLIST" "continent@Africa,subcontinent@Eastern Africa,geographicarea@Uganda,serviceprovider@British Geological Survey,DS_TOPIC@utilitiesCommunications,thematic@Energy,DS_DATE@2016"
        "OWS_TITLE" "Energy generation type (2016)"
        INCLUDE "commonLayerMD.map"
    END
    NAME "ENERGY_TYPE_2016"
    TEMPLATE "tmpl/UPP_energy_tpl.html"
    TYPE POINT
    INCLUDE "style/entype.map"
END

and in the 'style' file we have:
    CLASS
        NAME "Crude Oil"
        EXPRESSION {Crude Oil}
        STYLE
            SYMBOL "circlef"
            COLOR "#000000"
            OUTLINECOLOR "#232323"
            SIZE 6
        END
        LABEL
            FONT scb
            TYPE TRUETYPE
            SIZE 8
            COLOR 0 0 0
            ALIGN CENTER
            PRIORITY 10
            BUFFER 1
            PARTIALS TRUE
            POSITION lc
        END
    END


text:
Q: Xamarin: Web API receiving different results based on OS I am running into a strange problem and I have had a difficult time finding a solution. I am using Xamarin to build an app for both Android and iOS. The app does a call out to a Web Api service using a rest request. I have found that, in my Web Api service the object that is being passed to my Post method is null on iOS, but is completely intact for Android only after changing the Post method's parameter from my defined type to type of "Object".
I was able to identify a partial solution for after heeding the advice found in this stack overflow article: Web API complex parameter properties are all null. My object somewhat mirrors the example object in the article in that I have a decimal property, two date properties, and an array property. When I change my Post parameter to type "Object" then the object is successfully received by my Post method. When I test with using iOS though the parameter is still null. I have tried the following so far:

*

*Write the object to debug output both before and after it was added to the http request. Everything looks correct before it is posted.

*On the service side, included code inside of the Post method to view the parameter object's content by checking if it is null (this information was written to a log using log4net).

I have exhausted my knowledge and would appreciate any information and have not found any useful resources online.
UPDATE

Following is the code to call the service:
public async Task<ReportResult> SubmitReport(decimal amount,
DateTime reportDate, byte[] image)
{
    var rc = new RestClient(new
    Uri("https://service.example.com/Application"));

    var req = new RestRequest("api/Controller/", Method.POST);
    req.Serializer = new RestSharp.Portable.Serializers.JsonSerializer();

    req.AddHeader("token", Application.Current.Properties["token"]
    as string);

    var report = new Report()
    {
        CustomerID = "Customer/" +
        Application.Current.Properties["username"].ToString(),
        Amount = amount,
        ReportDate = reportDate,
        ReportImageExtension = "png",
        EntryDate = DateTime.Now,
        Image = image
    };

    req.AddBody(report);

    var results = await rc.Execute<ReportResult>(req);

    return results.Data;
}

And here is the signature of my Post method in the service:
public async Task<ReportResult> Post(Report report)

The first thing that I do in the Post method is check the report parameter. It exists in android but is null in iOS.
Here is the data that is receved by my Post method when the parameter's type is just "Object". This was sent from the Android OS:
{
  "CustomerID": "Customer/JohnDoe",
  "ReportDate": "2017-06-27T00:00:00-04:00",
  "EntryDate": "2017-06-27T11:01:17.382801-04:00",
  "Amount": 111.11,
  "Image": "/9j/4VFORXhpZgAASUkqAAgAAAAMA...y1P4bP/9k=",
  "ReportImageExtension": "png"
}

The Image property has been condensed by me since it is a large byte array.


text:
Q: How do you convert an AVAsset into CMSampleBuffer frames? My app imports video that the user selects through the system file picker, which comes as an AVAsset:
@IBAction func handleImportVideoButton(_ sender: Any) {
    let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.movie], asCopy: true)
    documentPicker.delegate = self
    present(documentPicker, animated: true)
}

// UIDocumentPickerDelegate callback.
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    guard let url = urls.first else {
        return
    }
    model.recordedVideoSource = AVAsset(url: url)
}

How do I then convert this AVAsset into CMSampleBuffer frames? The end goal is to then convert the CMSampleBuffer frames into CGImages so I can think perform machine learning analysis on each image frame.

A: This is untested but it should give you the gist of how to go about this:
let asset = AVAsset()
let reader = AVAssetReader(asset: asset)
guard let track = asset.tracks(withMediaType: .video).last else {
    return
}
let trackOutput = AVAssetReaderTrackOutput(track: track, outputSettings: nil)
reader.add(trackOutput)
reader.startReading()

// Get first sample buffer
var sample = trackOutput.copyNextSampleBuffer()
while sample != nil {
    // iterate over all buffers
    // sample = trackOutput.copyNextSampleBuffer()
}


text:
Q: Quaternion To Direction Vector I am attempting to convert my Quaternion to a direction vector so that I can move my camera in the direction it is facing. I read that you can convert your quaternion to a rotation matrix first then get the direction so I tried that.
inline Matrix4<float> ToRotationMatrix() {
    Vector3<float> forward = Vector3<float>( 2.0f * ( GetX() * GetZ() - GetW() * GetY() ), 2.0f * ( GetY() * GetZ() + GetW() * GetX() ), 1.0f - 2.0f * ( GetX() * GetX() + GetY() * GetY() ) );
    Vector3<float> up = Vector3<float>( 2.0f * ( GetX() * GetY() + GetW() * GetZ() ), 1.0f - 2.0f * ( GetX() * GetX() + GetZ() * GetZ() ), 2.0f * ( GetY() * GetZ() - GetW() * GetX() ) );
    Vector3<float> right = Vector3<float>( 1.0f - 2.0f * ( GetY() * GetY() + GetZ() * GetZ() ), 2.0f * ( GetX() * GetY() - GetW() * GetZ() ), 2.0f * ( GetX() * GetZ() + GetW() * GetY() ) );

    return Matrix4<float>().InitRotationFromVectors( forward, up, right );
}

inline Matrix4<T> InitRotationFromVectors( const Vector3<T> &n, const Vector3<T> &v, const Vector3<T> &u ) {
    Matrix4<T> ret = Matrix4<T>().InitIdentity();

    ret[ 0 ][ 0 ] = u.GetX();
    ret[ 1 ][ 0 ] = u.GetY();
    ret[ 2 ][ 0 ] = u.GetZ();

    ret[ 0 ][ 1 ] = v.GetX();
    ret[ 1 ][ 1 ] = v.GetY();
    ret[ 2 ][ 1 ] = v.GetZ();

    ret[ 0 ][ 2 ] = n.GetX();
    ret[ 1 ][ 2 ] = n.GetY();
    ret[ 2 ][ 2 ] = n.GetZ();

    return ret;
}

inline Vector3<float> GetForward( const Matrix4<float> &rotation ) const {
    return Vector3<float>( rotation[ 2 ][ 0 ], rotation[ 2 ][ 1 ], rotation[ 2 ][ 2 ] );
}

When my camera is facing forward it moves in the correct direction but when  I turn it the camera starts moving in incorrect directions. The camera rotates like so.
void Camera::Rotate( const Vector3<float> &axis, float angle ) {
    Rotate( Quaternion( axis, angle ) );
}

void Camera::Rotate( const Quaternion &quaternion ) {
    m_rotation = Quaternion( ( quaternion * m_rotation ).Normalized() );
}

And to multiply those quaternions....
inline Quaternion operator*( const Quaternion &quat ) const {
    Quaternion ret;

    ret[ 3 ] = ( ( *this )[ 3 ] * quat[ 3 ] ) - ( ( *this )[ 0 ] * quat[ 0 ] ) - ( ( *this )[ 1 ] * quat[ 1 ] ) - ( ( *this )[ 2 ] * quat[ 2 ] );
    ret[ 0 ] = ( ( *this )[ 3 ] * quat[ 0 ] ) + ( ( *this )[ 0 ] * quat[ 3 ] ) + ( ( *this )[ 1 ] * quat[ 2 ] ) - ( ( *this )[ 2 ] * quat[ 1 ] );
    ret[ 1 ] = ( ( *this )[ 3 ] * quat[ 1 ] ) + ( ( *this )[ 1 ] * quat[ 3 ] ) + ( ( *this )[ 2 ] * quat[ 0 ] ) - ( ( *this )[ 0 ] * quat[ 2 ] );
    ret[ 2 ] = ( ( *this )[ 3 ] * quat[ 2 ] ) + ( ( *this )[ 2 ] * quat[ 3 ] ) + ( ( *this )[ 0 ] * quat[ 1 ] ) - ( ( *this )[ 1 ] * quat[ 0 ] );

    return ret;
}

Note: Quaternion[ 0 ] is x, Quaternion[ 1 ] is y, Quaternion[ 2 ] is z and Quaternion[ 3 ] is w.
I have been struggling with this for weeks and I am out of ideas of what could be wrong. If anybody has any ideas or suggestions on why this works or other ways to do it it would be greatly appreciated. Thanks!

A: So let's rephrase what you want to do: you have a representation of the camera's position in the global frame, G_p1, and want to move it forward in its own frame by an amount C_t = [0;0;1] (here, G_ prefix means global frame, C_ means camera).
We want to compute G_p2 = G_p1 + G_t. We need to write G_t in terms of C_t.
We can write this as G_t = G_R_C C_t, where G_R_C is the rotation matrix describing the rotation from the camera to the global frame. Writing this as a function of your quaternion q, you just need to compute G_t = G_R_C(q) C_t and add it to the position. Because C_t = [0;0;1], you can see that G_t is the last column of G_R_C(q). You're using the last row, not the last column.


text:
Q: Compare two lists of numbers, need to check the range of value in A filel with first 2 columns of B file Input files:
A.txt contains:
111
222
223
344
100002
99991

B.txt contains:
100 199 A
200 299 B
300 399 C
400 499 D

I want the output like this
111 A
222 B
223 B
344 C

A: You want to output the values for B.txt that fall within a range defined by A.txt, together with the label for that range.
$ awk 'FNR==NR { rs[$3] = $1; re[$3] = $2; next } { for (s in rs) if ($1 >= rs[s] && $1 <= re[s]) { print $1, s; next } }' A.txt B.txt
111 A
222 B
223 B
344 C

The first block would parse the ranges in A.txt and save the start and end for each range in the two arrays rs (for start) and re (for end).  These arrays are indexed by the label assigned to the range in the file.
When parsing the second file (which will be done in the second block of the code), we loop through each range in these variables and test wether the number falls within one of them.  If it does, the number is outputted together with the label of the range (in the code, the label is extracted into s for "string").

The main difference between the above code and the code presented by pLumo is that my code would iterate through the ranges for each given input number to find the range that contains the number, while their code stores each integer of each range for faster lookup.  Their code would be fast to use on a large number of lookups in small ranges, while my code is trades speed for memory efficiency and would be preferable if your ranges are large or you have just a few lookups to make.

A: Try with awk:
awk '
    FNR==NR{for(n=$1;n<=$2;n++)v[n]=$3}
    FNR!=NR{if(v[$1])print $1,v[$1]}
' B.txt A.txt

First row creates an array v with value being $3 for all numbers between $1 and $2 from file B.txt.
Second row reads the value from that array with the number given in A.txt.
Output:
111 A
222 B
223 B
344 C

A: awk -v test="$(awk '{print $1+0}' A.txt)" '{ if ($1 > test && $2 < test) {print test,$3} }'  B.txt


text:
Q: Gradle Copy task only doing partial copy I have a Gradle "deploy" task that copies a JAR and all the contents of a "config" folder to an intended destination. My project directory structure looks like:
myapp/
    src/main/java/
        <java sources>
    config/
        <lots of stuff>
    build.gradle
    settings.gradle

And my deploy task looks like:
task deploy(type: Copy, overwrite: true) {
    from('build/libs')
    into('/Users/myuser/myapp/deploy/myapp')
    include('myapp.jar')

    from('config')
    into('/Users/myuser/myapp/deploy/myapp')
    include('config/**')
}

When I run ./gradle build deploy, I see the JAR getting copied to /Users/myuser/myapp/deploy/myapp, but not the config directory (nor all of its subdirectories and contents). The desired end result is a /Users/myuser/myapp/deploy/myapp directory that looks like:
/Users/myuser/myapp/deploy/myapp/
    myapp.jar
    config/
        <lots of stuff>

Furthermore, the idea is that this copy should be "drop n' swap", particularly for the config directory. That is, regardless of what is currently in the /Users/myuser/myapp/deploy/myapp/config directory, when I run deploy, those contents are completely replaced by whatever is in the config/ directory of my project.
UPDATE
I have created a GitHub repo to demonstrate the issue. Simply follow the instructions to reproduce.
Any ideas where I'm going awry?

A: I suppose, the reason is include('config/**'), which should include something like config/config/**, where ** is all subdirectories, but not all the files under config/ directory.
Try to make it as follows:
task deploy(type: Copy, overwrite: true) {
    from('build/libs')
    into('/Users/myuser/myapp/deploy/myapp')
    include('myapp.jar')

    into('/Users/myuser/myapp/deploy/myapp')
    include('config/**')
}

A: *

*To directly answer your question:
task deploy(type: Copy, overwrite: true){
    from ("$buildDir/libs"){include('gradlecopyexample.jar')}
    from ("$rootDir"){include('config/**')}
    into("$buildDir/deploy")
}

*However, I still am of the opinion that the gradle application plugin is a good fit for your usecase. Instead of having the config folder in the root directory, place it under src/dist, Then running gradle installDist (or distZip) will include your config folder with the distribution package.


text:
Q: Ping to dnsmasq's host resolvesto 127.0.0.1 I've just set up dnsmasq in my home lan for the first time. I got it as DHCP and DNS.
Something strange is that when I ping DEV01 (which has dnsmasq) it resolves to 127.0.0.1 and I don't know why it is doing so.
jorgee@jorgee:~$ nslookup dev01 192.168.1.2
Server:     192.168.1.2
Address:    192.168.1.2#53

Name:   dev01
Address: 127.0.1.1

Is anything else to configure?

A: The solution is to change the hosts file to reflect the IP Address of the network interface (ie change 127.0.0.1 to 192.168.1.2).
This works because DNSMasq is translating the Domain name into the IP address based on the contents of the "hosts" file, and the hosts file is set to point the domain name to 127.0.0.1 which is a special address each machine on the Internet has so it can refer to itself even without a valid Internet connection - but 127.0.0.1 does not work so well for a server.


text:
Q: Node js mongoose MissingSchemaError: Schema hasn't been registered for model I am trying to make many to many relation between two collection categories and products and i am trying to view it on a table using populate() but it shows error 'MissingSchemaError: Schema hasn't been registered for model "Category"'.
Category.js
  const mongoose = require('mongoose');
  const Schema = mongoose.Schema;

  const categorySchema = new mongoose.Schema({
      catname: String,
      product: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Product"
        }
      ]
    });

  module.exports = mongoose.model('category', categorySchema);

Product.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const contactSchema = new mongoose.Schema({
    name: String,
    quantity: String,
    price: String,
    categories: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Category"
      }
    ]
  });

module.exports = mongoose.model('product', contactSchema);

home.js
const express = require('express');
const router = express.Router();
const Club = require('../models/Club');
const Category = require('../models/Category');

// ROUTE FOR READ
router.get('/', (req, res) => {

    let all_categories = [];
    Category.find((err, docs) => {
        all_categories = docs;
    });
    Club.find({}).populate('categories').exec((err, docs) => {
        console.log(docs);
        if (err) throw err;
        // console.log(docs);
        res.render('home', {
            products: docs,
            categories: all_categories
        })
    })
});

A: In
module.exports = mongoose.model('category', categorySchema);

you wrote category in lower case. So your ref should be 'category' or the model be initialized with
module.exports = mongoose.model('Category', categorySchema);


text:
Q: How to place button without spaces? I need to place button at left side of a panel without any spaces.
i do it like this:

but I see in browser instruments that my content is in another inner div and it has default style settings:

        <button id="A7058:form:content">...</button>

so my button doesn't go left as I want to.
How to place button at left side?

A: In HTML, white space is meaningful, and is by default collapsed down to a single space. You can modify your markup to remove any white space, but this often results in code that isn't very readable. Commenting out white space is another possibility. You can also use font-size: 0 in your CSS to force text nodes (including white space) to occupy no physical space, then apply a second font-size declaration on child elements that should display text.
Space may also come from margins, padding or borders. Use your browser's developer tools to investigate where the space is coming from.


text:
Q: PHP function to implement sending SMS I am trying to implement sending SMS for this project I am working on using PHP. Note: I don't mean sending free SMS with the carrier and other things, I actually contacted an SMS company that provided a link as such
www.smssender.com?username=myusername&pass=mypass&message=mymessage&recipient=phonenumber.
What function in PHP can be used to send such a request to the server API, and also get a response? Here is what I want (pseudocode):
function Sendsms(){
  add details to sting
  send url to sms server with the parameters
  get response and display
}

A: you want to do something like the following (this is an example for a POST request)
i am using PHP's curl http://www.php.net/manual/en/function.curl-init.php
:
$url = 'http://domain.com/get-post.php';
$fields = array(
            'lname' => urlencode($last_name),
            'fname' => urlencode($first_name),
            'title' => urlencode($title),
            'company' => urlencode($institution),
            'age' => urlencode($age),
            'email' => urlencode($email),
            'phone' => urlencode($phone)
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

The response to the request is in the variable $result

A: Look like you are doing a GET request. Have you looked into php http_get function?
<?php
$response = http_get("http://www.example.com/", array("timeout"=>1), $info);
print_r($info);
?>

source: http://us2.php.net/manual/en/function.http-get.php

A: function Sendsms()
{
   //add details to sting
     $url="www.smssender.comusername=myusername&pass=mypass&message=
      mymessage&recipient=phonenumber";

   //send url to sms server with the parameters
   $rsp = file_get_contents($url);

   //get response and display
   if( $res )
   {
        echo "sms successfully send";
   }
}


text:
Q: Crystal Reports XI - convert csv input string parameter to number array for use in record selection formula I have a report which I'm working on which has an input parameter (strSchoolIds) that is a string of comma separated list of unique schoolIds. I'd like to convert this string into a number array which can then be used in the record selection formula. Here is what I've come up with so far. But whenever I view the report just the first schoolId gets used.
Example input string for strSchoolIds might be  1,3,63,237,281
The resulting SQL query I'd like would be similiar to this
Select name, phone, numStudents
from schools
where schoolId in (1,3,63,237,281) and active =1

My current code is:
StringVar Array schools := Split ({?strSchoolIds}, ",");
Local NumberVar arrLen := UBound( schools );
Local NumberVar i := 1;

NumberVar Array schoolIdsArray;
While i <= arrLen Do
(
    schoolIdsArray[i] = ToNumber(Trim(schools[i]));
    i := i + 1;
);

{Schools.schoolId} in schoolIdsArray
and {Schools.active} = 1;

A: I've got code similar to the:
{Schools.schoolId} in schoolIdsArray

and it works properly.
Are you sure your array is getting populated properly?
You can test this quickly by adding a new unbound string field and placing this in the formula
ToText(schoolIdsArray[1]) + ", " + ToText(schoolIdsArray[2])

A: I figured it out after using Nathan Koop's suggestion and building upon it to debug with. Turns out I needed to Redim the schoolIdsArray with the arrLen of the string Array schools before adding values to it.
StringVar Array schools := Split ({?strSchoolIds}, ",");
Local NumberVar arrLen := UBound( schools );
Local NumberVar i := 1;
NumberVar Array schoolIdsArray;
Redim schoolIdsArray[arrLen];
While i <= arrLen Do
(
    schoolIdsArray[i] = ToNumber(Trim(schools[i]));
    i := i + 1;
);

{Schools.schoolId} in schoolIdsArray
and {Schools.active} = 1;

A: In this part of the code, I added a colon and it worked...
schoolIdsArray[i] := ToNumber(Trim(schools[i]));

Hope this helps...

A: Discovered that there is a little error in the above code:

schoolIdsArray[i] = ToNumber(Trim(schools[i]));

This should be:

schoolIdsArray[i] := ToNumber(Trim(schools[i]));


text:
Q: Spring returning 200 with no content and not hitting controller I have a controller as
@Controller
@RequestMapping("/v2/**")
public class ReactController {

    @RequestMapping(method = RequestMethod.GET)
    public String reactEntry() {
        return "react-entry";
    }
}

When I log into the app and go through the login page, then navigate to the page that hits this URL, I get the content. However, if I go directly to the URL (it hits the login page but then forwards directly to this URL) spring returns a status code of 200 with a content length of 0 and my controller is never hit.
In debug logging, in the normal case I see:
[DEBUG] 17 Aug 2018 10:41:50,805 org.springframework.security.web.FilterChainProxy - /v2/ reached end of additional filter chain; proceeding with original chain
[TRACE] 17 Aug 2018 10:41:50,807 org.springframework.web.servlet.DispatcherServlet - Bound request context to thread: SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.context.HttpSessionSecurityContextRepository Servlet3SaveToSessionRequestWrapper@38f60506]
[DEBUG] 17 Aug 2018 10:41:50,807 org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'cem' processing GET request for [/cems/v2/]
[TRACE] 17 Aug 2018 10:41:50,807 org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping@746fb8d3] in DispatcherServlet with name 'cem'
[DEBUG] 17 Aug 2018 10:41:50,807 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /v2/
[TRACE] 17 Aug 2018 10:41:50,842 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Found 1 matching mapping(s) for [/v2/] : [{[/v2/**],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}]
[DEBUG] 17 Aug 2018 10:41:50,842 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public java.lang.String rest.controller.ReactController.reactEntry()]

However, when hit via the second mechanism, I get:
[DEBUG] 17 Aug 2018 10:45:32,702 org.springframework.security.web.FilterChainProxy - /v2/ reached end of additional filter chain; proceeding with original chain
[DEBUG] 17 Aug 2018 10:45:32,779 org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected element of bean 'domain.User': PersistenceElement for transient javax.persistence.EntityManager rest.domain.Personnel.entityManager

Notice the time gap which suggests that second line is part of a different request.
It appears that in the second case, the request is not being mapping to the cems DispatcherServlet even though it is the same URL.


text:
Q: Node.js: How to route website map I am newbie in Node.js; sorry if my question is dumb:
I wanted to return index.html from server:
var express = require('express');
var app = express();
var path = require('path');

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.get('/elements/hello-world.html', function (req, res) {
    res.sendFile(path.join(__dirname + '/elements/hello-world.html'));
});

app.listen(1337);

But there are many assets in the html file that are stored with the appropriate structure on local server. For example, for returning /elements/hello-world.html, it is sufficient to return hello-world.html under elements folder which itself is in root.
But it is not reasonable to write a route for every asset (like csses, images, etc) in index.html.
What is the solution?

A: looks like you want to serve static files,to serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
app.use(express.static('public'))

Now, you can load the files that are in the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

taken from the official express docs here

A: The solution is app.use, like (CoffeeScript):
app.use express.static(public_dir)
app.use '/js', express.static(path.join(public_dir, '/js'))
app.use '/css', express.static(path.join(public_dir, '/css'))
app.use '/images', express.static(path.join(public_dir, '/images'))
app.use '/fonts', express.static(path.join(public_dir, '/fonts'))
app.use '/svgs', express.static(path.join(public_dir, '/svgs'))

In the index.html we pull resources like
    <script type="text/javascript" src="/js/primus.js"></script>
    <script type="text/javascript" src="/js/app_090.js"></script>

I'm actually not sure if that answers your question, but this is how resource type routing is done in Express.

A: You need to use the express static module.
app.use(express.static(path.join(__dirname, 'public')));

Create a folder called public in your nodejs root folder, put your index.html and your elements folder inside it.
Now when you load http://localhost/index.html and http://localhost/elements/hello-world.html it should work without any issues.


text:
Q: How I can access to $_SESSION in Craft CMS 3.x Is it possible to access to $_SESSION variable in .twig template Craft CMS 3.x version ? I found articles about 2.5 version but nothing for 3.x+.
Thanks for help.

A: The session component in Craft 3 is available under Craft::$app->session in PHP and craft.app.session in twig. This returns a craft\web\Session object corresponding to the current user's session.