text:
Q: Creating C structs using the RubyInline gem I've got a Rails app that needs to show the results of a Monte Carlo sim, and for the first time, Ruby just isn't fast enough for my needs. So, I started poking around to see if I could rewrite my simulation in C and use those results in Ruby, and some googling turned up the RubyInline gem for easily writing faster C code directly in Ruby. Doing simple stuff works great, for instance, some basic functions written in both Ruby and C:
class FasterFunctions
  inline do |builder|
    builder.c '
    double rand_sum(int trials)
    {
      double sum = 0.0;
      for (int i = 0; i<trials; i++)
      {
        sum += (double)rand()/(double)RAND_MAX;
      }
      return sum;
    }'

    builder.c '
    long loop_sum(long trials)
    {
      long sum = 0;
      for (long i = 0; i<trials; i++)
      {
        sum+=i;
      }
      return sum;
    }'
  end
end

#the C version is 4 orders of magnitude faster
trials = 1_000_000
ruby_sum = 0
trials.times {|i| ruby_sum += i}
c_sum = FasterRand.new.loop_sum(trials)

# the C version is 1 order of magnitude faster
ruby_sum = 0.0
trials.times {ruby_sum += rand}
c_sum = FasterRand.new.rand_sum(trials)

So, great, it should definitely speed up my sim since it's pretty much just generating random numbers and adding stuff up based on those results. Unfortunately, beyond basic stuff like this, I can't figure out how to actually write my program. I need to pass some structs around to act as state variables, so the first order of business is figuring out how to create a C struct. Reading the documentation, it seems like it should be fairly simple.

accessor(method, type, member = method)
Adds a reader and writer for a C struct member wrapped via
  Data_Wrap_Struct. method is the ruby name to give the accessor, type
  is the C type. Unless the C member name is overridden with member, the
  method name is used as the struct member.
builder.struct_name = 'MyStruct'
builder.accessor :title,        'char *'
builder.accessor :stream_index, 'int',   :index

The documentation isn't entirely clear to me, but I assume that I'd put that in a class much like before and do something like the following to access it:
class MyStructClass
  inline do |builder|
    builder.struct_name = 'MyStruct'
    builder.accessor :title, 'char *'
    builder.accessor :stream_index, 'int', :index
  end
end

#possible this
struct = MyStructClass.new.MyStruct
struct.title = 'A Title'

#or maybe
struct = MyStructClass.new
struct.title = 'A Title'

Unfortunately, I can't even get that far

*/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:456:3:
  error: use of undeclared identifier
        'MyStruct'   MyStruct *pointer;   ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:456:13: error: use of undeclared identifier
        'pointer'   MyStruct *pointer;
              ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:458:35: error: use of undeclared identifier
        'pointer'   Data_Get_Struct(self, MyStruct, pointer);
                                    ^
  /.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/ruby.h:1038:6: note: expanded from macro 'Data_Get_Struct'
      (sval) = (type)DATA_PTR(obj);\
       ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:458:25: error: use of undeclared identifier
        'MyStruct'   Data_Get_Struct(self, MyStruct, pointer);
                          ^
  /.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/ruby.h:1038:15: note: expanded from macro 'Data_Get_Struct'
      (sval) = (type)DATA_PTR(obj);\
                ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:458:3:
  error: expected expression   Data_Get_Struct(self, MyStruct, pointer);
  ^
  /.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/ruby.h:1038:20: note: expanded from macro 'Data_Get_Struct'
      (sval) = (type)DATA_PTR(obj);\
                     ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:460:23: error: use of undeclared identifier
        'pointer'   return (rb_str_new2(pointer->title));
                        ^
  */.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/intern.h:786:27: note: expanded from macro 'rb_str_new_cstr'
      (__builtin_constant_p(str)) ?               \
                            ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:460:23: error: use of undeclared identifier
        'pointer'
  */.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/intern.h:787:14: note: expanded from macro 'rb_str_new_cstr'
          rb_str_new((str), (long)strlen(str)) :  \
                      ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:460:23: error: use of undeclared identifier
        'pointer'
  */.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/intern.h:787:33: note: expanded from macro 'rb_str_new_cstr'
          rb_str_new((str), (long)strlen(str)) :  \
                                         ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:460:23: error: use of undeclared identifier
        'pointer'
  */.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/intern.h:788:18: note: expanded from macro 'rb_str_new_cstr'
          rb_str_new_cstr(str);                   \
                          ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:460:10: error: returning 'void' from a
        function with incompatible result type 'VALUE' (aka 'unsigned long')   return (rb_str_new2(pointer->title));
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:478:3:
  error: use of undeclared identifier
        'MyStruct'   MyStruct *pointer;   ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:478:13: error: use of undeclared identifier
        'pointer'   MyStruct *pointer;
              ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:480:35: error: use of undeclared identifier
        'pointer'   Data_Get_Struct(self, MyStruct, pointer);
                                    ^
  /.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/ruby.h:1038:6: note: expanded from macro 'Data_Get_Struct'
      (sval) = (type)DATA_PTR(obj);\
       ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:480:25: error: use of undeclared identifier
        'MyStruct'   Data_Get_Struct(self, MyStruct, pointer);
                          ^
  /.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/ruby.h:1038:15: note: expanded from macro 'Data_Get_Struct'
      (sval) = (type)DATA_PTR(obj);\
                ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:480:3:
  error: expected expression   Data_Get_Struct(self, MyStruct, pointer);
  ^
  /.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/ruby.h:1038:20: note: expanded from macro 'Data_Get_Struct'
      (sval) = (type)DATA_PTR(obj);\
                     ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:482:3:
  error: use of undeclared identifier
        'pointer'   pointer->title = StringValuePtr(value);   ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:456:3:
  error: use of undeclared identifier
        'MyStruct'   MyStruct *pointer;   ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:456:13: error: use of undeclared identifier
        'pointer'   MyStruct *pointer;
              ^
  */.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/RubyInline-3.12.4/lib/inline.rb:458:35: error: use of undeclared identifier
        'pointer'   Data_Get_Struct(self, MyStruct, pointer);
                                    ^
  /.rbenv/versions/2.1.2/include/ruby-2.1.0/ruby/ruby.h:1038:6: note: expanded from macro 'Data_Get_Struct'
      (sval) = (type)DATA_PTR(obj);\
       ^ fatal error: too many errors emitted, stopping now [-ferror-limit=]

I've done a bunch of googling, but pretty much every example I've found deals only with the simple use case I outlined at first. The first error it spit out was that MyStruct was undeclared, so I tried adding a struct definition before the accessor methods, like so:
builder.c '
  typedef struct
  {
    char *title;
    int index;
  } MyStruct;
'

That doesn't do anything, and the documentation seems to be clear that the c method is only for declaring functions, not structs. I'm not really sure what to try next, does anyone else have some experience with this?

A: RubyInline seems to assume that you know your way around writing Ruby extensions if you are doing anything more complex than the basics.
You do need to define the struct yourself as you tried, but you should use the prefix method rather than the c method (which is for defining methods). You also need to define the allocation method for the class. You can do this with the c_singleton method by adding a function named allocate which RubyInline will recognise and use as the allocation function (this doesn't seem to be documented, I found it by looking at the source).
Putting it all together looks something like this.
class Foo
  inline do |builder|

    # First define the struct that will be wrapped in the
    # class.
    builder.prefix <<-DEFINE_STRUCT
      typedef struct {
        char* bar;
      } MyStruct;
    DEFINE_STRUCT

    # Next define the allocation function that will
    # allocate and wrap a MyStruct struct when creating a
    # new Foo object. You might want to initialize the values
    # to avoid possible segfaults.
    builder.c_singleton <<-ALLOCATE
      VALUE allocate() {
        MyStruct* pointer = ALLOC(MyStruct);
        return Data_Wrap_Struct(self, NULL, free, pointer);
      }
    ALLOCATE

    # Finally we can use the struct_name and accessor methods.
    builder.struct_name = 'MyStruct'
    builder.accessor 'bar', 'char *'
  end

end

Note you can see the generated C code if you look under the directory .ruby_inline in your home directory.


text:
Q: Isotope won't reload onkeypress When i'm using onkeypress the isotope('reloadItems') won't reload the layout which means the textarea gets pushed under the item below. Can anyone help please? :] jsfiddle

        <textarea onkeypress="$('.main_trans_contain').isotope('reloadItems');" class='trans_comment'></textarea>

A: Use 'layout" instead of 'reloadItems'
jsFiddle
$(function() {

$('.trans_comment').css('overflow', 'hidden').autogrow();

$('.main_trans_contain').isotope({
itemSelector: '.item'
});

$('.trans_comment').on('input', function(){
$('.main_trans_contain').isotope('layout');
});

});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a possibility to make function working like a for loop? I was wondering if there is any way to write a custom method working as a "for" loop.
Because of very unusual iteration throught objects (well, not as usual as typical iteration) I' am forced to rewrite it every time I want to use it.
Sorry for my English and very unclear explaination, I'm not a very communicative person, but I think that sample below will explain my problem correctly.
The code below is not a real code, but just a scheme. Pointers and references can be used wrong but what I mean is to show my conception.
 class Element{
          Element *next;       // Pointer to the next object
          Element *previous;   // Pointer to the previous object
          // There are also some primitives (int, double etc.) there.

          void actionA(int a){ /* sth happpens to the primitives and may affect *next and *previous */ }
          void actionB(int b,int c){ /* just like above */ }
          // ............. and even more methods

    }

void makeActionA(int i){
       Element pointer=start.next;
       while(pointer!=end){
            Element tmp=pointer.next;
            pointer.actionA(i);          //X
            pointer=tmp;
        }
    }

void makeActionBC(int i,int j){
       Element pointer=start.next;
       while(pointer!=end){
            Element tmp=pointer.next;
            pointer.actionB(i,j);            //X
            pointer.actionC(i,j,i*j);        //X
            pointer=tmp;
        }
    }
    // AND SO ON

We can see that structers of makeAction methods are nearly the same except the lines marked with "X".
I want to make it shorter without stupid repeating like it is in a "for" loop.
   void custom_loop(Element pointer,Element start, Element end){
            pointer=start.next;
            while(pointer!=end){
                Element tmp=pointer.next;
                {
                        // Magical function that read the code between the brackets in code.
                }
                pointer=tmp;

            }
    }

And replace makeAction methods with more simple ones using the custom_loop
    void makeActionA(int i){
          Element t,s,e;
          custom_loop(t;s;e){
               t.actionA(i);
          }
    }

    void makeActionBC(int i,int j){
          Element t,s,e;
          custom_loop(t;s;e){
               t.actionB(i,j);
               t.actionC(i,j,i*j);
          }
    }

The only solution which comes to my mind are some magical tricks with metaprograming and macros.
I'm not really into them, but they won't scare me off.
I'm looking forward to the solution.
Many thanks.
And sorry for my English again.

A: In c++, you may do
template <typename F>
void makeElementAction(Element& element, F f){
   for (auto* pointer = &element; pointer != nullptr; pointer = pointer->next) {
       f(*pointer);
   }
}

With a call like
makeElementAction(root, [&](Element& element) { element.actionA(i); });

A: In Java you can implement interface Iterable, which allows you to iterate  "iterable" structures using for loop:
Element start = ...;
for (Element current : start) {
   // do something with current element
}

class Element implements Iterable<Element> {
    ...

    public Iterator<Element> iterator() {
        return new ElementIterator(this);
    }
}

class ElementIterator implements Iterator<Element> {
    private Element current;

    ElementIterator(Element start) {
        this.current = start;
    }

    public boolean hasNext() {
        return current != null;
    }

    public Element next() {
        Element result = current;
        current = current.next;
        return result;
    }
}

A: I've found an interesting structre.
It solves the problem also.
Loop looks that:
public static void loop(Element start, Element end, T t){
         for (Element pointer = start; pointer != end; pointer = pointer.next) {
              t.run(pointer);
          }
}
interface T{
    void run(Element pointer);
 }

And new methods look like that
void makeActionA(int i){
     loop(s,e,(pointer)-> pointer.actionA(i) );
 }

void makeActionBC(int i,int j){
     loop(s,e,(pointer)->{pointer.actionB(i,j); pointer.actionC(i,j,i*j);} );
 }

Links: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
     : http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html


text:
Q: Grails 3.1.1 with Java 8 time api in unit tests I cannot query domain classes in unit tests that use a field of type LocalDate.
I am trying to persist date and time values like LocalDate which were introduced in Java 8. Grails 3.1.1 and Gorm 5 are the stack. I already followed How to configure Grails 3.1.1 to use Hibernate 5 to make use of Hibernate 5.
I added compile "org.hibernate:hibernate-java8:5.0.7.Final" for the new type mappings of the date and time api. That works fine when running the app. Persist and load are possible.
Unit tests on the other hand crash. For example take this domain class:
class Event {
    String name
    LocalDate date
}

And this unit test:
void "test criteria with date"() {
    when:
    def c = Event.createCriteria()
    c.list {
        eq("date", LocalDate.now())
    }.each {
        println it
    }
    then:
    true
}

It crashes with this:
java.lang.IllegalArgumentException: Property [date] is not a valid property of class [localdate.Event]
at grails.gorm.CriteriaBuilder.validatePropertyName(CriteriaBuilder.java:1132)
at grails.gorm.CriteriaBuilder.eq(CriteriaBuilder.java:489)
at localdate.EventControllerSpec.test criteria with date_closure2(EventControllerSpec.groovy:31)
at localdate.EventControllerSpec.test criteria with date_closure2(EventControllerSpec.groovy)
at groovy.lang.Closure.call(Closure.java:426)
at groovy.lang.Closure.call(Closure.java:420)
at grails.gorm.CriteriaBuilder.invokeClosureNode(CriteriaBuilder.java:1157)
at grails.gorm.CriteriaBuilder.list(CriteriaBuilder.java:279)
at grails.gorm.CriteriaBuilder.list(CriteriaBuilder.java:52)
at localdate.EventControllerSpec.test criteria with date(EventControllerSpec.groovy:30)

My guess is that the new types are not available while testing as a unit test. On the other hand, the test works if it is done as an integration test.
I do not want to be forced to test all controller logic in integration tests. How to make the domain classes unit testable again?

A: The HibernateTestMixin as described in https://grails.github.io/grails-doc/latest/guide/testing.html#unitTestingDomains solved the problem. In the example given above I added:
@Domain(Event)
@TestMixin(HibernateTestMixin)

You also need an extra dependency:
testCompile 'org.grails:grails-datastore-test-support:5.0.1.RELEASE'


text:
Q: AWS CloudFront Custom domain name with HTTPS not working 1.I have a domain purchased through godaddy. I have set custom DNS and added 4 name servers generated by the hosted zone in AWS Route 53. DNS lookup through whois.net shows the correct values.
2.In Route 53, I have added an A record to the Alias Target xxxxxxxxxxxxxx.cloudfront.net. So the traffic hits Route 53 and goes to CloudFront.
3.In CloudFront, I have one distribution. As Alternate Domain Names (CNAMEs), I have the following values:
 *.domain.com / www.domain.com / domain.com
Under origins, I have one record with the following Origin Domain Name:
domain.com.s3-website.az-name-1.amazonaws.com
4.I am hosting website in an S3 bucket. All HTTP requests are set to redirect to HTTPS.
5.Lastly, I have created (US East (N. Virginia) region) and verified a single certificate for the following domain names: domain.com, www.domain.com, *.domain.com
I have read some answers that I should just wait and the custom SSL certificate option will become enabled. It's been more than day now, however, and there is no sign of that happening.
My website works in http mode, but not in https url. Any solution ...Please help...
PS. I am new to aws, please help me...

A: Can you confirm whether you have used ACM to generate the SSL certificate? Or you are using SSL certificate from other vendors?
STEP 1:
If you have generated the SSL Certificate from ACM, please make sure you did that with US East (N. Virginia) region. Because, CloudFront being an AWS service which is not tied to any specific region, it will use the certificates from US East region only.
STEP 2:
 1. Use the "Request or Import a certificate" option in CloudFront
 2. Select the certificate which you generated
 3. Complete the setup and try
If everything else is setup fine, you should be able to access the contents with HTTPS after the above step.
Let me know in case it didn't work

A: HTTPS settings was working perfectly as cloudfront url was working as expected so I realized it was just a DNS issue. All it took was an TYPE A record pointing to it.
Solution :
Add/edit proper "TYPE A" record with "Alias Target" as a cloudfront url.
Credit : Setup AWS S3 static website hosting using SSL (ACM)

A: For anyone else coming across this issue, the button was greyed out for me also and YES, I had requested the ACM cert in us-east-1.
The fix was to try in the Edge browser instead of Chrome.

A: For me the solution was very simple... I failed to add "Alternate Domain Name", once I did everything clicked.


text:
Q: WPF control performance What is a good (and preferably simple) way to test the rendering performance of WPF custom controls?  I have several complex controls in which rendering performance is highly crucial.  I want to be able to make sure that I can have lots of them drawwing out in a designer with a minimal impact on performance.

A: Tool called Perforator will help you.
See following article for details:
Performance Profiling Tools for WPF


text:
Q: How do I loop audio in a flash video? I'm making an animated presentation for a class and I need to have audio looping in the background of the presentation. So far I've figured out how to make it loop but the music stops at every point where I have stop(); - I'm thinking because the code affects the music too. How can I stop the presentation so that the text can be read but make sure the music keeps looping?
Thanks in advance, sorry if the answer is incredibly obvious.

A: If your audio is embedded within the timeline, set the "Sync" property in the Properties panel to "Event"
Or, you can add the song with code, like so...
Set the linkage of the sound in the library to "Music"
And add this code to wherever you want the music to start:
import flash.media.Sound;

var music:Sound = new Music();
music.play();


text:
Q: Expected value of random variable in word problem I have the following problem in my probability course. I am asked to compute the expected value of a random variable $X$ defined as follows:
Let $n \in \mathbb{N}$. In the first step a number $Y_1$ is randomly (uniformly distributed) chosen among $\{0, \ldots, n\}$. In the second step a number $Y_2$ is randomly chosen among $\{0, \ldots, Y_1\}$. This procedure is continued until the $0$ is drawn. Let $X$ be the number of steps necessary for this.
The solution to this exercise is given as:
Let $X_n$ be the number of steps necessary, when $\{0, \ldots, n\}$ is the first set. Let $n \geq 2$. If the first draw is $k \neq 0$, then the number of remaining steps has the same distribution as $X_k$ and thus
$$ \text{E}(X_n) = 1 + \sum_{k = 1}^n \text{E}(X_k) \cdot \mathbb{P}(Y_1 = k) ~~.$$
After that, some more derivation follows until an explicit formula for $X_n$ is derived. However, the stuff after the formular is clear.
My question is: How is this formula derived?
The formula would be true if
$$ X_n = 1 + \sum_{k = 1}^n X_k \mathbb{P}(Y_1 = k)$$
And, in fact, this was one explanation that was given on the blackboard, when this problem came up in a discussion.
However, since $\mathbb{P}(Y_1 = k) = \frac{1}{n+1}$, the right hand side may not even be an integer, while the left hand side is.
$X_n$, from the word problem, is presumably defined on $\Omega := \{0, \ldots, n\}^{\mathbb{N}}$ - I would not know what else would be a suitable space. But then for some $\omega \in \Omega$ we had
$$ X_n(\omega) = 1 + \sum_{k = 1}^n X_k(\omega) \mathbb{P}(Y_1 = k) ~~.$$
How would $X_k(\omega)$ even be defined for some $k < n$?


text:
Q: "Was it fun there?" or "How did you like there?" I am learning English. Once a friend is speaking her travel experience in a foreign country and I wanted to ask her how the experience is, did she enjoy it. So in this case, are these two sentences valid?

Was it fun there?
  How did you like there?
  How did you like X country?

Also, conversely, if my friend is travelling in my country and I'm local, I want to know if she likes my country. What should I ask? Is this sentence good?

Is it fun here?
  Do you like it here?

A: If your friend visited a foreign country, you could say any of the following.

A. "Was it fun there?" or even better "Did you have fun there?"
B. "How did you like it there?"

Note that it is possible for a person to have fun in a foreign country and not like the country at the same time. They might have had fun meeting their relatives and friends, doing certain activities, or going to some specific places. But they might not have liked the polluted environment, the road congestion, and the high price level.
Hence, if someone says they did not like "Country X", it does not necessarily mean they did not have fun there.

C. "How did you like "Country X"?"

If someone asked me that question, I would most likely start talking about the beauty of the country and the great things about the country. If you want to ask your friend about their daily debauchery, then "Did you have fun?" would be a better choice.
If your foreign friend is visiting your country, you could ask

D. "Do you like it here?" or "How are you liking it here so far?" or "How are you liking Country X so far?" or "What do you think of my country?"

But this to me is very awkward

E. "Is it fun here?"

Instead, you could ask

F. "So, are you having fun yet?"


text:
Q: Why do immediately invoked function and non-immediately invoked function behave differently when running return statement? I've encountered an instance of a difference between immediate invocation and non-immediate invocation of a function:
var x = (function foo() {
    return function() {
        console.log('something');
    }
})();
x();
//        logs 'something'

var x = function foo() {
    return function() {
        console.log('something');
    }
};
x();
x();
// no log at all

Why is there a difference here?
In all other cases, as far as I know, immediately and non-immediately invoked functions behave exactly the same.
I didn't find any documentation on this issue.

A: They don't behave differently in the sense that an IIFE is just a regular function call.
However in the first case, x refers to the result of the outer function being called, which is the inner function, while in the second case x refers to the outer function. Therefore in the second case you call the outer function twice, and the inner function gets returned, but you ignore that returned value. Do:
var inner = x();
inner(); // tadaa

A: var x = (function foo() {
    return function() {
        console.log('something');
    }
})();
x();
//        logs 'something'

First version immediately executes the function which returns another function which is stored at variable x. Then calling x() actually executes the internal function and somethign is logged.
var x = function foo() {
    return function() {
        console.log('something');
    }
};
x();
x();
// no log at all

Second version simply stores to variable x the external function. When calling x() it simply returns the internal function. Since that internal function is not stored or accessed anywhere, it is not called, hence nothing is logged.
What you could do (for second version):
y = x();
y(); // now logs something
// or equivalently
x()(); // now logs something

A: When you execute the second function expression, the expression is simply returning a reference to the inner function which is supposed to print something in the console. In other words, when x is executed it is not executing the returned function expression:
function() {
  console.log('something');
}

To do that you need to execute the returned expression by placing another pair of parenthesis ():

// x now has a reference to the outer function
var x = function foo() {
    return function() {
        console.log('something');
    }
};
//y has a reference to the inner function, as outer function has returned a ref to it
var y = x();
// To print in console, just execute the inner function
y();

In the case of IIFE, you already have the reference of the inner function when you invoke the IIFE:

//x now has a reference to the inner function
var x = (function foo() {
    return function() {
        console.log('something');
    }
})();
// you execute the inner function and print something in console
x();

A: in case 2 you are just setting x to equal a function that returns a NON invoked function you would need to invoke that function as well with x()()


text:
Q: VueJS transition-group is not working on images, how can I fade images? I'm trying to create an image slider, which fades the images. Image 1 should fade-out at the same moment as image 2 fades in. In other words: there shouldn't be a gap between them. Right now it does nothing like fading. The code is working, as so far that when the user clicks "next", the current images disappears, 0.9s later the next image appears. There is a delay of 0.9s between them (the same amount as declared in the CSS), so somehow it recognizes the transition time. It is only not fading, after clicking the button it immediately disappears. What am I missing?
My code
<template>

    <transition-group name='fade' tag='div'>

    </transition-group>
    ❮
  ❯

</template>

A: Change .fade-enter to .fade-enter-from.
See example

A: The position:absolute was messing things up here... Removed this line, now it works like a charm!


text:
Q: Брутфорс и потоки Не могу понять как работает многопоточный брутфорс. Допустим есть словарь для перебора:
aaa
bbb
ccc
ddd

Каким образом этот словарь распределяется по потокам? По половине? То есть если я запускаю 2 потока, в первом потоке будет aaa, bbb, во-втором — ccc, ddd?!


text:
Q: How do I sort an array of integers in php or JavaScript? Given an array of integers sort the array such that arr1 >= arr2 <= arr3 >= arr4 <= arr5 ... then return array
Example:
Given [1,2,3,4]
Possible results:
1: [2,1,4,3]
2: [4,1,3,2]

A: That's how I would implement it, the most naive way:
const arr = [4, 2, 1, 3, 5];

const sorted = arr.sort((a, b) => a - b);

const left = sorted.slice(0, sorted.length / 2);
const right = sorted.slice(sorted.length / 2);

const merged = [];

for (let i = 0; i < right.length; ++i) {
  merged.push(right[i]);
  if (i < left.length) {
    merged.push(left[i]);
  }
}

console.log(merged);

What it does:

*

*It first sorts the array, to ensure it's totally ordered

*Then it splits it to 2 sides, as evenly as possible: left and right. For odd count of items the right would be longer

*Then it merges them from either side one after another

Visual explanation:
Initial state:
left        right
[1, 2]      [3, 4, 5]

Merging:
Step 1:
left        right
[1, 2]      [4, 5]

merged
[3]

Step 2:
left        right
[2]         [4, 5]

merged
[3, 1]

Step 3:
left        right
[2]         [5]

merged
[3, 1, 4]

Step 4:
left        right
[]          [5]

merged
[3, 1, 4, 2]

Step 5:
left        right
[]          []

merged
[3, 1, 4, 2, 5]

A: Starting with a sorted array:
sort($numbers);

Append numbers to your result array by alternating between taking numbers from the beginning and end of the input array.
$i = 1;

// remove elements from $numbers array until it is empty
while ($numbers) {

    if ($i++ % 2) {

        // on odd iterations, pull an item from the end of $numbers (highest numbers)
        $result[] = array_pop($numbers);
    } else {

        // on even iterations, pull an item from the beginning of $numbers (lowest numbers)
        $result[] = array_shift($numbers);
    }
}


text:
Q: No weak derivative in singularity Let $\Omega := B_{\frac{1}{2}}(0) \subseteq \mathbb{R}^n$ and $n>1$. It is rather well known that $u: \Omega \setminus \lbrace 0 \rbrace \rightarrow \mathbb{R}$ lives in the Sobolev space $W^{1, n}(\Omega)$, where
$$
u(x) := \log \lvert \log \lvert x \rvert \rvert.
$$
This is in spite of the fact that $u$ can not be extended such that it is a function in $C^1(\Omega)$. An approximation argument can be applied to show weak differentiability while using that $u \in C^1(\Omega \setminus \lbrace 0 \rbrace)$.
Now, out of pure interest: Do you know an example of a function $f \in C^1(\Omega \setminus \lbrace 0 \rbrace)$ with $f, \nabla f \in L^p(\Omega)$ (for some $1 \leq p \leq \infty$) but that is not weakly differentiable, i.e. $f \notin W^{1, p}(\Omega)$?

A: When you write $\nabla f\in L^p(\Omega)$ I have to interpret it as the statement:

the classical gradient of $f$ on $\Omega\setminus\{0\}$ extended (say)
by zero to $\Omega$ is in $L^p(\Omega)$.

Then, in one dimension, consider on $\Omega\setminus\{0\}:=(-1,1)\setminus\{0\}$ the indicator function $\chi$ of $(0,1)$. Clearly $\chi$ is in $L^\infty(-1,1)$ as well as its classical gradient (which is identically zero). But the distributional derivative is a measure (Dirac measure). Therefore it is not in any of the Sobolev spaces $W^{1,p}(-1,1)$.
You can cook up similar examples in any dimension if you increase the dimension of the singular set. In fact, you are essentially asking when $W^{1,p}(\Omega)$ and $W^{1,p}(\Omega\setminus \{0\})$ are different. This should happen only in dimension one as the question is related to the capacity of a set (the capacity of the singleton $\{0\}$ here).


text:
Q: mysql show offset with query I have some data in my database
---------
| Name  | Offset(only for imagine it)
---------
| Aa    | 1
| Ab    | 2
| Ba    | 3
| Cf    | 4
| As    | 5
---------

when use this query
SELECT * FROM table LIMIT 1,3;

it must be show 3 of the first data, Aa, Ab, Ba, with offset like that.
Now, I want to selecting all of Name with prefix a, so use this query
SELECT * FROM table WHERE Name LIKE 'a%' LIMIT 1,3;

I want to show the result of that query with the offset, how to do this?
Loop it is not the solution I needed.
---------
| Name  | Offset(only for imagine it)
---------
| Aa    | 1
| Ab    | 2
| As    | 5
---------

Any help appreciated
Thank you!

A: You have it mostly correct. However, rows start at 0. So the answer: SELECT * FROM table WHERE Name LIKE 'a%' LIMIT 0,3
That SQL query will select everything in the table table that starts with the letter 'a' (or 'A').
For alphabetical order, use ORDER BY Name.


text:
Q: completionHandler / userCompletionHandler problem - Swift iOS I've got two functions below:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath)
    let message = self.messages[indexPath.row]

    // Set table cell values

    getUserFriendlyName(sid: message.sid!, arg: true, completion: { (success) -> Void in

        cell.detailTextLabel?.text = self.friendly_name
        cell.textLabel?.text = message.body
        cell.selectionStyle = .none
        //self.tableView.reloadData()
    })

    return cell
}

and
func getUserFriendlyName(sid: String, arg: Bool, completion: @escaping (Bool) -> ()) {

    let ACCOUNT_IDENTITY: String = "AC***redacted"
    let AUTH_TOKEN: String = "**redacted"
    let SERVICE_ID: String = "IS***redacted"

    let loginString = "\(ACCOUNT_IDENTITY):\(AUTH_TOKEN)"

    let loginData = loginString.data(using: String.Encoding.utf8)

    let base64LoginString = loginData!.base64EncodedString()

    let url = URL(string: "https://chat.twilio.com/v2/Services/IS***redacted/Users/US***redacted")

    var request = URLRequest(url: url!)
    var session = URLSession.shared
    request.httpMethod = "GET"
    request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    //request.addValue(AUTH_TOKEN, forHTTPHeaderField: "Authorization")
    var fn: String!
    let task = session.dataTask(with: request, completionHandler: { data, response, error in
        var strData = String(data: data!, encoding: String.Encoding.utf8)
        print("Body: \(strData)")
        guard error == nil else {
            print(error!)
            return
        }
        guard let data = data else {
            print("Data is empty")
            return
        }

        let json = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary

        //getting the json response
        print(json)
        fn = json["friendly_name"] as! String?
        self.friendly_name = fn

        completion(arg)
        //return fn
        //print(fn)
    })

    task.resume()

}

Here's the problem I'm running into... When a new chat message is detected, the tableView function gets called. A new cell is created with text and subtext. Because the native Twilio code doesn't allow me to display the friendly name of who wrote the chat, I have to go and make an HTTP call, so I call getUserFriendlyName(). Because resumeTask() is asynchronous, the flow of the program goes like this:

*

*tableView function is entered

*I make the call to the getUserFriendlyNameFunction(), which gets entered

*When we get to the HTTP request, resumeTask() is called and then the flow returns back to the tableView function, specifically the end of the call to the friendly user name function and it executes the return Cell line, which means the cell is created but contains the prototype data, namely "Title" for the text and "Subtitle" for the description text.

*The flow then goes back to the HTTP request and it gets executed

*The flow returns to the line of code directly after the call to getUserFriendlyName() inside the tableView function. That code sets the text and detail text values to the data returned by the HTTP call. But at this point, the cell already exists in my tableView. So I'm left with just a cell containing "Text" and "Subtext".

What I've tried:

*

*Adding tableView.reloadData() after the final lines of code in the tableView function are executed. This did not update the tableView with the data from the HTTP call. In fact, it continually refreshed the tableView over and over again.

*Moving the final three lines of code to the same spot as the "return Cell" line. This also did not work.
I've come to believe my only hope is/are completionHandler / userCompletionHandler. I've played around with them for a long time and cannot get the desired outcome, which would be to have the first incoming chat message populated with the data from the HTTP request.
Can anyone help?

A: When you receive a message don't add it directly to messages array but first call
// this goes inside some function not cellForRowAt

let message =  // received

getUserFriendlyName(sid: message.sid!, arg: true, completion: { (success) -> Void in
       message....// set all needed properties
       self.messages.append(message)
       self.tableview.reloadRows(at:[IndexPath(row:messages.count - 1,section:0)],with:.none)
}

Don't do any asynchronous work inside cellForRowAt as it'll be be done every scroll , in addition it doesn't display the full data at the same time

Completion of session.dataTask(with: request  is in a background thread so consider
DispatchQueue.main.async {
  completion(arg)
}

You make self.friendly_name
self.friendly_name = fn

A vc property while it should be a property for every message object so not to mix with other messages senders


text:
Q: Which method is better for display terrain in OpenLayers? I want to display terrain in OpenLayers.
So, I tried to use dem(.img) and convert it to dem(.jpg) on QGIS.
But, the effect is very bad.
My expected effect is (This picture is captured from google earth)

Which method is better for display terrain in OpenLayers?
This is my website for test:http://www.cv.nctu.edu.tw/shapefile-js-openlayers/ol_simple.html

A: If you don't want/have a server side map rendering engine, I'd convert the image to a tileset with a convenient palette.
For example you can use gdal2tiles.py script but it needs as a source an image with the palette applied so your source wouldn't be a DEM but a regular RGB image (height values have to be mapped to colors). This step can be done with gdaldem tool.
Not sure, but maybe you can do all those steps also in QGIS.

A: I'd recommend looking in TileMill to create an mbtiles file, which you can then unpack into a standard tileset.  You can style imagery very nicely in TileMill, and then export with your chosen number of zoom levels.
You could pull imagery into TillMill also, and get the google earth look by putting a semi-transparent hillshade on top of it.  Basically, you can add vectors and rasters to TileMill, and do complex, zoomlevel specific styling to them, and get a tileset as the output.


text:
Q: File writing from multiple threads. I have an application A which calls another application B which does some calculation and writes to a file File.txt
A invokes multiple instances of B through multiple threads and each instances tries to write to same file File.txt
Here comes the actual problem :
Since  multiple threads tries to access the same file , the file access throws out which is common.
I tried an approach of using a concurrent queue in a singleton class and each instances of B adds to the queue And another thread in this class takes care of dequeing the items from queue and writes to the file File.txt. The queue is fetched synchronously and write operation succeeded . This works fine .
If I have too many threads and too many items in queue the file writing works but if for some reason my queue crashes or stops abruptly all the information which is supposed to be written to file is lost .
If I make the file writing synchronous from the B without using the queue then it will be slow as it needs to check for file locking but here there are less chances of data being missed as after B immediately writes to file.
What could be there best approach or design to handle this scenario? I don't need the response after file writing is completed . I can't make B wait for the file writing to be completed.
Would async await file writing could be of any use here ?

A: I think what you've done is the best that can be done.  You may have to tune your producer/consumer queue solution if there are still problems, but it seems to me that you've done rather well with this approach.
If an in-memory queue isn't the answer, perhaps externalizing that to a message queue and a pool of listeners would be an improvement.
Relational databases and transaction managers are born to solve this problem.   Why continue with a file based solution?  Is it possible to explore an alternative?

A:
is there a better approach or design to handle this scenario?

You can make each producer thread write to it's own rolling file instead of queuing the operation. Every X seconds the producers move to new files and some aggregation thread wakes up, read the previous files (of each producer) and writes the results to the final File.txt output file. No read / write locks are required here.
This ensures safe recovery since the rolling files exist until you process and delete them.
This also mean that you always write to disk, which is much slower than queuing tasks in memory and write to disk in bulks. But that's the price you pay for consistency.

Would async await file writing could be of any use here ?

Using asynchronous IO has nothing to do with this. The problems you mentioned were 1) shared resources (the output file) and 2) lack of consistency (when the queue crash), none of which async programming is about.

Why the async is in picture is because I dont want to delay the existing work by B because of this file writing operation

async would indeed help you with that. Whatever pattern you choose to implement (to solve the original problem) it can always be async by merely using the asynchronous IO api's.


text:
Q: BackgroundWorker never does anything? This is the code that I am trying to execute, but stepping through my code I never see any progress indicated or updated on my windows form showing progressbar1.  This is my 1st attempt in getting a background worker to function properly, and all I have is a windows form with one button on it and this is all of the code involved in the project.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    private int i = 0;

     public Form1()
    {
        InitializeComponent();
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.WorkerSupportsCancellation = false;
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
    }

    private void button1_Click(object sender, EventArgs e)
    {
            backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        ReadySteadyGo();
        worker.ReportProgress((i * 10));
        FinalizeAndFinish();
        worker.ReportProgress((i * 10));
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        progressBar1.Text = "Done!";
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Text = (e.ProgressPercentage.ToString() + "%");
    }

    private void ReadySteadyGo()
    {
        Thread.Sleep(100000);
    }
    private void FinalizeAndFinish()
    {
        Thread.Sleep(1000);
    }
}

A: It appears that you are using Thread.Sleep() to simulate a long-running operation.  There are a few things you should consider based on your code example:
When the backgroundWorker1.RunWorkerAsync(); is executed, it starts working on another thread.  Thus, if you are debugging interactively and you have not set a breakpoint in the backgroundWorker1_DoWork method, you are not likely to see this code execute.
When the Thread.Sleep(100000) executes, it essentially means that the background worker will pause for 100 seconds - so you need to make sure you are waiting at least that long to see the UI updated.
Also, as per Hans Passant's comment, consider the following:

Nor can you see it doing anything, there's no point to assigning the
  ProgressBar.Text property since it doesn't display text. Set Value
  instead.

A: I recreated your example in Visual Studio and am hitting a breakpoint in backgroundWorker1_DoWork so the multi-threading is working properly, you just need to do proper processing?
    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 1; i <= 100; i++)
        {
            backgroundWorker1.ReportProgress(i);
            Thread.Sleep(100);
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }


text:
Q: Profiling C++/CLI NUnit tests Is it possible to profile C++/CLI NUnit tests with Visual Studio 2012?
The Profiler always wants to have an Executable.

A: No it is possible. The testrunner is attachable for debugging.


text:
Q: XMPP Server and Custom APIs I have a scenario , where i need a Chat client for android and iOS and a XMPP server either setup privately or hosted. I need to call three APIs from mobile app (chat client) and from web based app.
1) Need API that can register a new user with XMPP server so in future if there is call from chat client to xmpp server, server can recognize it.(mobile app will call this api)
2) Need API that can create chat groups. (web based app will call this api)
3) Need API that can add user to chat groups and can create session for the user for particular chat group (mobile app will call this api)
Do i need to create above APIs as custom APIs in some existing XMPP server or i need to create my own xmpp server ?
Please suggest any good XMPP server which fulfill my requirement.
I am not sure how can i proceed with above requirement.
Note that i would need it in .net technology.

A: As server, you can use more or less what you want.
For sure Openfire and Ejabber are largly used and supports more or less all XMPP specs.
About API: you have 2 choices:

*

*get "best" API for each platform, so do for each platform you
need it's own client (best as performance)

*use a javascript API and wrap a HTML + JS client in your
declied-platform application.

This is the list of API:
https://xmpp.org/software/libraries.html
it's hard to suggest something particoular due to varius linceses.
As I know, Smack it's a very complete API and works with Android: it's not that easy to use, but Bubbler is (even if not all it's supported).
About js:
strophe.js supports chat and groupchat
About session: it's 75% Server and 25% API. Api just require connect and login, server will store the session.
About creation: Smack does, have to check for others API.
However write this kind of function it's not that hard (XMPP require a fixed template XML, just replicate this XML). Of course it's better to have something already cooked, tested and ready but a single functionality can be developed in short time.


text:
Q: How to Configure multiple sites locally? I have set up wamp locally on my machine but i want to view multiple sites locally when i need to.
So far I have entered the following code in the hosts file
# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost

127.0.0.1   mysitesname

How can i have multiple sites at once? is this possible?

A: Configure name based virtual hosting, for example
# Only needed once.
NameVirtualHost *:80

# One section for each virtual host. Must
# match the "NameVirtualHost" directive.
<VirtualHost *:80>
    # The FQDN of the host.
    ServerName mysitesname

    # The file system path to the directory with
    # the files to serve by this virtual host.
    DocumentRoot /www/mysitesname
</VirtualHost>


text:
Q: add attachment pipeline in nest 7 I have class like this:
public class Document
{
    public string Id { get; set; }
    public string Content { get; set; }
    public Attachment Attachment { get; set; }
}

and context is read from a file (e.g. pdf) like so:
Content = Convert.ToBase64String(File.ReadAllBytes(location))

when I write a bunch of documents like so:
var bulkResponse = client.Bulk(b => b
    .Pipeline("attachments")
    .IndexMany(documents)
);

I get:
"pipeline with id [attachments] does not exist"

Similar code used to work but I now switched to Nest 7?
I use this code to create my index (used to work):
client.Indices.Create(indexName, c => c
    .Settings(s => s
    .Analysis(a => a
        .Analyzers(ad => ad
        .Custom("windows_path_hierarchy_analyzer", ca => ca
            .Tokenizer("windows_path_hierarchy_tokenizer")
        )
        )
        .Tokenizers(t => t
        .PathHierarchy("windows_path_hierarchy_tokenizer", ph => ph
            .Delimiter('\\')
        )
        )
    )
    )
    .Mappings(m => m
    .Map<Document>(mp => mp
        .AutoMap()
        .AllField(all => all
        .Enabled(false)
        )
        .Properties(ps => ps
        .Object<Attachment>(a => a
            .Name(n => n.Attachment)
            .AutoMap()
        )
        )
    )
    )
);

I also came across something like this, which may be used to define attachment pipeline?
client.PutPipeline("attachments", p => p
                .Description("Document attachment pipeline")
                .Processors(pr => pr
                    .Attachment<Document>(a => a
                        .Field(f => f.Content)
                        .TargetField(f => f.Attachment)
                    )
                    .Remove<Document>(r => r
                        .Field(f => f.Content)
                    )
                )
            );

PS:
This may work:
client.Ingest.PutPipeline("attachments", p => p
                .Description("Document attachment pipeline")
                .Processors(pr => pr
                    .Attachment<Document>(a => a
                        .Field(f => f.Content)
                        .TargetField(f => f.Attachment)
                    )

A: Here's a complete example, updated from the Elastic blog post that targeted Elasticsearch 2.x, using NEST 2.x
using System;
using Elasticsearch.Net;
using Nest;

namespace Example
{

    private static void Main()
    {
        var defaultIndex = "attachments";
        var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

        var settings = new ConnectionSettings(pool)
            .DefaultIndex(defaultIndex)
            .DisableDirectStreaming()
            .PrettyJson()
            .OnRequestCompleted(callDetails =>
            {
                if (callDetails.RequestBodyInBytes != null)
                {
                    Console.WriteLine(
                        $"{callDetails.HttpMethod} {callDetails.Uri} \n" +
                        $"{Encoding.UTF8.GetString(callDetails.RequestBodyInBytes)}");
                }
                else
                {
                    Console.WriteLine($"{callDetails.HttpMethod} {callDetails.Uri}");
                }

                Console.WriteLine();

                if (callDetails.ResponseBodyInBytes != null)
                {
                    Console.WriteLine($"Status: {callDetails.HttpStatusCode}\n" +
                             $"{Encoding.UTF8.GetString(callDetails.ResponseBodyInBytes)}\n" +
                             $"{new string('-', 30)}\n");
                }
                else
                {
                    Console.WriteLine($"Status: {callDetails.HttpStatusCode}\n" +
                             $"{new string('-', 30)}\n");
                }
            });

        var client = new ElasticClient(settings);

      if (client.Indices.Exists(defaultIndex).Exists)
      {
        var deleteIndexResponse = client.Indices.Delete(defaultIndex);
      }

        var createIndexResponse = client.Indices.Create(defaultIndex, c => c
            .Settings(s => s
                .Analysis(a => a
                    .Analyzers(ad => ad
                        .Custom("windows_path_hierarchy_analyzer", ca => ca
                            .Tokenizer("windows_path_hierarchy_tokenizer")
                        )
                    )
                    .Tokenizers(t => t
                        .PathHierarchy("windows_path_hierarchy_tokenizer", ph => ph
                            .Delimiter('\\')
                        )
                    )
                )
            )
            .Map<Document>(mp => mp
                .AutoMap()
                .Properties(ps => ps
                    .Text(s => s
                        .Name(n => n.Path)
                        .Analyzer("windows_path_hierarchy_analyzer")
                    )
                    .Object<Attachment>(a => a
                        .Name(n => n.Attachment)
                        .AutoMap()
                    )
                )
            )
        );

      var putPipelineResponse = client.Ingest.PutPipeline("attachments", p => p
        .Description("Document attachment pipeline")
        .Processors(pr => pr
          .Attachment<Document>(a => a
            .Field(f => f.Content)
            .TargetField(f => f.Attachment)
          )
          .Remove<Document>(r => r
            .Field(ff => ff
              .Field(f => f.Content)
            )
          )
        )
      );

      var base64File = Convert.ToBase64String(File.ReadAllBytes(@"C:\Users\russc\Dropbox\Other Linqpad queries\example_one.docx"));

      var indexResponse = client.Index(new Document
      {
        Id = 1,
        Path = @"\\share\documents\examples\example_one.docx",
        Content = base64File
      }, i => i
        .Pipeline("attachments")
        .Refresh(Refresh.WaitFor)
      );

      var searchResponse = client.Search<Document>(s => s
        .Query(q => q
        .Match(m => m
          .Field(a => a.Attachment.Content)
          .Query("NEST")
        )
        )
      );

      foreach(var hit in searchResponse.Hits)
      {
        var attachment = hit.Source.Attachment;
        Console.WriteLine($"Attachment details for doc id {hit.Id}");
        Console.WriteLine($"date: {attachment.Date}");
        Console.WriteLine($"content type: {attachment.ContentType}");
        Console.WriteLine($"author: {attachment.Author}");
        Console.WriteLine($"language: {attachment.Language}");
        Console.WriteLine($"content: {attachment.Content}");
        Console.WriteLine($"content length: {attachment.ContentLength}");
      }
    }

    public class Document
    {
        public int Id { get; set; }
        public string Path { get; set; }
        public string Content { get; set; }
        public Attachment Attachment { get; set; }
    }

}


text:
Q: Python: Printing out result from conditional for loop I have a simple question. I have a small dataframe:
      Column1  Column2  Column3
Row1        0        4        6
Row2        1        3        5
Row3        0        4        2

I need to only print out only Column1 and Column2 only if Column1 equals 1:
      Column1  Column2
Row2        1        3

I have this piece of code that I am stuck at:
col=[col for col in df.columns if col=="Column1" or col=="Column2"]
print(loc[:,col])

This is printing out the result such that we are having Column1 and Column2 with all the values.
      Column1  Column2
Row1        0        4
Row2        1        3
Row3        0        4

How can I incorporate the condition such that Column1==1?
Thanks!

A: Two of the easiest ways to do this are to use .loc with boolean indexing and query with column filtering:
Method 1:
df.loc[df.Column1 == 1,['Column1','Column2']]

Output:
      Column1  Column2
Row2        1        3

Method 2:
df.query('Column1 == 1')[['Column1','Column2']]

Output:
      Column1  Column2
Row2        1        3

A: You can use a conditional index:
>>> df[df['Column1'] == 1]
      Column1  Column2  Column3
Row2        1        3        5

Then just select the columns you want:
>>> df[df['Column1'] == 1][['Column1', 'Column2']]
      Column1  Column2
Row2        1        3

A: You can use the namedtuple of python to do this. Namedtuple creates individual single classes to represent the values. It is worth remembering that classes have only values and no method.
would be like this:
from collections import namedtuple

Value = namedtuple('Value', ['column', 'line', 'value'])

examples = [Value(column, line, value) for column in range(3)
                                       for line in range(2)
                                       for value in range(2)]

>>> examples
[Value(column=0, line=0, value=0), Value(column=0, line=0, value=1), Value(column=0, line=1, value=0), Value(column=0, line=1, value=1), Value(column=1, line=0, value=0), Value(column=1, line=0, value=1), Value(column=1, line=1, value=0), Value(column=1, line=1, value=1), Value(column=2, line=0, value=0), Value(column=2, line=0, value=1), Value(column=2, line=1, value=0), Value(column=2, line=1, value=1)]

for _ in examples:
  if _.column == 1:
    print('Line: %s' % _.line, 'Value: %s' % _.value)

Line: 0 Value: 0
Line: 0 Value: 1
Line: 1 Value: 0
Line: 1 Value: 1


text:
Q: Cannot import matplotlib with ipython/jupyter notebook Cannot import matplotlib with ipython/jupyter notebook through a virtual environment.
I'm able to import matplotlib just fine using the console. Having seen other SO posts I can't seem to get this set up right.
I followed this to get the separate ipython/jupyter kernel.
When I checked my locations through jupyter I get
six.__file__: '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six.pyc'
and
datutil.__file__: '/Library/Python/2.7/site-packages/dateutil/__init__.pyc'
I am not sure these are correct. Main jupyter error below
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-3-20188fbdb2fd> in <module>()
      1
----> 2 import matplotlib.pyplot as plt
      3 get_ipython().magic(u'matplotlib inline')

/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/pyplot.py in <module>()
     27 from matplotlib import docstring
     28 from matplotlib.backend_bases import FigureCanvasBase
---> 29 from matplotlib.figure import Figure, figaspect
     30 from matplotlib.gridspec import GridSpec
     31 from matplotlib.image import imread as _imread

/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/figure.py in <module>()
     34 import matplotlib.colorbar as cbar
     35
---> 36 from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
     37 from matplotlib.blocking_input import BlockingMouseInput, BlockingKeyMouseInput
     38 from matplotlib.legend import Legend

/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py in <module>()
     18 import matplotlib.colors as mcolors
     19 import matplotlib.contour as mcontour
---> 20 import matplotlib.dates as _  # <-registers a date unit converter
     21 from matplotlib import docstring
     22 import matplotlib.font_manager as font_manager

/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/dates.py in <module>()
    117
    118
--> 119 from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
    120                             MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
    121                             SECONDLY)

/Library/Python/2.7/site-packages/dateutil/rrule.py in <module>()
     17
     18 from six import advance_iterator, integer_types
---> 19 from six.moves import _thread
     20 import heapq
     21

ImportError: cannot import name _thread

A: Ok I fixed this by using the tutorial properly (http://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs)
You need to set up a virtualenv, then make sure that you install jupyter within it. I was using the globally installed jupyter.
Then set up the new jupyter kernel (linked above) and everything should work with your virtualenv pointed to correctly


text:
Q: Exception during JDBC SSL connection with Oracle I've followed this document but unable to setup SSL JDBC connection. Getting exception

java.sql.SQLRecoverableException: IO Error: An established connection was aborted by the software in your host machine, connect lapse 16 ms., Authentication lapse 0 ms.
at oracle.jdbc.driver.T4CConnection.handleLogonIOException(T4CConnection.java:915)

Currently my getConnection method looks as below: Can someone point me what is going wrong here?
public static java.sql.Connection getConnection(String user, String password) throws MalformedURLException, InstantiationException, IllegalAccessException, ClassNotFoundException
    {
        String trustStoreWalletPath="C://input//cwallet.sso" , keyStoreWalletPath="C://input//cwallet.sso";
        Security.addProvider(new oracle.security.pki.OraclePKIProvider());
        Security.insertProviderAt(new oracle.security.pki.OraclePKIProvider(),3);
        Properties property = new Properties();
        property.setProperty("oracle.net.authentication_services","(TCPS)");
        property.setProperty("javax.net.ssl.trustStore", trustStoreWalletPath);//
        property.setProperty("javax.net.ssl.trustStoreType", "SSO");
        property.setProperty("javax.net.ssl.keyStore", keyStoreWalletPath);
        property.setProperty("javax.net.ssl.keyStoreType", "SSO");
        String url = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=xx.dm.xyz.com)(PORT=2484))(CONNECT_DATA=(SERVICE_NAME=xx.dm.xyz.com)))";
        property.setProperty("user", user);
        property.setProperty("password", password);

        try {
            Connection c = DriverManager.getConnection(url, property);
            return c;

        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

Found a SOF link but not answered. But this is exactly what I am trying.

A: Can you specify the JDBC driver version and database server version that you are using? Also, are you using oraclepki.jar, osdt_core.jar and osdt_cert.jar in the classpath? You can check out SSL blog for 12.2 and lower

A: I know that Nirmala is supporting you as expected. However, beyond Oracle's official resources, there's a nice one here that might help you - https://www.thesslstore.com/blog/activate-ssl-oracle-jdbc-thin-driver/
Below you can find tips concerning how to debug SSL/TLS connections from the official Java SE docs as well.
https://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/ReadDebug.html


text:
Q: How do I increase axis labels and legend size in ggplot2? I want my axis labels and legend to look bigger and I want to increase font size
My code:

ggplot(data.frame(x = c(-2, 2)), aes((x),xname ='wind') ) +
    stat_function(fun = dnorm, args = list(mean = -0.05116279, sd = 0.5725349),                                                  aes(colour = "1 hour"))  +xlab("wind_speed_Error",cex.lab=1.5, cex.axis=1.5) +
    stat_function(fun=dnorm, args = list(mean = -0.355, sd = 0.6602059),  aes(colour = "4 hour"))  +
    scale_colour_manual("Predictions",values=c("blue","red"))

A: You can use theme to access title and legend font sizes as below.
library(ggplot2)
library(scales)
ggplot(data.frame(x = c(-2, 2)), aes((x), xname ="wind")) +
  stat_function(fun = dnorm, args = list(mean = -0.05116279, sd = 0.5725349), aes(colour = "1 hour"))  +
  stat_function(fun=dnorm, args = list(mean = -0.355, sd = 0.6602059),  aes(colour = "4 hour"))  +
  scale_colour_manual("Predictions", values=c("blue","red")) +
  xlab("wind_speed_Error") +
  theme(axis.title.x = element_text(size = rel(1.5)),
        legend.text = element_text(size = rel(1.5)),
        legend.title = element_text(size = rel(1.5)))


text:
Q: Usage of Thread.currentThread().getContextClassLoader().getResourceAsStream("system.properties") In my web application, I have kept system.properties file in the web-inf/classes folder.
To Access that file's inputstream, I am using the code snippet below:
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(SYSTEM_PROPERTIES_FILE)

Is there any other way to access that file?

A: It simply means: Return the property file as InputStream from the ClassLoader the current thread of my application is running from (in loose english).


text:
Q: Do I need to configure a development device to test Apple Push Notification and Update of my Pass I am creating a passbook server in ruby on rails.
No problem to generate,download and remove a valide pkpass on my Iphone.
However, when I use this project https://github.com/nomad/houston to implement apple push notification I can't get the notification my web app sent.
Anymore, when I use this project https://github.com/mattt/passbook_rails_example/blob/master/app/controllers/passbook/passes_controller.rb to implement update of my pass, this last is not modified after an update.
Apparently, my device needs to maintain a stable connection between my device and APNS. So my question is: Do I have to create a development provisioning profile to register my device? Or is this supposed to work with any device?

A: To use non-https, you have to put your device into developer mode using Xcode and then in settings on the device there is a new setting to allow non-secure passbook URLs.


text:
Q: Nuget package failing on Install and on push I recently created a huge NuGet package (more than 2000 files, most of them just Content, and 15Mb). Creating a NuSpec and packing it worked fine.
Then I went to a next step: testing it.
First I tried intalling it locally, but the installation failed after installing all dependencies and couldn't install the package itself. Rollback happened.
Then I uploaded to the local server, just to be sure the problem wasn't Visual Studio trying to find the package, and it failed. I searched on how to get more details on the error and used this command line:
nuget push MyPackage.1.0.0.nupkg -Source "http://localhost/myserver/api/v2/package" "API-KEY" -Verbosity detailed -ForceEnglishOutput
The return is as follows:
Pushing MyPackage.1.0.0.nupkg to 'http://localhost/myserver/api/v2/package'...
  PUT http://localhost/myserver/api/v2/package/
  InternalServerError http://localhost/myserver/api/v2/package/ 645ms
  PUT http://localhost/myserver/api/v2/package/
  InternalServerError http://localhost/myserver/api/v2/package/ 315ms
  PUT http://localhost/myserver/api/v2/package/
  InternalServerError http://localhost/myserver/api/v2/package/ 277ms
System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at NuGet.Protocol.Core.Types.PackageUpdateResource.<>c.<PushPackageToServer>b__21_3(HttpResponseMessage response)
   at NuGet.Protocol.HttpSource.<ProcessResponseAsync>d__14`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.Core.Types.PackageUpdateResource.<PushPackageToServer>d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.Core.Types.PackageUpdateResource.<PushPackageCore>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.Protocol.Core.Types.PackageUpdateResource.<PushPackage>d__14.MoveNext()

Could you help me figure it out what the problem is? Sadly I can't post the package for privacy issues (I'm developing for the company I work in).

A: Have encountered a similar error and again it was the same 500
and the error message was not helpful.
2019-08-20T09:29:15.4059254Z System.AggregateException:
One or more errors occurred. ---> System.Net.Http.HttpRequestException:
Response status code does not indicate success: 500 (Internal Server Error).

In this case the culprit was the Outopus Deploy server,
which was running out of disk space.
Freed up disk space from deleting the old packages and was able to resolve it smoothly.
Alternatively you may increase the volume size (if it is a cloud storage like AWS EBS).


text:
Q: How to change Chore properties in cognos-tm1 process? I need to turn on\off chore or change it's start time during proceess regarding some conditions, how can i do this?

A: Not sure if it's possible by using TI. It might be possible through REST API.
But you may store chore time of execution in the cube. And create a special chore which would check condition (cube cell value = current time) in  every minute/two and run target process.


text:
Q: SQL View with LIKE? I get data from 3 tables into a view:
SELECT
    ROW_NUMBER() OVER (ORDER BY dbo.A.[key] DESC) AS ID,
    dbo.A.[key], dbo.B.ARBPL,
    dbo.A.[rssi_mittelwert (dBm)], dbo.A.[rssi_varianz (dBm)],
    dbo.A.[rssi_standardabweichung (dBm)],
    dbo.A.[snr_mittelwert (dB)], dbo.A.[snr_varianz (dB)],
    dbo.A.[snr_standardabweichung (dB)],
    dbo.A.Zeitstempel
FROM
    dbo.C
LEFT OUTER JOIN
    dbo.B ON dbo.C.LastKnownRelation = dbo.B.[Arbeitsplatz Alias]
RIGHT OUTER JOIN
    dbo.A ON dbo.C.SwitchId = dbo.A.[key]
WHERE
    (dbo.C.Active = 1) AND (dbo.B.ARBPL IS NOT NULL)

My question is: how can I make a LIKE there, which means, its like this:
WHERE dbo.C.LastKnownRelation LIKE '%dbo.B.[Arbeitsplatz Alias]%'

so if Arbeitsplatz Alias = Football AUS/ES and my LastKnownRelation = Football AUS, it should return the result of the ARBPL because the LIKE is true.

A: It is not possible to filter because the view "hides" the tables that make it up. If you want to apply a filter like that, you must return the value in the view.


text:
Q: Algebraic geometry additionally equipped with field automorphism operation I am looking for some facts on theory, which is essentially algebraic geometry but with field automorphisms added as 'basic' operations. (Precisely, I mean universal algebraic geometry for (universal) algebra being a field $\mathbb{F}$ and operations being polynomials and field automorphisms) I am also interested in computational aspects.
I am mainly interested in case of field of multivariate rational functions, i.e. $\mathbb{F} = K(x,y)$.
An algebraic set in such setting could be $$\{(f,g) \in (K(x,y))^2 \mid x^2-y^2-f \cdot g(x=\frac{x+y}{2}, y = \frac{x-y}{2}) = 0\}.$$ and ideals are additionally closed under field automorphisms.
I would be grateful for reference to any source that considers theory like this, also the computational aspects.

A: You should look into difference algebra, which is exactly this setting.  (It's called difference algebra because the most classical version looked at the automorphism on polynomials that sends $f(x)$ to $f(x+1)$, which can be used to state the theory of difference equations.)
The hottest area in this is the study of the model theory of fields with automorphisms.  Zoe Chatzidakis has some lecture notes on the subject.


text:
Q: compact set in a space of functions continuous in $\mathbb{R}$ As it is known the set $\mathcal{B}=\{ f:\mathbb{R}\rightarrow \mathbb{R} : f \mbox{  is continuous}\}$ it is not a metric space with the metric $d(f,g)=sup_{x\in \mathbb{R}}\| f(x)-g(x)\|$ it can take the infinite value. But it is possible to make a decomposition
$$\mathcal{B}=\bigcup_{f} (\mathcal{B}_f,d)$$
where $(\mathcal{B}_f,d)$ is a metric space and $\mathcal{B}_f=\{ h\in \mathcal{B}: d(f,h)<\infty\}$. I wonder if there is a "metric" (so it is with infinite values) $d^{\prime}$ in $\mathcal{B}$ such that

If $K$ is compact in $(\mathcal{B},d^{\prime})$ then $K\subset \mathcal{B}_f$ for some $f\in \mathcal{B}$ and $(K,d)$ is compact (metric of $\mathcal{B}_f$).

I do not know much about metric take infinite values, but they said they do exist and that there is the solution. thank you in any suggestions or comments.


text:
Q: Converts a number into a series of numbers I want to generate a random number
And fill in matrix elements
I want to get every part of the number separately
And filling the parts of the matrix with the parts of the number
For example
random number = 12340;
I want to get the numbers 1 , 2 , 3 , 4 , 0
int []c = new int[5];

c[0] = 1; c[1] = 2; c[2] = 3; c[3] =4; c[4] =0;
But I cannot get every part of the number separately

A: Using Linq for positive integers
var random = new Random();
int count = 5;
int max = (int)Math.Pow(10, count);
int number = random.Next(0, max);
var list = number.ToString(new string('0', count)).Select(c => char.GetNumericValue(c));
var digits = list.ToArray();
Console.WriteLine(number + " => " + string.Join(" ", digits));

Output
32409 => 3 2 4 0 9

123 => 0 0 1 2 3

Explanation
We generate the max value that can fit in the array of count cells (+1).
For count = 5, we generate numbers between 0..99999 thanks to the Pow.
We convert it to a string and select each char converted in its numeric value.
The use of new string('0', count) ensure that we will have 5 digits no matter the generated number: for example 50 will be 00050 and all cells of the array will be filled to match the required size. But if the size of this array may be less than the max count to just have the real digits, it is not needed and will produces:
32409 => 3 2 4 0 9

123 => 1 2 3

To have the expected array we apply the convert method on the resulting query.

A: You could use string conversion for it (matrix) or numeric (matrix2):
        // Via string
        int rndNum = 12345;
        string rndNumStr = "" + rndNum;
        char[] matrix = rndNumStr.ToCharArray();

        Console.WriteLine("|" + string.Join("|", matrix) + "|");

        // Numerically
        int rnd = 12345;
        int maxDigits = 10;     // You could calc the max digits too
        int[] matrix2 = new int[maxDigits + 1];
        int p = 0;

        for (int i = maxDigits; i >= 0; i--) {
            double rs = rnd / Math.Pow(10, i);
            int fl = (int) Math.Floor(rs);
            if (fl > 0) {
                rnd = (int) (rnd - (fl * Math.Pow(10, i)));
                matrix2[maxDigits - i] = fl;
            }
            else
            {
                p = i;
            }
        }

        for (int i = 0; i <= maxDigits; i++)
        {
            if (i>p) Console.Write("|" + matrix2[i]);
        }

        Console.Write("|");

A: If you want to the digits mathematically:
public static void Main(string[] args)
{
    int randomNumber = 12340; // however you get this
    Console.WriteLine(randomNumber);

    List<byte> digits = new List<byte>();
    while (randomNumber > 10)
    {
        digits.Add((byte)(randomNumber % 10));
        randomNumber /= 10;
    }
    digits.Add((byte)randomNumber);
    digits.Reverse();

    for(int i=0; i<digits.Count; i++)
    {
        Console.WriteLine(i + ": " + digits[i]);
    }

    Console.Write("Press Enter to quit...");
    Console.ReadLine();
}

Output:
12340
0: 1
1: 2
2: 3
3: 4
4: 0
Press Enter to quit...


text:
Q: Push and Pop in arm I don't really understand how stack commands or how stacks in general work.
Say if I had
PUSH R3
POP R3

Line 1 : Does this mean that the content of R3 would be put onto the top of the stack? Would the contents of the stack then change if R3 changed?
Line 2: On the second line, would the contents at the top of the stack be moved from the stack into R3 OR is the contents of R3 that was pushed onto the stack popped off the stack?
Also what does pop/push do when a register is surrounded in brackets like so
POP {LR}

A: Minimal armv7 example
The best way to learn is to write minimal examples, run them on emulators, and observe what is going on all registers with GDB:
/* Save sp before push. */
mov r0, sp

/* Push. */
mov r1, #1
mov r2, #2
push {r1, r2}

/* Save sp after push. */
mov r1, sp

/* Restore. */
mov r3, #0
mov r4, #0
pop {r3, r4}
cmp r3, #1
bne fail
cmp r4, #2
bne fail

/* Check that stack pointer moved down by 8 bytes
 * (2 registers x 4 bytes each). */
sub r0, r1
cmp r0, #8
bne fail

Boilerplate to run the example on Ubuntu 18.04: https://github.com/cirosantilli/arm-assembly-cheat/blob/f8d78775bd052e9ead579a408c0a2a1651adb9f0/v7/push.S
The brackets are called "register lists" in the arm assembly notation. GNU GAS 2.26.1 does not accept push and pop instructions without the braces, even for single register pushes {} as in push r1.
Also note that:

*

*according to the armv7 calling convention, the stack must be aligned by multiples of 8, so pushing 2, 4, ... registers at a time is way more common than just 1:  ARM: Why do I need to push/pop two registers at function calls?

*armv8 dropped push and pop, compilers often use stp and ldp instead. Example at: https://github.com/cirosantilli/arm-assembly-cheat/blob/f8d78775bd052e9ead579a408c0a2a1651adb9f0/v8/common_arch.h#L20

A: The mentioned stack operations are only shortcuts for memory operations using sp in the address part. E.g.
PUSH {r3}
POP {r3}

are aliases for
str r3, [sp, #-4]!
ldr r3, [sp], #4

First operation says "store content of r3 into [sp - #4] and decrement sp by 4".  Last one "load r3 from [sp] and increment sp by 4".
Instead of {r3} you can use any other register or register sets (e.g. {r1,r2,r3,lr}.  Register sets are specified in a bitmask in the machine code so you can not influence the order in which the registers are stored/loaded.


text:
Q: Remove the Text in C#.net I have a string like,
string str;

str = "This is my new string. "<script>" Hi this is XYZ "</script>"";

Now I want to remove the text, from "<script>" to "</script>" including the  tags by using C#.net code.
Thanks,

A: You should check Regex.
With that you can locate it and delete then.
This should get everything between script tags "<script>[^<]+</script>"

A: this is what i use to remove html tags in a string
public static string ClearHtmlTags(string html)
        {
            if (string.IsNullOrWhiteSpace(html))
                return html;

            html = html.Trim();
            string[] hs = html.Split("<>".ToArray());
            bool skip = false;

            StringBuilder sb = new StringBuilder();
            foreach (string s in hs)
            {
                if (!skip)
                    sb.Append(s);

                skip = !skip;
            }
            return sb.ToString();
        }

and with a simple modify you will get your method
public static string ClearHtmlTags(string html)
        {
            if (string.IsNullOrWhiteSpace(html))
                return html;

            html = html.Trim();
            string[] hs = html.Split("<>".ToArray());
            bool skip = false;
            bool skipTag = false;

            StringBuilder sb = new StringBuilder();
            foreach (string s in hs)
            {
                if (!skip)
                {
                    if (!skipTag)
                        sb.Append(s);
                }
                else
                {
                    skipTag = s == "script";
                }

                skip = !skip;
            }
            return sb.ToString();
        }

A: If you want to remove text from specific length e.g
"my name is testing"

here you want to remove is
just use indexof function later on use substring method for replace string with null or some thing else.
In c# you can filter your string like this or user regex before enter the data

A: You can use something like:
Regex.Replace(inputString, "<script>([a-z]|[A-Z])*</script>", "");

now this would only allow alphanumeric text within the script tags


text:
Q: execute a function after html table is been populated I want to call a function which will add a class to all anchor tags inside a table.
The problem is the table is being populated dynamically.
So i dont know when to call or on which event to call my fucntion to add class to anchor tags.
I tried following.
 $('document').ready(function () {
        $('#htmlTable a').addClass("needsclick");
    });

Kindly advise

A: If you are using DataTable plug-in for JQuery then you can write your code into draw event of dataTable like follows:
$('#htmlTable').on( 'draw.dt', function () {
    $('#htmlTable a').addClass("needsclick");
} );


text:
Q: How to make the superposing of two or more images on server-side PHP? I have <canvas>in HTML that is getting via JS picture from my web camera, and I need to select pictures from the list of superposable images and then make an image from the superposing. How is possible to get two images into PHP and make them superposing without any frameworks?
HTML that I have at this moment:
<div class="form-group" id="snap-new-photo">
            <video style="background-color: #777" id="video" width="640" height="480" autoplay></video>
            <button id="snap">Snap Photo</button>
</div>

<script type="text/javascript">
            // Put event listeners into place
            window.addEventListener("DOMContentLoaded", () => {
                // Grab elements, create settings, etc.
                const canvas = document.getElementById('canvas');
                const context = canvas.getContext('2d');
                const video = document.getElementById('video');
                const snapButton = document.getElementById('snap');

                navigator.getMedia = ( navigator.getUserMedia ||
                    navigator.webkitGetUserMedia ||
                    navigator.mozGetUserMedia ||
                    navigator.msGetUserMedia );

                navigator.getMedia({ video: true },
                    function(stream) {
                        if (navigator.mozGetUserMedia) {
                            video.mozSrcObject = stream
                        }
                        else {
                            video.srcObject = stream
                        }
                        video.play();
                    },
                    function(err) {
                        snapButton.disabled = true;
                    }
                );

                // Trigger photo take
                document.getElementById('snap').addEventListener('click', () => {
                    context.drawImage(video, 0, 0, 640, 480);
                });
            }, false);
</script>

A: Well, I figured out my problem by myself and solved superposing of two images among them one is getting from the canvas and second is stored on the server with imagecopy() and imagepng() standart PHP functions. For getting them from canvas element I used simple AJAX function. You can look and suggest improvements of my self-educational project here: https://github.com/znatno/42-camagru
JS Code:
saveSnapBtn.addEventListener('click', () => {
    let imageBase64 = convertCanvasToImage(canvas).src;

    // Process uploading
    ajax('/create/new-upload', `image=${imageBase64}&maskFilename=${maskFilename}`, (json) => {
        if (json) {
            if (json.status === 'Success') {
                alert(json.status + ': ' + json.message);
            } else {
                alert(json.status + ': ' + json.message);
            }
        }
        draw(video, context);
        })
    });

PHP Code:
public function createImage($img_base64, $mask_filename) {

    if (empty($mask_filename)) {
        $this->error = 'No mask selected';
        return false;
    }

    // Base64 to Image
    $img_base64 = str_replace('data:image/png;base64,', '', $img_base64);
    $img_base64 = str_replace(' ', '+', $img_base64);
    $img_data = base64_decode($img_base64);

    // Creating Image
    $src = imagecreatefrompng('pub/res/masks/src/' . $mask_filename . '.png');
    $dest = imagecreatefromstring($img_data);
    imagecopy($dest, $src, 0, 0, 0, 0, 640, 480); //have to play with these numbers for it to work for you, etc.
    header('Content-Type: image/png');
    $filename = uniqid('', true) . '.png';
    $path = 'pub/photos/' . $filename;
    // Saving to path
    $status = imagepng($dest, $path);
    imagedestroy($dest);
    imagedestroy($src);

    // Saving to Database
    if ($status) {
        $sql = 'INSERT INTO db_ibohun.photos (id, username, user_id, path, timestamp)
            VALUES (:id, :username, :user_id, :path, :timestamp)';
        $params = [
            'id' => 0,
            'username' => $_SESSION['user']['username'],
            'user_id' => $_SESSION['user']['id'],
            'path' => $path,
            'timestamp' => date('Y-m-d H:i:s'),
        ];
        $this->db->query($sql, $params);
    } else {
        $this->error = 'Error during saving. Please, try again';
    }

    // Return success or error
    return $status;
}


text:
Q: I got an error when updateing the gradle plugin to 2.0.0 my configuration is as below:
buildToolsVersion "23.0.2"

gradle plugin is 2.0.0
but i got this error:
Exception while inflating <vector>
org.xmlpull.v1.XmlPullParserException: Binary XML file line #17<vector> tag requires viewportWidth > 0

i've tried this:
 //for Gradle Plugin 2.0+
 android {
   defaultConfig {
     vectorDrawables.useSupportLibrary = true
    }
 }

but it doesn't work for me.

A: my gradle build tool is 1.3.1. my solution is to add
aaptOptions {
    additionalParameters "--no-version-vectors"
}

outside the defaultConfig{} and it works


text:
Q: Apache bandwidth throttling per client, by subnet We're interested in restricting the number of requests per second and/or available bandwidth to HTTP clients, to stop accidental DoS. We provide free scientific data and web services, and sadly some users' scripts aren't well behaved.
I know there's lots of Apache mods that allow you to throttle per client IP address, but the problem is, sometimes we see people doing distributed crawling from their clusters (today this caused a load average > 200 incident!).
What I'd really like to do is throttle per /24 subnet, but without having to specify which subnets in advance.
Ideally, I'd also like to be able to do this as a proportion of a maximum cap, so if we're only seeing requests from one subnet, they get to use all the server's resources, but if two subnets are competing, they get to use half each.
Is this possible with either:

*

*Apache mods

*Traffic control

*Proxy server

*Something else?

Thanks!
EDIT: Couple of further things... If anything needs to be done at the network infrastructure level (e.g. routers) that's out of our responsibility and becomes an instant PITA. So I'm hoping to find a solution that only requires changes at the server level. Also please don't be offended if I take a while to pick a winner, this is a new topic to me so I want to read around the suggestions a bit :-)

A: If you are using HAProxy or can use it check see if this blog post helps </end_shameless_promotion_of_a_fellow_admin_and_company :)>

A: Be very careful. Simply slowing the network down means that you will be compounding any DOS attack - you need to limit connections before they arrive at the webserver.
Consider - disks are very slow, and only handle one request at a time. One of the most important factors in determining webserver performance is the amount of I/O caching the OS can do - and this is limited by the amount of free memory on the system. Whenever a request comes in, an Apache process (or thread) is scheduled to handle it. That process will sit and hog memory and CPU for the whole time it needs to compose the response and send it across the internet to the client. Denying this memory to the I/O cache. One way to minimise the impact of this is to use a suitable reverse proxy in front of the webserver - e.g. squid which tuns as a single threaded server.
Assuming you can avoid the problem of gumming up your webserver, then you might want to have a look at running a traffic shaper at the perimeter of your network. Linux now comes with tc as standard.
(/me just googled 'linux tc' and got a picture of a girl in a bikini ;)
In terms of identifying crawlers / real DDOS, then the answer is a lot more tricky. Certainly there's no off-the-shelf solution which works reliably for HTTP that I am aware of. However it should be possible to amend the detector in fail2ban to trigger lockout or throttling where you can detect an aberrant pattern. And the basic package can interpret high volumes of requests from a particular end point as such a pattern.


text:
Q: SearchBar In TableView hello I am trying to implement a SearchBar in My app. I have followed some tutorials and successfully implemented a SearchBar. But the problem is that in my working code the data is hardcoded and it is in NSArray and in my actual app the data is in NSDictionary coming from a web service. Here is the working code. I want to implement this using Nsdictionary
class  CountryTableViewController: UITableViewController, UISearchResultsUpdating {

    var filterTableData = [String]()
    var resultSearchController = UISearchController()

    var tableData = ["one","two","three"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.resultSearchController = ({

            let controller  = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.sizeToFit()
            self.tableView.tableHeaderView = controller.searchBar
            return controller

        })()

        self.tableView.reloadData()
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if(self.resultSearchController.active){

            return self.filterTableData.count
        }else {
            return tableData.count
        }

    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CountryTableViewCell

        if(self.resultSearchController.active){

            cell.countryNameLabel.text = filterTableData[indexPath.row]
            return cell

        }else{

            cell.countryNameLabel.text = tableData[indexPath.row]
            return cell
        }

    }

    func updateSearchResultsForSearchController(searchController: UISearchController) {
        filterTableData.removeAll(keepCapacity: false)

        let searchPredict = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)

        let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredict)
        filterTableData = array as! [String]
        self.tableView.reloadData()
    }
  }

My NSDictionary Data is like this
{

    0 =     {

        City =         {

            code = 11859;

            "country_id" = 177;

            "created_at" = "<null>";

            id = 23219;

            name = Lahore;

        };

        Country =         {

            id = 177;

            name = "Pakistan

\n";

        };

        State =         {

            Country =             (

            );

            id = 3262;

            name = "Punjab

";

        };

    };

    code = 200;

}

I have tried using Nsdictionary but didn't succeed

A: You can use this
NSDictionary *dictn = [main_dictn objectForKey:@"0"];
NSString *str = [NSString stringWithFormat:@"%@ , %@",[[dictn objectForKey:@"City"] objectForKey:@"name"],[[dictn objectForKey:@"Country"] objectForKey:@"name"]];

In Swift
let dictn : NSDictionary = main_dictn.objectForKey("0") as! NSDictionary

let Cityname = dictn["City"]?.objectForKey("name") as! String /// get city name
let Countryname = dictn["Country"]?.objectForKey("name") as! String /// get country name

let str : String = String(format: "%@ , %@",Cityname,Countryname)


text:
Q: Error waiting for Creating CloudFunctions Function: Error Code 3, Hello I am trying to create my Google Cloud Function in Python by using Terraform
resource "google_cloudfunctions_function" "function" {
    name        = "scheduled-cloud-function-python-api-request"
    description = "A Python Cloud Function that is triggered by a Cloud Schedule."
    runtime     = "python37"

    available_memory_mb   = 128
    source_archive_bucket = google_storage_bucket.bucket.name
    source_archive_object = google_storage_bucket_object.archive.name
    trigger_http          = true
    entry_point           = "http_handler" # This is the name of the function that will be executed in your Python code
}

And it's giving me an error at this code block after I do terraform apply:

Error code 3, message: Function failed on loading user code.

What am I doing wrong here?
This is my python code :
import requests
import csv

request = requests.get(f'https://api.sportsdata.io/v3/nba/scores/json/TeamSeasonStats/2022?key=')

nba_team_stats = request.json()
data_file = open('nba_team_stats.csv', 'w')
csv_writer = csv.writer(data_file)
count = 0

for stats in nba_team_stats:
    if count == 0:
        header = stats.keys()
        csv_writer.writerow(header)
        count += 1
    csv_writer.writerow(stats.values())
data_file.close()

Am I writing my Python Code in an undesired way for the GCP function to execute?


text:
Q: File.readline() and csv.reader(file) are not returning the final two columns in my csv file my code is only returning the first 7 elements of each row, but not the final two elements. I have tried copy-pasting the data into another file but it hasn't worked. Nothing appears to be wrong with the file itself either.
with open("tr_cities.csv") as file:
    for row in csv.reader(file):
        print(row)

Here is a photo of the output
Its interesting to note that it picks up the final two cells as a null cell and doesn't ignore them entirely. idk what to do
Here is the file in question. Im running Ubuntu if it helps.

Here are a few lines as text of the file:
city,lat,lng,country,iso2,admin_name,type,population,population_proper
Istanbul,41.01,28.9603,Turkey,TR,Istanbul,admin,15154000,15029231
Ankara,39.93,32.85,Turkey,TR,Ankara,capital,5503985,5503985
Izmir,38.4127,27.1384,Turkey,TR,Izmir,admin,4320519,4320519
Bursa,40.1833,29.0667,Turkey,TR,Bursa,admin,2901396,2901396
Antalya,36.9081,30.6956,Turkey,TR,Antalya,admin,2426356,2426356
Konya,37.8714,32.4847,Turkey,TR,Konya,admin,2232374,2232374
Adana,37,35.325,Turkey,TR,Adana,admin,2220125,2220125
...

A: This is because your file does not have data for the last two columns after the 196 record.
Your application is working properly.
See this:

And this is the output of the program:


text:
Q: How to do memcmp() in Swift? I'm trying to convert some of my code from Objective-C to Swift.  One method that I'm having trouble with does a comparison of a CBUUID with an UInt16. This was fairly straight-forward in Objective-C, but I'm having a hard time coming up with a good way to do this in Swift.
Here's the Objective-C version:
/*
 *  @method compareCBUUIDToInt
 *
 *  @param UUID1 UUID 1 to compare
 *  @param UUID2 UInt16 UUID 2 to compare
 *
 *  @returns 1 (equal) 0 (not equal)
 *
 *  @discussion compareCBUUIDToInt compares a CBUUID to a UInt16 representation of a UUID and returns 1
 *  if they are equal and 0 if they are not
 *
 */
-(int) compareCBUUIDToInt:(CBUUID *)UUID1 UUID2:(UInt16)UUID2 {
    char b1[16];
    [UUID1.data getBytes:b1];
    UInt16 b2 = [self swap:UUID2];
    if (memcmp(b1, (char *)&b2, 2) == 0) return 1;
    else return 0;
}

My (untested) version of this method in Swift got much more complicated and I'm hoping that I'm just missing some better ways to use the language:
func compareCBUUID(CBUUID1: CBUUID, toInt CBUUID2: UInt16) -> Int {
    let uuid1data = CBUUID1.data
    let uuid1count = uuid1data.length / sizeof(UInt8)
    var uuid1array = [UInt8](count: uuid1count, repeatedValue: 0)
    uuid1data.getBytes(&uuid1array, length: uuid1count * sizeof(UInt8))

    // @todo there's gotta be a better way to do this
    let b2: UInt16 = self.swap(CBUUID2)
    var b2Array = [b2 & 0xff, (b2 >> 8) & 0xff]
    if memcmp(&uuid1array, &b2Array, 2) == 0 {
        return 1
    }
    return 0
}

There are two things that seem to complicate things.  First, it isn't possible to declare a fixed sized buffer in Swift, so the char b1[16] in ObjC becomes 3 lines in Swift.  Second, I don't know of a way to do a memcmp() in Swift with a UInt16.  The compiler complains that:
'UInt16' is not convertible to '@value inout $T5'

So that's where the clunky step comes in where I separate out the UInt16 into a byte array by hand.
Any suggestions?

A: The corresponding Swift code for char b1[16] would be
var b1 = [UInt8](count: 16, repeatedValue: 0)

and for the byte swapping you can use the "built-in" method byteSwapped
or bigEndian.
Casting the pointer for memcpy() is a bit tricky.
The direct translation of your Objective-C code to Swift would be (untested!):
var b1 = [UInt8](count: 16, repeatedValue: 0)
CBUUID1.data.getBytes(&b1, length: sizeofValue(b1))
var b2: UInt16 = CBUUID2.byteSwapped
// Perhaps better:
// var b2: UInt16 = CBUUID2.bigEndian
if memcmp(UnsafePointer(b1), UnsafePointer([b2]), 2) == 0 {
    // ...
}

However, if you define b1 as an UInt16 array then you don't need
memcmp() at all:
var b1 = [UInt16](count: 8, repeatedValue: 0)
CBUUID1.data.getBytes(&b1, length: sizeofValue(b1))
var b2: UInt16 = CBUUID2.bigEndian
if b1[0] == b2 {
    // ...
}