text:
Q: Data sent over TCPClient to Java Server Socket on Android causes Thread to hang I'm creating an Android app which sends Text Messages( SMSManager Class ). This is an app I'm creating for developers, so, the app has to be inter-operable with the various programming languages. The app seems to be working well with JAVA and PHP.
I've been experiencing problems with C#.
        TcpClient sock = new TcpClient();
        sock.Connect("192.168.1.24", 5000);
        NetworkStream ns = sock.GetStream();
        String str = "9840486945#hi";
        byte[] by = Encoding.Default.GetBytes(str);
        ns.Write(by, 0, by.Length);
        ns.Read(by, 0, by.Length);             //Will receive "Transmitted" or "Failed"
        string returndata = System.Text.Encoding.Default.GetString(by);
        Console.WriteLine(returndata);
        if(returndata.Equals("Transmitted"))
        {
             ns.Read(by, 0, by.Length);                     //Will receive "Delivered"
             returndata = System.Text.Encoding.Default.GetString(by);
             Console.WriteLine(returndata);
        }

On the Android side, I've attempted this:
        if(lang.equals("CS"))
        {
            byte[] by=new byte[1024];
            InputStream is;
            try {
                   is = s.getInputStream();
                   is.read(by);
                   input=new String(by);
                }
             catch (IOException e)
                {
                       // TODO Auto-generated catch block
                       e.printStackTrace();
                }
         }

I've checked the input coming into the Android app, its perfectly normal. But when I use the input I've received from the socket, the Logcat app's log shows:
W/System.err(14636): at com.app.mysmsgateway.Receiver.run(MainActivity.java:498)

This is what line 498 contains:
smsManager.sendTextMessage(phoneNo, null, msg, sentPI, deliverPI);

Thanks in advance!
EDIT: Changed encoding on both ends to UTF-8. Still showing me the System.err.

A: I figured out the issue, I had set a predefined byte array size, which caused a number of characters with ASCII code 0, which means most of my byte array wasn't filled. Worked around this and solved my problem! Thanks for your time @Jonskeet and @PedroOlivera!


text:
Q: Как связать БД mongodb и приложение на NodeJS в Jelastic? После регистрации на reg.ru создал окружение с NodeJS и добавил mongodb. Пришла информация с данными для подключения.
Имя хоста, пароль, логин.
Открываю соединение через mongoose:
mongoose.connect('
  mongodb://login:password@mongodb148973-nodejs.jelastic.regruhosting.ru/bd');

Запускаю и вижу следующую картину:
nodejs@node148974-nodejs /home/jelastic/ROOT/seed $ node product-seeder.js
(node:608) UnhandledPromiseRejectionWarning: MongoError: Authentication failed.
    at /home/jelastic/ROOT/node_modules/mongodb-core/lib/connection/pool.js:595:61
    at authenticateStragglers (/home/jelastic/ROOT/node_modules/mongodb-core/lib/connection/pool.js:513:16)
    at Connection.messageHandler (/home/jelastic/ROOT/node_modules/mongodb-core/lib/connection/pool.js:549:5)
    at emitMessageHandler (/home/jelastic/ROOT/node_modules/mongodb-core/lib/connection/connection.js:309:10)
    at Socket.<anonymous> (/home/jelastic/ROOT/node_modules/mongodb-core/lib/connection/connection.js:452:17)
    at Socket.emit (events.js:160:13)
    at addChunk (_stream_readable.js:269:12)
    at readableAddChunk (_stream_readable.js:256:11)
    at Socket.Readable.push (_stream_readable.js:213:10)
    at TCP.onread (net.js:599:20)
    at emitWarning (internal/process/promises.js:65:17)
    at emitPendingUnhandledRejections (internal/process/promises.js:109:11)
    at process._tickCallback (internal/process/next_tick.js:161:7)
(node:608) MongoError: Authentication failed.
    at /home/jelastic/ROOT/node_modules/mongodb-core/lib/connection/pool.js:595:61
    at authenticateStragglers (/home/jelastic/ROOT/node_modules/mongodb-core/lib/connection/pool.js:513:16)
    at Connection.messageHandler (/home/jelastic/ROOT/node_modules/mongodb-core/lib/connection/pool.js:549:5)
    at emitMessageHandler (/home/jelastic/ROOT/node_modules/mongodb-core/lib/connection/connection.js:309:10)
    at Socket.<anonymous> (/home/jelastic/ROOT/node_modules/mongodb-core/lib/connection/connection.js:452:17)
    at Socket.emit (events.js:160:13)
    at addChunk (_stream_readable.js:269:12)
    at readableAddChunk (_stream_readable.js:256:11)
    at Socket.Readable.push (_stream_readable.js:213:10)
    at TCP.onread (net.js:599:20)
(node:608) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
    at emitWarning (internal/process/promises.js:92:15)
    at emitPendingUnhandledRejections (internal/process/promises.js:109:11)
    at process._tickCallback (internal/process/next_tick.js:161:7)

Что я сделал не так?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find out the version of savon(SOAP client for Ruby) installed? Please suggest the command to find out the version of savon already installed?

A: For a list of all your gems and their version number use:
gem list

If you use bundler, then you can get the version from:
bundle show [gemname]

If you use RVM:
[gemname] --version

Or list all your gems:
rvm gemset list


text:
Q: Notation in the definition of random variable I am trying to understand definition of random variable.
Given a probability space $(\Omega, \mathcal F, P),$ a random variable $X$ is a function from the sample space $\Omega$ to the real numbers $\mathbb R.$ Once the outcome $\omega \in \Omega$ of the experiment is revealed, the corresponding $X(ω)$ is known as realization of the random variable.
Consider two sample spaces $\Omega_1$ and $\Omega_2$ and a sigma-algebra $\mathcal F_2$ of sets in $\Omega_2.$ Then, for $X$ to be a random variable, there must exist a sigma-algebra $\mathcal F_1$ in $Ω_1$ such that for any set $S$ in $\mathcal F_2$ the inverse image of $S,$ defined by:
$$X^{-1}(S) := \{ω \mid X(ω) ∈ S\}$$
I do not know how to read this and I am hoping some one can explain each part to me.

A: It may be pertinent to frame the answer defining a random variable as a measurable function $X$ from the sample space of a probability space $(\Omega, \mathcal F, \mathbb P)$ to the space $(\mathbb R, \mathcal B)$ of the real numbers endowed with the Borel sigma algebra (i.e. the smallest sigma algebra which contains the open sets of $\mathbb R$), such that
$$X^{-1}(A)=\{\omega \in \Omega \mid X(\omega)\in A\}\in \mathcal F \;\; \forall A \in \mathcal B.$$
Constructing the sigma-field (or sigma-algebra) generated by two random variables will bring home the idea as follows:
The random experiment is tossing a fair die once, which has as possible outcomes or sample space $\Omega=\{1,2,3,4,5,6\}.$
It is up to the definition of the probability space to determine which events will have assigned probabilities. We could consider the events even or odd outcome and contrapose it to the events prime or not-prime. Thus we define two random variables: $X: \Omega \to \{0,1\}$ maps the outcome to $1$ if the die lands on an odd number, and otherwise $0.$ On the other hand, the second random variable $Y: \Omega\to \{0,1\}$ maps to $1$ when the die lands on a prime number.
Now these two random variables will generate two different sigma algebras. In the first case, the pre-image of the random variable $X$ will include the set $V=\{1,3,5\}$ corresponding to the value of the random variable $1$ in the Borel set $A_1=\{1\}:$
$$V=X^{-1}(A_1)=\{\omega\in\Omega \mid X(\omega) \in A_1\}=\{1,3,5\}$$
This reads: The pre-image (not the inverse function!) of the set $A_1$ for the random variable $X$ is the set $\{\text{...}\}$ containing those outcomes ($\omega$) in the big set $\Omega$ such that (that is the little bar $\mid$) the random variable maps to elements in $A_1.$ And the fact that $\{1,3,5\}\in \mathcal F$ (see below) makes the function $X$ measurable.
Logically, there would be the set $W =\{2,4,6\}$ corresponding to the pre-image of the value $0$ in the Borel set $ A_2=\{0\},$ or
$$W=X^{-1}(A_2)=\{\omega\in\Omega \mid X(\omega) \in A_2\}=\{2,4,6\}$$
The sigma algebra will also contain complementary, union and finite intersections, ending up with the sigma algebra $\mathcal F=\{\{1,3,5\} , \{2,4,6\}, \emptyset,\Omega \},$ of which $\{1,3,5\}$ and $\{2,4,6\}$ are called atoms (an atom of $\mathcal F$ is a set $F \in \mathcal F$ such that the only subsets of $F$ which are also in $\mathcal F$ are the empty set $\emptyset$ and $F$ itself). And the probability space will determine (in a fair die) that $\frac12$ is assigned to each one of them by the PMF: $\mathbb P\left(\{1,3,5\}\in \mathcal F\right )= \sum_{\mathbf 1_{1,3,5}} p(\omega_i )=3\frac 1 6.$
Here is the construct:

All Borel sets of interest have pre-images corresponding to sets in the sigma algebra $\mathcal F.$
If instead the events of interest were powers of 2 and powers of 3, the sigma algebra would contain $\small \left\{\emptyset, \Omega,\{1,2,4\},\{3,5,6\},\{1,3\},\{2,4,5,6\},\{1,2,3,4\},\{1,3,5,6\},\{1,2,4,5,6\},\{2,3,4,5,6\}\right\}$, the function simply mapping the face of the die to the numbers $1,\dots,6$ would not be a random variable, because the set formed by the pre-image of the singleton Borel set $\small \{5\}$ is not in the sigma algebra (not measurable): $\small \text{pre-image}(\{5\})=\{5\}\notin \mathcal F$.
Going back to the random variable $X,$ i.e. (odd, even), it will not contain information allowing separation of $1$ from $3$ for example, because they are both outcomes belonging to the same event ("odd").
The same exercise for $Y$ will result in two atomic sets $\{2,3,5\}$ and $\{1,4,6\},$ and a sigma algebra $\mathcal G=\{\{2,3,5\} , \{1,4,6\}, \emptyset,\Omega \}.$
This random variable $Y,$ in contradistinction to $X,$ contains information allowing us to separate the outcomes $1$ and $3.$

A: Probability notation can be a bit confusing at first! Maybe a simple example helps to see why the notation is actually chosen in a somewhat natural way:
Let's look at a specific probability space $(\Omega, F, P)$ that corresponds to the toss of a coin. So the sample space is $\Omega = \{H, T\}$, where we denote 'Heads' by $H$ and 'Tails' by $T$. We set $F = 2^\Omega$ and we're looking at a fair coin toss, so $P(H) = P(T) = \frac{1}{2}$.
Now we define the random variable $X:\Omega \rightarrow \mathbb{R}, X(H) = 0, X(T) = 1$. You can think of the r.v. $X$ as doing an 'experiment', in this case tossing the coin, and recording a $0$ for 'Heads' and a $1$ for 'Tails'. Now of course your question is, "What is the probability that my experiment results in a Heads?". So, linguistically you would want to write something like:
$$P(X = 0) = \frac{1}{2}$$
This is why we define it exactly this way:
$$P(X = 0) := P(X^-1(\{0\})) = P(\{\omega | X(\omega) = 0\})\, (= P(H) = \frac{1}{2})$$
We have to do it like this, because the probability measure $P$ 'lives' on the left-hand side (the $\Omega$-side) and can only measure things there, but the outcomes of the experiment 'live' on the right-hand side.
I hope this doesn't confuse more than it helps...


text:
Q: When to use header('Content-Type: application/json') in PHP I've been trying to figure out what's really the usage of header('Content-Type: application/json') in php scripts and I've found different questions and answers on stackoverflow about this subject but I still don't completely get it...
So here's the question : I've seen in some php projects this line of code, and I'm trying to understand

*

*if this is used when another web page is calling this actual script (with ajax for example) so that the calling page can get a json from the php page

OR

*

*if this script means that the php page is going to deal with json sent from another web page. Or maybe something else ???

Another thing that could help me if answered, lately I've been retrieving json from a resource (external url) with cURL and I had to put this header (Content-type:application/json) in the request. Did I send this header to the exertnal resource or was this MY header so that I can deal with the returned json ?
thanks

A: Ok for those who are interested, I finally figured out that header('Content-Type: application/json') is used when another page is calling the php script, so that the other page can automatically parse the result as json.
For instance i have in my test.php :
header('Content-type: application/json; charset=utf-8');
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}

and in my main.js
function test() {
    $.ajax({
        url: 'test.php',
        type: 'GET',
        //dataType: 'html',
        success: function (response) {
            alert(response);
        }
    });
};

When I dont have dataType set to "json" or when I don't have the header in my test.php, the alert gives {"a":1,"b":2,"c":3,"d":4,"e":5} which is a string (tried with typeof(response), and when I have this header, or dataType:"json", I get [object Object] from the alert. So this header function is there to indicate to the calling pages which type of data it gives back, so that you can know how to deal with it. In my script, if I didn't have header('Content-Type: application/json'), I would have to parse the response in the javascript like this : JSON.parse(response) in order to make it a json, but with that header, I already have a json object, and I can parse it to html with jSON.stringify(response).

A: You should always set the Content-Type for any HTTP response to describe what you're serving in that response.
Whether it's JSON or something else, and whether it's for an AJAX request or any other kind of request.

You should also set the Content-Type for any request to describe your POST payload.

A: In PHP, if you don't specify the Content-Type header in the script, it will default to whatever you've configured default-mimetype to be in your php.ini file which is usually text/html.
Calling header('Content-Type: application/json') will override that default setting so that the script will respond with that Content-Type when requested.
Also, when calling curl with a Content-type:application/json header, you're specifying the content type for your request body and not for the expected reponse.

A: W3 Description For the Content-Type

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.

Shortly speaking, just to inform the receiver what kind of data he received and consume it accordingly.


text:
Q: How to remove the duplicated image data? In my site, the product image are duplicated many times? how to remove the repeat data in the database.
Eg: The correct product image is: product.jpg producta.jpg productb.jpg now, there are
product.jpg producta.jpg productb.jpg product.jpg producta.jpg productb.jpg. How to make them unique? thank you.

A: Just delete them? What is the exact problem? You have products with a lot of product images attached.
You can load the product, loop over the mediaGallery images, save the names in an array, remove all images when the name already exists and save the image. Something like this:
    // get the media-gallery backend model to remove images
    $attributes = $this->getTypeInstance(true)->getSetAttributes($this);
    if (!isset($attributes['media_gallery'])) {
        return $this;
    }
    $mediaGalleryAttribute = $attributes['media_gallery'];
    /* @var $mediaGalleryAttribute Mage_Catalog_Model_Resource_Eav_Attribute */
    $mediaGalleryAttribute->getBackend()->addImage($this, $file, $mediaAttribute, $move, $exclude);

Mage_Catalog_Model_Product_Attribute_Backend_Media::removeImage(Mage_Catalog_Model_Product $product, $file)


text:
Q: Plot y1 in x1 with respect to x2 axis I have a data a follows:
y1   x1   x2
125  100   1
130  90    2
136  85    3
143  70    4
145  65    5

I would like to plot it in gnuplot as in the figure.
I used the procedure mentioned here Gnuplot: Plot x2 axis with respect to x1 axis , but it is plotting the x2 differently.

A: Plot your data as usual on the x1 and y1 axes, but place additional labels on the x2-axis with x2tic(3):
set xrange [*:*] reverse
set x2tics
set xtics nomirror
plot 'file.dat' using 2:1:x2tic(3) with linespoints pt 7 notitle

If you don't want a conventional numerical, you could also use both x2tic and xtic:
plot 'file.dat' using 2:1:x2tic(3):xtic(2) with linespoints pt 7 notitle


text:
Q: Rescue all errors of a specific type inside a module I have a module in which I am performing all of my encryption/decryption tasks for a project. I would like to catch any OpenSSL::Cipher::CipherError exceptions that occur in this module so that I can handle them.
Is it possible to do something like
rescue_from OpenSSL::Cipher::CipherError, :with => :cipher_error

inside of a module?

A: I've investigated a little and came with a solution. You said you have a module in which you do your encryption. I'm guessing that module represents a singleton. My solution, however, requires you have an instance instead.
class Crypto
   def self.instance
      @__instance__ ||= new
   end
end

Extract encryption behavior in a module.
module Encryptable
   def encrypt
      # ...
   end

   def decrypt
      # ...
   end
end

Create a new module that handles exceptions.
module ExceptionHandler
  extend ActiveSupport::Concern

  included do
    include ActiveSupport::Rescuable
    rescue_from StandardError, :with => :known_error
  end

  def handle_known_exceptions
     yield
  rescue => ex
     rescue_with_handler(ex) || raise
  end

  def known_error(ex)
    Rails.logger.error "[ExceptionHandler] Exception #{ex.class}: #{ex.message}"
  end
end

So now you can use the newly defined handle_known_exceptions inside your Crypto. This is not very convenient because you haven't gained much. You still have to call the exception handler inside every method:
class Crypto
  include ExceptionHandler

  def print_bunnies
    handle_known_exceptions do
      File.open("bunnies")
    end
  end
end

No need to do this if we define a delegator that does that for us:
class CryptoDelegator
  include ExceptionHandler

  def initialize(target)
    @target = target
  end

  def method_missing(*args, &block)
    handle_known_exceptions do
      @target.send(*args, &block)
    end
  end
end

Completely override the initialization of Crypto, to use the delegator instead.
class Crypto
  include Encryptable

  def self.new(*args, &block)
    CryptoDelegator.new(super)
  end

  def self.instance
      @__instance__ ||= new
  end
end

And that's it!


text:
Q: Get object key and use it as a property in Jackson I currently have this JSON
input
[
    {
        "A": {
            "name": "Dog"
        }
    },
    {
        "B": {
            "name": "Cat"
        }
    }
]

I have the following classes:
public class Pet {

  @JsonProperty("name")
  String name = "";

  @JsonIgnore
  String id  = "";
}

I want to have this output

note: (this is just a representation of the deserialized objects)

 Pet [ name = "Dog" , id = "A"],
 Pet [ name = "Cat" , id = "B"]

A: You need to have List<Pet>, not PetList class. In this case Jackson will do what you want - [ { pet1..}, {pet2...} ] And Pet will have name and id.
EDIT: if you want
[
    {
        "A": {
            "name": "Dog"
        }
    },
    {
        "B": {
            "name": "Cat"
        }
    }
]

then you need to put a Map<String, IdClass> into your Pet, put in this map "A": new IdObject(), and IdObject should have String name = "Dog"


text:
Q: Roles in Sonata Admin Good day. I can not understand how in sonata admin bundle to add roles to users. Namely, it is necessary that the user with a specific role seen in adminpanel only one entity and only worked with her. For now, there is only one role - it ROLE_SONATA_ADMIN, which gives access to the whole adminpanel. On official site found just such an example :
security:
    ...
    role_hierarchy:
        # for convenience, I decided to gather Sonata roles here
        ROLE_SONATA_FOO_READER:
            - ROLE_SONATA_ADMIN_DEMO_FOO_LIST
            - ROLE_SONATA_ADMIN_DEMO_FOO_VIEW
        ROLE_SONATA_FOO_EDITOR:
            - ROLE_SONATA_ADMIN_DEMO_FOO_CREATE
            - ROLE_SONATA_ADMIN_DEMO_FOO_EDIT
        ROLE_SONATA_FOO_ADMIN:
            - ROLE_SONATA_ADMIN_DEMO_FOO_DELETE
            - ROLE_SONATA_ADMIN_DEMO_FOO_EXPORT
        # those are the roles I will use (less verbose)
        ROLE_STAFF:             [ROLE_USER, ROLE_SONATA_FOO_READER]
        ROLE_ADMIN:             [ROLE_STAFF, ROLE_SONATA_FOO_EDITOR, ROLE_SONATA_FOO_ADMIN]
        ROLE_SUPER_ADMIN:       [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

But I can not understand that instead embed DEMO, and that instead of FOO. Tried a lot of options but nothing is worked.
Thanks in advance and sorry for my bad English.

A: The permissions are:

*

*LIST: view the list of objects

*VIEW: view the detail of one object

*CREATE: create a new object

*EDIT: update an existing object

*DELETE: delete an existing object

*EXPORT (for the native Sonata export links)


text:
Q: POSIX semaphores/threads not working correctly? I have the following code:
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>

sem_t semr;

void* func(void* i)
{
    sem_wait(&semr);
    printf("\nInstance %d running",*(int*)i);
    //sem_post(&semr);
    return NULL;
}

int main(void)
{
    sem_init(&semr,0,1);
    void* (*fp)(void*);
    int s1,s2,s3,val=0;
    pthread_t t1,t2,t3;
    fp=&func;
    val=1;
    s1=pthread_create(&t1,NULL,fp,(void*)&val);
    val=2;
    s2=pthread_create(&t2,NULL,fp,(void*)&val);
    val=3;
    s3=pthread_create(&t3,NULL,fp,(void*)&val);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    pthread_join(t3,NULL);
    return 0;
}

This is my understanding of what happens:
The first thread(t1) executes successfully. The subsequent threads(t2 and t3) though, are blocked, since I never sem_post the semaphore. The pthread_joins will make main() wait for all 3 threads to terminate.
This is what happens:
Neither thread will output anything. Not even t1s output(see question 1 below)
However,
removing all pthread_joins has a better effect in terms of what I expect:
t1 executes successfully and the command prompt is returned.
My questions:

*

*According to the sample code on this page, main() should wait for t2 and t3 to terminate (in addition to successfully executing t1 and  outputting something). Am I using pthread_join incorrectly here? What's happening?

*Why happens to the blocked threads(t2 and t3)? Are the threads forced to terminate due to main() returning?

A: You should ensure that anything you print is terminated (not followed) with a newline. stdout won't be flushed while main is blocked waiting to join your threads. When you explicitly cancel the program, again, stdout won't be flushed.


text:
Q: How to check what's kind of an iOS Application? I am new on iOS programming. I download some samples from apple website.
How do I know what's kind of the sample? View-Based, Window-based, Navigation-based etc.

A: To add to what @Steve said ( I was editing answer for some time now ... you put it better than I had :)), template does not create any indicator that allows you to find what kind of project. Of course the SDK setting and the run setting can help you understand if its for Iphone or MAC.
But if your project is created with some standard template, it is possible to understand which of those template was used.
Navigate to the .xcodeproj file for the corresponding project. CMD + click ( or right click) and choose open package contents. Open the .pbxproj file. By default this will open in Xcode, search for the term "Template". This will probably point you to the right direction.

A: Your question "[...] what's kind of an iOS Application? [...] View-Based, Window-based, Navigation-based etc." implies that these templates which ship with Xcode create fundamentally different "kinds" of applications.
This is not true.
All of those project templates create the same kind of project.
They are simply there as a quick-start convenience.

A: View-based, Window-based, ... are actually the names given to project templates in Xcode. When choosing one at project creation, Xcode provides the stuff you will need, which includes subclasses of common controller classes.
In almost all cases, an iOS app will show a window, and a view inside, so you can consider facing a window-based or a view-based app every time.
About the others, have a look to the files Xcode put in the project folder, you should find a UINavigationController when working with a navigation-based app, and for example a UITabBarController when you develop a tab-based app.
Finally, the best answer you will find is actually in the excellent View Controller Programming Guide for iOS provided by Apple.
Good luck.


text:
Q: 403 when trying to access /mod_cluster-manager? I'm running CentOS 7 with Apache 2.4.6.  I'm trying to create a Wildfly/JBoss cluster using mod_cluster 1.2.6.  I've successfully accomplished this on Mac OSX, and am just trying to get it up and running in our server environment.
My cluster and virtual host config looks like this:
 LoadModule slotmem_module       modules/mod_slotmem.so
 LoadModule proxy_cluster_module modules/mod_proxy_cluster.so
 LoadModule advertise_module     modules/mod_advertise.so
 LoadModule manager_module       modules/mod_manager.so

 MemManagerFile /var/cache/httpd

<VirtualHost *:80>

  <Directory />
    Order deny,allow
    Allow from all
  </Directory>

  KeepAliveTimeout 60
  MaxKeepAliveRequests 0
  ManagerBalancerName myBalancer
  ServerAdvertise On
  AdvertiseFrequency 3
  EnableMCPMReceive

  <Location /mod_cluster-manager>
    SetHandler mod_cluster-manager
    Order deny,allow
    Allow from all
  </Location>
</VirtualHost>

The server starts fine, however when I try to access http://localhost/mod_cluster-manager I get a 403 saying permission denied.  Here is the exact message in my error_log file:
[Wed Jul 30 11:53:21.547109 2014] [authz_core:error] [pid 6012] [client 127.0.0.1:36425] AH01630: client denied by server configuration: /mod_cluster-manager

I did not encounter any such issues in getting this to work on OSX, so I'm not entirely sure what the problem is or why I'm getting a 403.  As I understand it, the Allow from all directive should be enough to grant me access when connecting via localhost.  Has anyone else run into anything similar?  Am I missing something?

A: Regarding configuration
Yes you are, but the fix is a trivial one: Apache HTTP Server 2.4.x employs mod_authz system requiring a slightly different configuration, e.g.:
Allow MCMP messages from worker nodes in EnableMCPMReceive active VirtualHost only from your internal network 10.10.:
<Directory />
    Require ip 10.10.
</Directory>

or for development more convenient:
<Directory />
    Require all granted
</Directory>

Anyway, this is one of default configuration examples for Apache HTTP Server 2.4.x:
# Load mod_cluster modules
# Please, note:
#  - mod_cluster cannot coexist with proxy_balancer_module; disable it
#  - mod_cluster needs proxy_module and proxy_ajp_module loaded for AJP transport

LoadModule proxy_cluster_module modules/mod_proxy_cluster.so
LoadModule cluster_slotmem_module modules/mod_cluster_slotmem.so
LoadModule manager_module modules/mod_manager.so
LoadModule advertise_module modules/mod_advertise.so

# Place for slotmem files
MemManagerFile cache/mod_cluster

<IfModule manager_module>
  ## We suggest to use a restricted VirtualHost
  ## for receiving MCPM (Mod Cluster Protocol Message) from worker nodes.
  Listen 6666
  <VirtualHost *:6666>
    <Directory />
      Require ip 127.0.0.1
    </Directory>
    ## Apache HTTP Server advertises its presence
    ## on 224.0.1.105:23364 by default.
    ServerAdvertise on
    EnableMCPMReceive

    ## Management and monitoring console
    <Location /mod_cluster_manager>
      SetHandler mod_cluster-manager
      Require ip 127.0.0.1
   </Location>
  </VirtualHost>
</IfModule>

Regarding mod_cluster version
Please, note that mod_cluster 1.2.6.Final is obsolete, it contains several performance and security related bugs that have been fixed in newer versions.
Definitely download mod_cluster 1.3.1.Final binaries or use mod_cluster 1.3.1.Final Apache HTTP Server enabled load balancer Docker image. You may also compile the modules yourself; the Dockerfile contents may guide you as far as Linux environment goes.

A: You have degraded version. Please try using as below:
<Directory />
    Order deny,allow
    Deny from all
    Allow from all
    Require all granted
</Directory>

A: Getting error response " You don't have permission to access mod_cluster_manager on this server " when trying to access the management URL: http://myHttpd:6666/mod_cluster_manager
Apache 2.4 mod_cluster 1.3  required me to configure basic authentication.
Go to $HTTPD_HOME/bin and create a login account for e.g. "admin" as follows:
./htpasswd -c /etc/httpd/modclusterpassword admin

then, in your /etc/httpd/conf/httpd.conf or one of its child include file like /etc/httpd/conf.d/mod_cluster.conf, find the section  under which you shall now have:
<Location /mod_cluster_manager>
  SetHandler mod_cluster-manager
  AuthType Basic
  AuthName "MCM"
  AuthUserFile /etc/httpd/modclusterpassword
  Require user admin

  Order deny,allow
  Deny from all
  Allow from all
</Location>

and restart the HTTPD service.
Now going to http://myHttpd:6666/mod_cluster_manager, will prompt for login. Use 'admin' and the password supplied interactively vi 'htpasswd' hereabove.


text:
Q: How to disable the namespace auto import in Visual Studio 2015? Since I have installed Visual Studio 2015, one thing really bother me...
When you override a method or implement an interface using the automatic intellisense way... it import all the "required" namespace as "using" on the top of the file.
As we have the coding rule to use "fully qualified" name in our company, I have then to go on the top of the file, clean all the using, then go to the method and add all the namespace "correctly".
It take me "a lot of time" to do that every time...
[EDIT] Even when I use the quick action stuff![/EDIT]
Regardless of the "usefulness" of "fully qualified", do anyone of you know how to disable this?
I searched for using and namespace in the option but didn't found anything.
I know Resharper can do it... but we do not have licences for now, so the question is: can VS do it?
Thanks for reading!
flo.

A: After typing the partial name into Visual Studio will underlined it in red and possibly show a "light bulb" symbol. The context menu for the red-underlined name should include "Quick actions" (or "Resolve" on older versions). The options then offered include "using ..." and the full name of the item. Select the full name
For example. When I type Regex rex; into a C# method, the Regex is underlined in red. If I select the using ... action then a using System.Text.RegularExpressions is added to the top of the file. If I select the other action my code is changed to System.Text.RegularExpressions.Regex rex;


text:
Q: How to apply gradient color at the end of the content? I am trying to replicate the below-added image UI(taken from the udemy.com course description section). I was looking for a way to create a similar gradient UI on only some parts of the content as shown in the below image.

Here is the sample code sandbox where I have been experimenting https://codesandbox.io/s/fervent-einstein-doeql?file=/src/Demo.js. I am trying to apply this exact ui to a material-ui card content. Here is my Demo.js where I have the card content defined
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import CardMedia from "@material-ui/core/CardMedia";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";

const useStyles = makeStyles({
  root: {
    maxWidth: 345
  }
});

export default function ImgMediaCard() {
  const classes = useStyles();

  return (
    <Card className={classes.root}>
      <CardMedia
        component="img"
        alt="Contemplative Reptile"
        image="https://images.unsplash.com/photo-1503803548695-c2a7b4a5b875?ixlib=rb-1.2.1&w=1000&q=80"
        title="Contemplative Reptile"
      />
      <CardContent>
        <Typography gutterBottom variant="h5" component="h2">
          Lizard
        </Typography>
        <Typography
          className="content"
          variant="body2"
          color="textSecondary"
          component="p"
        >
          Lizards are a widespread group of squamate reptiles, with over 6,000
          species, ranging across all continents except Antarctica Lizards are a
          widespread group of squamate reptiles, with over 6,000 species,
          ranging across all continents except Antarctica Lizards are a
          widespread group of squamate reptiles, with over 6,000 species,
          ranging across all continents except Antarctica Lizards are a
          widespread group of squamate reptiles, with over 6,000 species,
          ranging across all continents except Antarctica Lizards are a
          widespread group of squamate reptiles, with over 6,000 species,
          ranging across all continents except Antarctica Lizards are a
          widespread group of squamate reptiles, with over 6,000 species,
          ranging across all continents except Antarctica Lizards are
        </Typography>
      </CardContent>
      <div className="button">
        <Button size="small">Read more</Button>
      </div>
    </Card>
  );
}

and my styles.css
.content {
  max-height: 100px;
}

.content:hover {
  max-height: none;
}

.button {
  display: flex;
  margin-top: 5px;
  justify-content: flex-end;
  width: 100%;
  background-color: grey;
}

Any help is appreciated. Thanks

A: I am not sure if I understand the question. If I do to the sample code sandbox, it actually expands on hover. Maybe you found the answer?


text:
Q: I can't remove the margin with
* Do you know why I can't remove the margin from my <li> elements? The browser always adds the specific margin for my list, even when I write the code a specific margin. Here is the CSS and HTML code:
#NavLeftList {
    height: 57 % ;
    width: 15 % ;
    position: absolute;
    top: 23 % ;
    border-style: none;
    background: url(images / heaven.jpg);
    margin: 0px
}

#NavLeftList ul {
    margin-left: 11 % ;
}

#NavLeftList ul li {
    text-align: center;
    width: 170px;
    list-style-type: none;
    text-decoration: none;
    margin: 10px 0px 0px 0px;
    padding: 1px;
}

#NavLeftList li a {
    height: 35px;
    padding: 10px 0px 0px 0px;
    text-decoration: none;
    color: #fff;
    background: url(images / tabright.gif);
    display: block
}

#NavLeftList li a span {
    padding: 0px
}

#NavLeftList li a: hover {
    color: #7EC0EE;
}

I haven't pasted the HTML code here since it was appearing strangely.

A: What you're seeing isn't a margin on the lis, it's padding on the ul.
Zero out the ul's padding.

A: try list-style-position:inside; on the li.  It's probably leaving space that would be filled by the bullet even though you've set list-style-type:none;

A: Try setting
body{margin: 0;}

or find the containing element for NavLeftList and set that element's margin to 0 as well.

A: Try following CSS for UL
ul { list-style: none; }

A: Try making use of a reset.css file which will reset all "default" (and thus different) implementations of paddings and margins in the different browsers.
Example: CSS Reset


text:
Q: Theme change in Aptana Studio Issue (already downloaded Eclipse Market Place and Eclipse Color Theme Plug in After following the instructions found in: Aptana Studio 3: How to apply themes to python editor I still can't change my theme.
In Aptana Studio 3 I go to Windows->Preferences->General->Color Theme and choose the appropriate theme but the background remains the standard white color. Thanks.

A: The issue is you have to navigate to Windows->Preferences->Aptana Studio->Themes and check the box at the bottom of the window 'Apply to all (non-Studio) editors'. Then having downloaded Eclipse Market Place and the Color Theme Plug-In you can change the theme (background & font) of your primary work space.


text:
Q: Asterisk client behind NAT - UDP registration does not work I have some clients connected to my Asterisk server behind a NAT device. When using TCP everything works OK. If I change the client and server config to use UDP (from transport=tcp to transport=udp,tcp or even simply transport=udp) the phone can no longer register and Asterisk sends SIP: SIP/2.0 401 Unauthorized to the client.
From what I have read it is possible to use UDP behind a NAT with Asterisk, however experience seems to dictate otherwise. Have I missed another mandatory step or is there something else that I am unaware of?
To clarify: it is the clients behind the NAT device; not the server.
Here's the relevant portions of my sip.conf:
[general]
context=bogus
allowguest=no
allowoverlap=no
bindport=5060
bindaddr=0.0.0.0
srvlookup=no
disallow=all
allow=ulaw
alwaysauthreject=yes
videosupport=yes
canreinvite=no
nat=force_rport,comedia
session-timers=refuse
localnet=x.x.x.x/255.255.0.0     ; blanked out for serverfault
tcpenable=yes                    ; Enable server for incoming TCP connections (default is no)
tcpbindaddr=0.0.0.0:5060         ; IP address for TCP server to bind to (0.0.0.0 binds to all interfaces)
transport=udp,tcp

[my-codecs](!)                    ; a template for my preferred codecs
        disallow=all
;        allow=ilbc
;        allow=gsm
;        allow=g723
        allow=alaw
        allow=ulaw
;       allow=g722

[basic-options](!,my-codecs)                ; another template
        dtmfmode=rfc2833
        context=internal
        type=friend

[natted-phone](!,basic-options)   ; another template inheriting basic-options
        directmedia=no
        host=dynamic
        transport=tcp,udp

[101](natted-phone)
callerid="Office"
secret=12345678901234567890
context=internal
mailbox=101@main
transport=udp,tcp

UPDATE: On investigation I have found that this only seems to affect Avaya handsets. Other softphones connected to the same server do not seem to suffer this problem. Here is a sample of register and un authorized packets:
asterisk*CLI> sip set debug on
SIP Debugging enabled
<--- SIP read from UDP:x.x.x.x:1032 --->
REGISTER sip:asterisk SIP/2.0
From: sip:2003@asterisk;tag=46c2abf4589053ec5895ffc0_F2003192.168.0.174
To: sip:2003@asterisk
Call-ID: 1_5a7d0-b0875cb5895fbc0_R@192.168.0.174
CSeq: 1 REGISTER
Via: SIP/2.0/UDP 192.168.0.174;branch=z9hG4bK1_5a7d12149bcad5895ffc4_R2003
Content-Length: 0
Max-Forwards: 70
Contact: <sip:2003@192.168.0.174;avaya-sc-enabled;transport=udp>;q=1;expires=900;reg-id=1;+sip.instance="<urn:uuid:00000000-0000-1000-8000-2cf4c54ef19b>"
Allow: INVITE,CANCEL,BYE,ACK,SUBSCRIBE,NOTIFY,MESSAGE,INFO,PUBLISH,REFER,UPDATE
User-Agent: Avaya one-X Deskphone
Supported: eventlist

<------------->
--- (12 headers 0 lines) ---
Sending to x.x.x.x:1032 (NAT)
Sending to x.x.x.x:1032 (NAT)

<--- Transmitting (NAT) to x.x.x.x:1032 --->
SIP/2.0 401 Unauthorized
Via: SIP/2.0/UDP 192.168.0.174;branch=z9hG4bK1_5a7d12149bcad5895ffc4_R2003;received=x.x.x.x;rport=1032
From: sip:2003@asterisk;tag=46c2abf4589053ec5895ffc0_F2003192.168.0.174
To: sip:2003@asterisk;tag=as5f37e30b
Call-ID: 1_5a7d0-b0875cb5895fbc0_R@192.168.0.174
CSeq: 1 REGISTER
Server: Asterisk PBX 13.1.0~dfsg-1.1ubuntu4
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH, MESSAGE
Supported: replaces
WWW-Authenticate: Digest algorithm=MD5, realm="asterisk", nonce="2350c222"
Content-Length: 0

A: When using Asterisk behind NAT, you should always add the externip option along with nat option to the [general] section of your sip.conf
Try this
[general]
nat=force_rport,comedia
externip=<your external IP here>
... rest of your config ...

Some clients also allow specifying the "Proxy Address" field in addition to SIP Server address & SIP Domain. When using NAT you should put your external IP there. So a configuration like this should also keep you safe:
 SIP Server: 192.168.1.200 (Servers internal IP)
 SIP Proxy: 1.2.3.4  (Servers external IP)
 SIP Domain: 192.168.1.200  (Servers internal IP)

Finally, checking your asterisk logs in real time, by running:
 asterisk -rvvvv

will help you to diagnose a lot, since 401 Unauthorized maybe related to ACL-problems (like when a peers IP doesn't match permit/deny options specified in sip.conf). In that case Asterisk will give an error like:
SIP Peer ACL: Rejecting '1.2.3.4' due to a failure to pass ACL '(BASELINE)'

P.S. This might save you a lot of headache. Always remember to forward full range of RTP ports, which are specified in /etc/asterisk/rtp.conf
If you have
rtpstart=50000
rtpend=60000

there, then you should unconditionally forward 50000-60000 UDP from your [external IP] to your asterisk, or you will face a lot of weird problems (like inability to reliably transfer a call, random voice loss/disconnections and lots of other things you definitely do not want)...

A: This is proper behavior - you have to understand how NAT works!  NAT can only track connections by keeping a table of open connections (opened by SYN ACK, closed by FIN ACK).  But only TCP uses connections; UDP is connectionless.
So a NAT device does not even attempt to route UDP packets based on connection state.  If you need NAT traversal for UDP packets you will have to create static rules based on port range, source IP, etc.


text: Q: Incorrect Tier Price for logged user let's say I have product A. In product A I have set the product to have a Special Price and also Tier Price 1 for user B, and Tier Price 2 for user C. But why when I login using user D, magento still displays product A with Tier Prices? even though I didn't set the Tier Price for user D.


text:
Q: How to efficiently filter datetime column for extracting data? I am usng sqlite to log data every 5 minutes to a column that is time stamped with and integer in Unix time. The user interface uses php code to extract data in various user selectable time frames which is then plotted using javascript. Charts typically have 12 data/time points and I need to extract data for plotting over different periods of say 1Hr/12Hr/24Hr/12days/month/year. So  only need to extract 12 data rows per search. So for a 24Hr plot I need to only extract data at houly intervals (when minutes = 0) similarly for 12day plots at daily intervals (when mins=0 && hours=0) etc.
My php code for 1Hr works fine since the data is logged every 5min giving me 12 rows of data between search start time and end time. What is an efficient way of extracting data for the longer periods when number of rows between start time and end time is greater than 12? I need to further filter the search to efficiently extract only the data I need?
any suggestions - most appreciated - frank
$db = new MyDB();                                    // open database
$t=time(); // get current time
$q1 = "SELECT TimeStamp,myData FROM mdata WHERE ";
$q2 = " AND TimeStamp <=".$t;                        // end time
$q3 = " AND TimeStamp >=".($t-3600);                 // start time 1 hour earlier

$qer = $q1.$q2.$q3; // my search query form above parts

$result = $db->query($qer);
$json = array();
while ($data = $result->fetchArray(SQLITE_NUM)) {
$json[] = $data;
}

echo json_encode($json);             // data is returned as json array

$db->close();           // close database connection

A: I think you should use WHERE date BETWEEN in your search query?
This kind of search could take up a lot of time once data builds up?

A: Since you already know the exact times you're interested in, you should probably just build an array of times and use SQL's IN operator:
$db = new MyDB();                                    // open database
$timeStep = 300;  // Time step to use, 5 minutes here - this would be 3600 for hourly data
$t = time(); // get current time
$t -= $t % $timeStep;  //  round to the proper interval

$query  = "SELECT TimeStamp,myData FROM mdata ";
$query .= "WHERE TimeStamp IN "
$query .= "(" . implode(",", range($t, $t + $timeStep * 12, $timeStep)) . ")";

$result = $db->query($query);
$json = array();
while ($data = $result->fetchArray(SQLITE_NUM)) {
    $json[] = $data;
}

You'll need to do some different math for monthly data - try constructing 12 times with PHP's mktime() function.
Here are the references for the PHP implode() and range() functions I used.


text:
Q: How to special character after 3rd character in Oracle SQL query I want to add special character after 3rd character. Below is the example
Current Phone Number:- 123234567
Expected output     :- (123)234-567

How can I do this ?

A: Concatenation, as you said, along with the substr function:
SQL> with test (col) as
  2    (select 123234567 from dual)
  3  select '(' || substr(col, 1, 3) || ')' ||substr(col, 4, 3) ||'-'|| substr(col, 7) result
  4  from test;

RESULT
------------
(123)234-567

SQL>

Or, using regular expressions:
SQL> with test (col) as
  2    (select 123234567 from dual)
  3  select regexp_replace(col, '([0-9]{3})([0-9]{3})', '(\1)\2-') result_2
  4  from test;

RESULT_2
------------
(123)234-567

SQL>


text:
Q: Oracle Data Migration [data modification] - Data Tuning I'm facing with a data migration, my goal is update 2.5M of row in less than 8 hours, that's because the customer have a limited window of time where the service can be deactivated. Moreover the table can't be locked during this execution because is used by other procedures, I can lock the record only. The execution will done through batch process.
Probably in this case migration isn't the correct word, could be better say "altering data"...
System: Oracle 11g
Table Informations
Table name: Tab1
Tot rows: 520.000.000
AVG row len: 57
DESC Tab1;
Name             Null?    Type
---------------- -------- -----------
t_id             NOT NULL NUMBER
t_fk1_id                  NUMBER
t_fk2_id                  NUMBER
t_start_date     NOT NULL DATE
t_end_date                DATE
t_del_flag       NOT NULL NUMBER(1)
t_flag1          NOT NULL NUMBER(1)
f_falg2          NOT NULL NUMBER(1)
t_creation_date           DATE
t_creation_user           NUMBER(10)
t_last_update             DATE
t_user_update             NUMBER(10)
t_flag3                   NUMBER(1)

Indexs are:

*

*T_ID_PK [t_id] UNIQUE

*T_IN_1 [t_fk2_id,t_fk1_id,t_start_date,t_del_flag] NONUNIQUE

*T_IN_2 [t_last_update,t_fk2_id] NONUNIQUE

*T_IN_3 [t_fk2_id,t_fk1_id] NONUNIQUE

Currently I've thinked some possible solutions and most of that I've already test:

*

*Insert + delete: selecting the existing data, insert the new record with needed modification and delete the old one [this result as slowest method ~21h]

*Merge: use the merge command for update the existing data [this result as the fastest method ~16h]

*Update: update the existing data [~18h]

With the above solution I've faced some issues like: if executed wit /*+ parallel(x) / option the table was locked, the /+ RESULT_CACHE */ seem not affect at all the selection time.
My last idea is partition the table by a new column and use that for avoid table locking and proceed with the solution 1.

Here the query used for Merge option (for the others two is the same more or less):
DECLARE
v_recordset NUMBER;
v_row_count NUMBER;
v_start_subset NUMBER;
v_tot_loops NUMBER;
BEGIN
--set the values manually for example purpose, I've use the same values
v_recordset := 10000;
v_tot_loops := 10000;
  BEGIN
    SELECT NVL(MIN(MOD(m_id,v_recordset)), 99999)
    INTO v_start_subset
    FROM MIGRATION_TABLE
    WHERE m_status = 0; -- 0=not migrated , 1=migrated
  END;
  FOR v_n_subset IN v_start_subset..v_tot_loops
    LOOP
      BEGIN
        MERGE INTO Tab1 T1
        USING (
          SELECT m.m_new_id, c2.c_id, t.t_id
          FROM MIGRATION_TABLE m
            JOIN Tab1 t ON t.t_fk_id = m.m_old_id
            JOIN ChildTable c ON c.c_id = t.t_fk2_id
            JOIN ChildTable c2 ON c.c_name = c2.c_name --c_name is an UNIQUE index of ChildTable
          WHERE MOD(m.m_id,v_recordset) = v_n_subset
            AND c.c_fk_id = old_product_id --value obtained from another subsystem
            AND c2.c_fk_id = new_product_id --value obtained from another subsystem
            AND t.t_del_flag = 0 --not deleted items
        ) T2
        ON (T1.t_id = T2.t_id)
        WHEN MATCHED THEN
          UPDATE T1.t_fk_id = T2.m_new_id, T1.t_fk2_id = T2.c_id, T1.t_last_update = trunc(sysdate)
        ;
        --Update the record as migrated and proceed
        COMMIT;
      EXCEPTION WHEN OTHERS THEN
        ROLLBACK;
      END;
  END LOOP;
END;

In the above script I've deleted the parallel and cache options but I've already test is with both and I've not obtained any bug result.
Anyone, please! Could you guys help me with this, in more than one week I wasn't able to reach the desired timing, any ideas?

MIGRATION_TABLE
CREATE TABLE MIGRATION_TABLE(
 m_customer_from VARCHAR2(5 BYTE),
 m_customer_to VARCHAR2(5 BYTE),
 m_old_id NUMBER(10,0) NOT NULL,
 m_new_id NUMBER(10,0) NOT NULL,
 m_status VARCHAR2(100 BYTE),
 CONSTRAINT M_MIG_PK_1
 (
  m_old_id
 )
 ENABLE
)
CREATE UNIQUE INDEX M_MIG_PK_1 ON MIGRATION_TABLE (m_old_id ASC)

ChildTable
CREATE TABLE ChildTable(
 c_id NUMBER(10, 0) NOTE NULL,
 c_fk_id NUMBER(10, 0),
 c_name VARCHAR2(100 BYTE),
 c_date DATE,
 c_note VARCHAR2(100 BYTE),
 CONSTRAINT C_CT_PK_1
 (
  c_id
 )
 ENABLE
)
CREATE UNIQUE INDEX C_CT_PK_1 ON ChildTable (c_id ASC)
CREATE UNIQUE INDEX C_CT_PK_2 ON ChildTable (c_name ASC, c_fk_id ASC)

A: Method 2 is similar to Method 1, but it is using ROWIDs instead of a primary key. In theory, it should be therefore a bit faster.
CREATE TABLE migration_temp NOLOGGING AS
SELECT t.t_id,
       t.rowid    AS rid,
       m.m_new_id AS new_fk1_id,
       c2.c_id    AS new_fk2_id
  FROM MIGRATION_TABLE m
  JOIN Tab1 t        ON t.t_fk1_id = m.m_old_id
  JOIN ChildTable c1 ON c1.c_id = t.t_fk2_id
  JOIN ChildTable c2 ON c1.c_name = c2.c_name
 WHERE t.t_del_flag = 0
 ORDER BY t.rowid;
EXEC DBMS_STATS.GATHER_TABLE_STATS(null,'migration_temp');

MERGE INTO Tab1 t USING migration_temp m ON (t.rowid = m.rid)
 WHEN MATCHED THEN UPDATE SET
      t.t_fk1_id = m.new_fk1_id,
      t.t_fk2_id = m.new_fk2_id,
      t.t_last_update = trunc(sysdate);

You could think of batching the MERGE based on blocks of ROWIDs. Those tend to be logically colocated, therefore it should be a bit faster.

A: Wow, 520 million rows! However, updating 2.5 million of them is only 0.5%, that should be doable. Not knowing your data, my first assumption is that the self join of Tab1 x Tab1 inside the MERGE takes up most of the time. Possibly also the many joins to migration- and child_tables. And the indexes T_IN_1, 2, and 3 need maintenance, too.
As you say the rows to be updated are fixed, I'd try to prepare the heavy work. This doesn't lock the table and wouldn't count towards the downtime:
CREATE TABLE migration_temp NOLOGGING AS
SELECT t.t_id,
       m.m_new_id AS new_fk1_id,
       c2.c_id    AS new_fk2_id
  FROM MIGRATION_TABLE m
  JOIN Tab1 t        ON t.t_fk1_id = m.m_old_id
  JOIN ChildTable c1 ON c1.c_id = t.t_fk2_id
  JOIN ChildTable c2 ON c1.c_name = c2.c_name
 WHERE t.t_del_flag = 0;

I omitted the bit with the old/new product_ids because I didn't fully understand how it should work, but that is hopefully not a problem.
Method 1 would be a join via primary keys:
ALTER TABLE migration_temp ADD CONSTRAINT pk_migration_temp PRIMARY KEY(t_id);
EXEC DBMS_STATS.GATHER_TABLE_STATS(null,'migration_temp');

MERGE INTO Tab1 t USING migration_temp m ON (t.t_id = m.t_id)
 WHEN MATCHED THEN UPDATE SET
      t.t_fk1_id = m.new_fk1_id,
      t.t_fk2_id = m.new_fk2_id,
      t.t_last_update = trunc(sysdate);

I'm not a fan of batched updates. As you have time estimates, it looks like you have a test system. I'd suggest to give it a go and try it in one batch.

A: If method 1 and 2 are still too slow, you could follow your partitioning idea. For instance, introduce a column to distinguish the rows to be migrated. Because of DEFAULT ... NOT NULL this will be very fast:
ALTER TABLE Tab1 ADD (todo NUMBER DEFAULT 0 NOT NULL);

Now partition your table into two partions, one with the migration data, one with the rest that you will not touch. I don't have much experience with introducing partitions while the application is running, but I think it is solvable, for instance with online redefinition or
ALTER TABLE Tab1 MODIFY
  PARTITION BY LIST (todo) (
  PARTITION pdonttouch VALUES (0),
  PARTITION pmigration VALUES (1)
) ONLINE UPDATE INDEXES (
  T_ID_PK GLOBAL, T_IN_1  GLOBAL,
  T_IN_2  GLOBAL, T_IN_3  GLOBAL
);

Now you can identify the rows to be moved. This can be done row by row and doesn't affect the other processes and should not count towards your downtime. The migration rows will move from partition pdonttouch to partition pmigration therefore you need to enable row movement.
ALTER TABLE Tab1 ENABLE ROW MOVEMENT;
UPDATE Tab1 SET todo=1 WHERE .... JOIN ...;

Now you can work on the partition PMIGRATION and update the data there. This should be much faster than on the original table, as the size of the partition is only 0.5% of the whole table. Don't know about the indexes, though.
Theoretically, you could create a table with the same structure and data as PMIGRATION, work on the table, and once done, swap the partition and the working table with EXCHANGE PARTITION. Don't know about the indexes, again.


text:
Q: Is Declaring Multiple Variables on one line Faster than Declaring one Variable on Multiple Lines? If I were to do
age, height = 16, 1.24

would that be faster than
age = 16
height = 1.24

It would be a very small difference, but I imagine if you are declaring many variables, that time will add up.

A: import timeit

code1 = 'age, height = 16, 1.24'
code2 = '''age = 16
height = 1.24'''

print (timeit.timeit(stmt = code1, number = 1))
print (timeit.timeit(stmt = code2, number = 1))

I think declaring each variable separately would be much faster. Try seeing that with the help of the code above.


text:
Q: OnClickListener for child views when parent itself has OnClickListener I just experimented with setting an OnClickListener to a parent View and  an OnClickListener for every children. Without the children listener the parent listener would fire at any point in the layout but when I added children listeners only the listener associated with the child at that position fired. Is this the expected behavior? Where is this documented?

A: In an hierarchy of views starting with a parent view, a click event is "absorbed" by the 1st visible and enabled view (at the lower level) positioned at the physical area of the click event that has a registered listener.
Of course if needed, the invoked listener of that view may (or may not) trigger the click event of other views in the hierarchy but this is not the usual practice. For documentation, you may read this:
https://developer.android.com/guide/topics/ui/ui-events
especially the section "Event handlers", where there are mentioned ways for changing the above described default way of handling input events.


text:
Q: Why Tomcat 8.5 option allowLinking=true makes startup faster I'm trying to upgrade a web application from  Java 7/tomcat 7  to Java8/Tomcat 8.5.
Everything works well but tomcat startup time is twice slower on tomcat 8.5 (2min) than in tomcat7 (1 min). The most unbelievable is that using option allowLinking=true in my  context.xml makes my tomcat 8.5 starts quickly (about 1 min)
My problem is  that I'm running on windows and tomcat 8.5 documentation about this option says

This flag MUST NOT be set to true on the Windows platform

https://tomcat.apache.org/tomcat-8.5-doc/config/resources.html
Does anybody have an explanation ?
And should i use this option on my tomcat (windows)  against apache recommendation ...
Thanks.

A: It's simple Windows doesn't manage symlinks like in unix systems! one more point to use unix server system !


text:
Q: how to find footer's value of gridview on RowCommand event? I want to find footer's value on the event of RowCommand in vb.net??
I'm assigning footer's value run-time on RowCreated.
e.Row.Cells(2).Text = FOOTERVALUE
e.Row.Cells(1).Text = "Total Subjects"

And this footer is for Parent Grid. I'm using nested gridview.

A:  Protected Sub Gridview1RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles Gridview1.RowCommand
     Dim Lblcolval = CType(dgrd_WWWH.FooterRow.FindControl("yourcolumn") ,Label)
 End Sub

Protected Sub Gridview1_How_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles Gridview1.RowDataBound
  If e.Row.RowType And DataControlRowType.Footer Or (e.Row.RowState And DataControlRowState.Edit) > 0 Then
  Dim ddlresp As DropDownList = CType(e.Row.FindControl("ddlResp"), DropDownList)
  SrchWhoBind(ddlresp)
  ddlresp.SelectedValue = Convert.ToInt32(Session("Uname"))
  End If
End Sub

A: I got the solution, just needed to write the code in rowDataBound instead of rowCreated.


text:
Q: Need to solve equations which take vector inputs. I have tried with matlab solve() but I'm getting zeros for both tau_new & b rc=1;
x=linspace(0,1,1000);
R=exp(1).*x.*rc;
b0=.3614/sqrt(2);
eqn1=(b./(8*pi)).(1./R).(log(R./rc)+1)+(b./(2*b0))-tau_new==0,
eqn2=(b./(2*pi)).(1./R).(log(R./rc))+(b./(b0))-tau_new==0];
vars=[tau_new b];
[solv, solu] = solve(eqns, vars)
The goal is to have an expression relating tau_new with R i.e. tau_new=f(R) also b=f(R). Can someone help please?

A: You have
$$
\left\{
\begin{array}{lcr}
 \frac{\left(\log \left(\frac{R}{\text{rc}}\right)+1\right) b}{8 \pi  R}+\frac{b}{2 \text{b0}}-\tau &=&0 \\
 \frac{\log \left(\frac{R}{\text{rc}}\right) b}{2 \pi  R}+\frac{b}{\text{b0}}-\tau &=&0 \\
\end{array}
\right.
$$
or
$$
\left\{
\begin{array}{lcr}
G_1(R) b-\tau &=&0 \\
G_2(R)b-\tau &=&0 \\
\end{array}
\right.
$$
or
$$
\left(
\begin{array}{cc}
G_1(R) & -1 \\
G_2(R) & -1
\end{array}
\right)
\left(
\begin{array}{c}
b \\
\tau
\end{array}
\right) =
\left(
\begin{array}{c}
0 \\
0
\end{array}
\right)
$$
with $G_1(R) \ne G_2(R)$
so $\det \left(
\begin{array}{cc}
G_1(R) & -1 \\
G_2(R) & -1
\end{array}
\right) = G_2(R)-G_1(R) \ne 0$ and the only solution for this homogeneous system is $b = \tau = 0$


text:
Q: How to pass query params and headers in a single request using grape How to pass query params and headers in a single request using grape
How to use post and query string params. What is the difference between them. I am using grape restful-api. Grape
HTTP method: POST
headers:
key
secret
Query string parameters:
name
age
For example
 post :student do
   name= params[:name]
   id = params[:id]
   query = {:name =>name, :id =>id}
   headers['key'] = "1988340998981183787898977"
   headers['sign'] = "1jkhhhajkaghvhgghgh9883dmkjkjkjkjk40998aaaadf1234981183787898977"

       HTTParty.post(url, :headers => headers, :query => query)
    end

A: Headers are set in about the same way. You pass the headers option to your chosen HTTP method with a hash of the headers you would like to include:
HTTParty.post("http://rubygems.org/api/v1/gems/httparty/owners",
:query => { :email => "alan+thinkvitamin@carsonified.com" },
:headers => { "Authorization" => "THISISMYAPIKEYNOREALLY"})

for more details see Document


text:
Q: Popup window value is not getting reflected in parent window I tried to get value of pop up window in textbox of parent window. But it's not worked. Could any one helped on this?
Parent.jsp

<form action="FirstTest" method="post" id="TestForm">
   <input type="text" id="PrintHere"/ >

    Repository Link
</form>

Popup.jsp
<form id="PopUpForm">
    <input type="text" id="ddlNames">

    <input type="button" value="Select" onclick="SetName();" />
</form>

A: Change your code like below on Popup.jsp
<form id="PopUpForm">
    <input type="text" id="ddlNames">

    <input type="button" value="Select" onclick="SetName();" />
</form>


text:
Q: Spring Cloud Config Server: Mercurial? As far as I understood it is not possible to setup Spring Cloud Config server with Mercurial.
Maybe somebody encountered a similar request and knows of a workaround or a solution?
Thanks!

A: Turns out the solution is pretty simple. In your application.properties of the Spring Cloud Config Server application define:
# tells spring to run without git
spring.profiles.active=native
# where the .properties or .yml files will be located
spring.cloud.config.server.native.search-locations=file:///{user.home}/config-repo

Source: https://cloud.spring.io/spring-cloud-config/spring-cloud-config.html -> File system backend.


text:
Q: How to do this in mysql: "Select * from $table where varchar_number between numberInString1 and numberString2"; How can I implement something like this in mysql:
"SELECT * FROM $database_table
 WHERE satellite_derived_time
       BETWEEN '{$from_time}' AND '{$to_time}'";

Where '{$from_time}' is a number in varchar like "1000"
     and '{$to_time}' is a number in varchar too like "9999".

A: try this one-
SELECT * FROM $database_table WHERE (satellite_derived_time BETWEEN $from_time AND $to_time);


text:
Q: Mysterious, Native "A" Registry Key with Path: Registry\A I recently wrote a native NT registry editor for Windows, and ran it on Windows 7. To my surprise, in addition to the two standard root keys, MACHINE and USER, that are present on Windows XP, there was also a mysterious key named "A", that cannot be opened in any way, whether by permission changes or backup privileges or otherwise:

Does anyone know what this key is for? I don't believe it's for any software, because it was there before I installed anything on the machine, and I believe I saw it on another fresh installation as well. It's rather very suspicious, and I'm curious as to why it's there. (If I'm curious enough, I might end up writing a driver to open it up without a privilege check, to see what happens!)
(I wasn't sure whether to put this on SuperUser or StackOverflow, since I think it could go in either one. I could be wrong, though; sorry if this isn't the appropriate place.)
Edit:
If forgot to say, I don't believe you can even see this key using the Win32 API, like RegOpenKey -- you have to use the native API like NtEnumerateKey instead.

A: Here is the comment from one of our driver writers: "DISCACHE.sys driver seems to be caching system file attributes and using \REGISTRY\A in an undocumented way. This driver is part of the kernel so it can load any hive wherever it wants."

A: Interesting...
The key indeed can be opened with a relative path, but not with an absolute path.
And it seems to contain information about all file systems and whatnot. Looks mysterious, indeed...


text:
Q: Any smooth complex line bundle over a smooth manifold is a subbundle of a trivial bundle In the book Vector Bundles and K-Theory of Hatcher, it is proven (Proposition 1.4) that for any (continuous) vector bundle $E\to B$ with $B$ a compact Hausdorff space, $E$ is a subbundle of a trivial bundle. Also it is remarked that this can fail when $B$ is noncompact: the canonical line bundle over $\Bbb RP^\infty$ is an example that fails.
But I am curious about the following special situation: Suppose $L$ is a (smooth) complex line bundle over a smooth manifold $M$. Then is it true that $L$ is a subbundle of a trivial (complex) bundle over $M$?

A: Yes, provided $M$ is finite dimensional and smooth. The key property is that a vector bundle over such a manifold has can be covered by a finite set of local trivializations $\{(U_i,\varphi_i)\}_{i=1}^N$ (see this answer for details). Armed with these trivializations, one can embed $L$ in $M\times\mathbb{C}^N$ using partitions of unity.


text:
Q: WooCommerce Conditional Tag inside plugin I'm writing a small plugin to add some text above the 'Add To Cart' button on the WooCommerce product page.
My code:
add_action('woocommerce_before_add_to_cart_button', 'ddd_above_add_to_cart', 100);
function ddd_above_add_to_cart() {
    if(is_product_category('vss') ) {
        echo 'hello world';
        }
}

My problem is when I use the conditional tag is_product_category('vss') to display the text based on the product category.
I'm sure this error is occurring as the function is not running inside the loop, but I'm not sure how to change this.
Can anyone help me with this?

A: Thist function not working in product page
is_product_category()

So, for me the best options is first get the terms of the current post and the next step is get the name or slug, in this case i chose the category name
$product_cat_name = $term->name;

But you can chose the slug too (better option)
$product_cat_slug = $term->slug;

Here the documentation
https://developer.wordpress.org/reference/functions/get_the_terms/
Example for Category name
/*Write here your own functions */
    add_action('woocommerce_before_add_to_cart_button', 'ddd_above_add_to_cart', 100);
    function ddd_above_add_to_cart() {

            global $post;
            $terms = get_the_terms( $post->ID, 'product_cat' );
            $nterms = get_the_terms( $post->ID, 'product_tag'  );
            foreach ($terms  as $term  ) {
                $product_cat_id = $term->term_id;
                $product_cat_name = $term->name;
                break;
            }
           //compare current category name == any category name you want
            if($product_cat_name =='vss' ) {
                echo "This Work";
            }
    }

Example for Category Slug
/*Write here your own functions */
    add_action('woocommerce_before_add_to_cart_button', 'ddd_above_add_to_cart', 100);
    function ddd_above_add_to_cart() {

            global $post;
            $terms = get_the_terms( $post->ID, 'product_cat' );
            $nterms = get_the_terms( $post->ID, 'product_tag'  );
            foreach ($terms  as $term  ) {
                $product_cat_id = $term->term_id;
                $product_cat_name = $term->name;
                $product_cat_slug = $term->slug;
                break;
            }

            //compare current category slug == any category slug you want
            if($product_cat_slug =='any-slug-category' ) {
                echo "This Work";
            }
    }


text:
Q: Get SPList Items Column Titles and Column Data including the SPLookupFieldValue Below source printing only the List Items that are on the first page of the SPList. Not printing the ListItems data in other pages i.e., Page 2, Page 3 etc.
Also it is required to print SPLookupFieldValue, rather than suggesting some links any modifications to the below source that can meet the requirement is greatly appereciated
 static void Main(string[] args)
 {
    using (SPSite site = new SPSite("http://intranet.contoso.com"))
    {
      using (SPWeb web = site.OpenWeb())
      {
        // Get data from a list.
        SPList list = web.Lists["Products"];
        SPView view = list.DefaultView;

        SPListItemCollection items = list.GetItems(view);
        // Get a collection of view field names.
        StringCollection viewFields = view.ViewFields.ToStringCollection();
        // Print data for each item in the view.
        foreach (SPListItem item in items)
        {
          // Print the value of each view field.
          foreach (string fieldName in viewFields)
          {
            Console.WriteLine("{0} = {1}", fieldName, item[fieldName]);
          }
          Console.WriteLine();
        }
      }
    }
  Console.ReadLine();
}

Country Column is Lookup, so the data is printed with ID and value. Needs to print only the value.
    Product = Television
    Country  = 2;#uk
    Product = Car
    Country = 1;#india

A: First get items with list.GetItems()
Second check is the field lookup, get SPFieldLookupValue, then get the value.
static void Main(string[] args)
{
    using (SPSite site = new SPSite("http://intranet.contoso.com"))
    {
    using (SPWeb web = site.OpenWeb())
    {
        // Get data from a list.
        SPList list = web.Lists["Products"];
        SPView view = list.DefaultView;

        SPListItemCollection items = list.GetItems();
        // Get a collection of view field names.
        StringCollection viewFields = view.ViewFields.ToStringCollection();
        // Print data for each item in the view.
        foreach (SPListItem item in items)
        {
            // Print the value of each view field.
            foreach (string fieldName in viewFields)
            {
                SPField field = list.Fields.GetField(fieldName);
                if (field.Type == SPFieldType.Lookup)
                {
                    string strValue = item[fieldName].ToString();
                    string value = new SPFieldLookupValue(strValue).LookupValue;
                    Console.WriteLine("{0} = {1}", fieldName, value);
                }
                else
                {
                    Console.WriteLine("{0} = {1}", fieldName, item[fieldName]);
                }
            }
            Console.WriteLine();
        }
    }
    }
    Console.ReadLine();
}


text:
Q: Increasing size on /home/user I have a problem. While installing Ubuntu I accidently give my /home/ayoub 8 GB and all 50Gb is on /home. how can I increase the size of /home/ayoub if it's possible
sudo parted -l

Model: ATA ST1000LM035-1RK1 (scsi)
Disk /dev/sda: 1000GB
Sector size (logical/physical): 512B/4096B
Partition Table: gpt
Disk Flags:

Number  Start   End     Size    File system     Name                          Flags
 1      1049kB  473MB   472MB   ntfs            Basic data partition          hidden, diag
 2      473MB   578MB   105MB   fat32           EFI system partition          boot, esp
 3      578MB   595MB   16,8MB                  Microsoft reserved partition  msftres
 4      595MB   891GB   891GB   ntfs            Basic data partition          msftdata
 5      891GB   912GB   20,8GB  ext4
 6      912GB   916GB   4000MB  linux-swap(v1)
 7      916GB   1000GB  84,3GB  ext4

Model: ATA SanDisk SD8SNAT1 (scsi)
Disk /dev/sdb: 128GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:

Number  Start   End    Size    File system  Name                          Flags
 1      1049kB  274MB  273MB   fat32        EFI system partition          boot, esp
 2      274MB   290MB  16,8MB               Microsoft reserved partition  msftres
 3      290MB   128GB  127GB   ntfs         Basic data partition          msftdata
 4      128GB   128GB  523MB   ntfs         Basic data partition          hidden, diag

df -h

Filesystem      Size  Used Avail Use% Mounted on
udev            3,9G     0  3,9G   0% /dev
tmpfs           785M  2,1M  783M   1% /run
/dev/sda5        19G   17G  1,2G  94% /
tmpfs           3,9G   28M  3,9G   1% /dev/shm
tmpfs           5,0M  4,0K  5,0M   1% /run/lock
tmpfs           3,9G     0  3,9G   0% /sys/fs/cgroup
/dev/loop0       90M   90M     0 100% /snap/core/6818
/dev/loop4      1,0M  1,0M     0 100% /snap/gnome-logs/57
/dev/loop19     152M  152M     0 100% /snap/gnome-3-28-1804/36
/dev/loop7      194M  194M     0 100% /snap/mailspring/346
/dev/loop9       54M   54M     0 100% /snap/core18/782
/dev/loop10     3,8M  3,8M     0 100% /snap/gnome-system-monitor/70
/dev/loop14     2,3M  2,3M     0 100% /snap/gnome-calculator/260
/dev/loop13      15M   15M     0 100% /snap/gnome-characters/258
/dev/loop12     1,0M  1,0M     0 100% /snap/gnome-logs/61
/dev/loop15     141M  141M     0 100% /snap/gnome-3-26-1604/74
/dev/loop17     141M  141M     0 100% /snap/gnome-3-26-1604/82
/dev/loop18     4,2M  4,2M     0 100% /snap/gnome-calculator/352
/dev/loop20     4,2M  4,2M     0 100% /snap/gnome-calculator/406
/dev/loop22     3,8M  3,8M     0 100% /snap/gnome-system-monitor/77
/dev/loop24      15M   15M     0 100% /snap/gnome-characters/206
/dev/loop27      15M   15M     0 100% /snap/gnome-logs/45
/dev/loop28     3,8M  3,8M     0 100% /snap/gnome-system-monitor/81
/dev/loop29      90M   90M     0 100% /snap/core/6673
/dev/loop2      195M  195M     0 100% /snap/mailspring/326
/dev/loop8      152M  152M     0 100% /snap/gnome-3-28-1804/40
/dev/loop3      174M  174M     0 100% /snap/spotify/34
/dev/loop26      36M   36M     0 100% /snap/gtk-common-themes/1198
/dev/loop1       75M   75M     0 100% /snap/sqlitebrowser-casept/2
/dev/loop6      181M  181M     0 100% /snap/spotify/35
/dev/loop23      54M   54M     0 100% /snap/core18/941
/dev/loop11      15M   15M     0 100% /snap/gnome-characters/254
/dev/loop30     194M  194M     0 100% /snap/mailspring/338
/dev/loop25      92M   92M     0 100% /snap/core/6531
/dev/loop16     144M  144M     0 100% /snap/gnome-3-28-1804/23
/dev/loop21     175M  175M     0 100% /snap/spotify/32
/dev/loop5      141M  141M     0 100% /snap/gnome-3-26-1604/78
/dev/sda7        77G  6,8G   67G  10% /home
/dev/sda2        96M   31M   66M  32% /boot/efi
tmpfs           785M   16K  785M   1% /run/user/120
tmpfs           785M   32K  785M   1% /run/user/1000


text:
Q: Making a search engine of sorts and I'm stuck I'm writing a code using C# for my school. I'm a noob when it comes to programming and this is my first course in programming.
I'm making a program with menuchoices where the goal is to be able to save a string title and body in two vektors. Then you will have the option to search for a title and if your search matches with a existing title the title and body will show up on the screen. Then you'll also be able too look upp all saved titles and bodys in another menuchoice.
I'm stuck on case 2: were I need to make a search engine to find a title in bloggInlägg[0] and when my search matches both bloggInlägg0 and bloggInlägg1 should show up in the program.
Everything is written in swedish but

*

*menuchoice 1: is to add a title and body,

*menuchoice 2 is to search for a title and then displaying both the title and body,

*menuchoice 3 is to display all of my already made titles and bodys and

*menuchoice 4 is to stop the program.

Here's my code:
static void Main(string[] args)
{
    bool kör = true;
    List<string[]> bloggen = new List<string[]>();

    while (kör)
    {
        Console.WriteLine("[1] Lägg till ett nytt inlägg i bloggen:");
        Console.WriteLine("[2] Sök inlägg i bloggen: ");
        Console.WriteLine("[3] Skriv ut alla blogginlägg: ");
        Console.WriteLine("[4] Avsluta programmet: ");

        string[] bloggInlägg = new string[2];
        int menyVal;
        int.TryParse(Console.ReadLine(), out menyVal);

        switch (menyVal)
        {
            case 1:
                Console.WriteLine("Välj titel till inlägget: ");
                bloggInlägg[0] = Console.ReadLine();

                Console.WriteLine("Nu kan du skriva ditt inlägg: ");
                bloggInlägg[1] = Console.ReadLine();

                bloggen.Add(bloggInlägg);

                break;
            case 2:
                Console.WriteLine("Ange titel på inlägget du söker: ");
                string searchWord = Console.ReadLine();
                bool hittad = false;

                for (int i = 0; i < bloggInlägg.Length; i++)
                {
                    if (bloggInlägg[0] == searchWord) // om man ordet man söker efter matchar
                    {
                        hittad = true;
                        Console.WriteLine("Din sökning hittades: " + bloggInlägg[0]);
                    }
                }

                if (hittad == false) // om man ordet man söker efter inte matchar
                {
                    Console.WriteLine("Din sökning hittades inte");
                }
                break;
            case 3:
                Console.WriteLine("Här är en lista på alla blogginlägg du sparat: ");
                foreach (var item in bloggen)
                {
                    Console.WriteLine(item[0] + " " + item[1]);
                }
                break;
            case 4:
                Console.WriteLine("Hejdå");
                Console.ReadLine();
                kör = false;
                break;
        }
    }
}

A: The loop in case 2 is flawed.
I think you want to loop through all the items and, if the Title or Body contains the word, then print the Title.
for (int i = 0; i < bloggen.Count; i++)
{
    var currentBloggen = bloggen[i];
    if (currentBloggen[0].Contains(searchWord) || currentBloggen[1].Contains(searchWord))
    {
        hittad = true;
        Console.WriteLine("Din sökning hittades: " + currentBloggen[0]);
    }
}

It is worth a look at the foreach statement to:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in
This gives you slightly neater code:
foreach (var currentBloggen in bloggen)
{
    if (currentBloggen[0].Contains(searchWord) || currentBloggen[1].Contains(searchWord))
    {
        hittad = true;
        Console.WriteLine("Din sökning hittades: " + currentBloggen[0]);
    }
}

Then look at how to create a class: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes.
You could create a class called Bloggen with 2 properties, for the Title and Body and use that object for your bloggInlägg,
class Bloggen
{
    public string Title { get; set; }
    public string Body { get; set; }
}

This will make the code a lot easier to read.
foreach (var currentBloggen in bloggen)
{
    if (currentBloggen.Title.Contains(searchWord) || currentBloggen.Body.Contains(searchWord))
    {
        hittad = true;
        Console.WriteLine("Din sökning hittades: " + currentBloggen.Title);
    }
}

Finally, create a method in the Bloggen class called "IsMatch"
class Bloggen
{
    public string Title { get; set; }
    public string Body { get; set; }

    public bool IsMatch(string word)
    {
        return Title.Contains(searchWord) || Body.Contains(searchWord);
    }
}

And the loop becomes:
foreach (var currentBloggen in bloggen)
{
    if (currentBloggen.IsMatch(searchWord))
    {
        hittad = true;
        Console.WriteLine("Din sökning hittades: " + currentBloggen.Title);
    }
}

--- other changes are required to implement the class but I will leave that for you to discover :)


text:
Q: Is there a way to add conditions in vsTemplates? or a way to generate output projects based on user selections I have a requirement to generate a custom projects template. I am showing the wizard (using vsix project) to the user which has three check boxes in which user can select one or many of them, based on the selection the number of projects need to be created.
Suppose user choose one, then output solution must have one project.
Suppose user choose any two, then output solution must have those two projects.
At Present irrespective of selection three output projects are created. The root vsTemplate file looks like below, Is there a way achieve my requirement?
<ProjectCollection>
      <ProjectTemplateLink ProjectName="Cat">
        CatProject\Cat.vstemplate
      </ProjectTemplateLink>
      <ProjectTemplateLink ProjectName="Dog">
        DogProject\Dog.vstemplate
      </ProjectTemplateLink>
      <ProjectTemplateLink ProjectName="Lion">
        LionProject\Lion.vstemplate
      </ProjectTemplateLink>
</ProjectCollection>

I tried two ways of doing it
1)At run time changing the root vsTemplate file accordingly , but always output project is created based on the vsTemplate file which is already in zip folder in bin directory.
2)using Development tool environment automation object , adding or removing projects programatically in ProjectItemFinished method of IWizard interface ,Example:
Dte.Solution.AddFromTemplate( vsTemplatePath, NewProjectName)
The above line creates a new project but folder structure is missed, and it is difficult to tweak it.
Is there any easy way to do like this?
<ProjectCollection>
      if(cat is selected)
      <ProjectTemplateLink ProjectName="Cat">
        CatProject\Cat.vstemplate
       </ProjectTemplateLink>
        end if
      if(Dog is selected)
      <ProjectTemplateLink ProjectName="Dog">
        DogProject\Dog.vstemplate
      </ProjectTemplateLink>
      end if
      if(Lion is selected)
      <ProjectTemplateLink ProjectName="Lion">
        LionProject\Lion.vstemplate
      </ProjectTemplateLink>
      end if
</ProjectCollection>

A: I made it work using the second approach I tried. Here is the complete solution. Remember when we add new vstemplate file to the project build action type must be "vstemplate" , to tell soln.GetProjectTemplate to look for vstemplate type of file, otherwise it may throw an error.
In this way we can conditionally create projects.

 using EnvDTE;
  using EnvDTE80;

  DTE dte;

public void ProjectFinishedGenerating(Project project)
        {
            //Accessing DTE(Development tool environment) object should only be done on main thread, otherwise throw exception
            ThreadHelper.ThrowIfNotOnUIThread();
            Solution2 soln = (Solution2)dte.Solution;
            if (firstForm.IsCatSelected)
            {
                dte.Solution.AddFromTemplate(soln.GetProjectTemplate("Cat.vstemplate", "CSharp"), destinationDirectory + "\\Cat", "Cat");
            }
            if (firstForm.IsDogSelected)
            {
                dte.Solution.AddFromTemplate(soln.GetProjectTemplate("Dog.vstemplate", "CSharp"), destinationDirectory + "\\Dog", "Dog");
            }
        }

public void RunStarted(object automationObject,
            Dictionary<string, string> replacementsDictionary,
            WizardRunKind runKind, object[] customParams)
        {
            //Accessing DTE(Development tool environment) object should only be done on main thread, otherwise throw exception
            ThreadHelper.ThrowIfNotOnUIThread();
            destinationDirectory = replacementsDictionary["$destinationdirectory$"];

            dte = automationObject as DTE;
          }


text:
Q: I got garbled character with ibm_db@2.6.1 in nodejs project I am working on a nodejs project. There is company name 'ABC AEROLÍNEAS SA DE CV' in DB2. While using ibm_db@2.6.1 to get the name, it turned into 'ABC AEROL�NEAS SA DE CV' in my nodejs.
I tried to verify it by using python with ibm_db 3.0.1 and got 'ABC AEROL\xcdNEAS SA DE CV'. I think the '\xcd' should be correct since it displays 'ABC AEROLÍNEAS SA DE CV' in python console. Furthermore, I tested it by JDBC and got the correct name too.
I don't know why nodejs's ibm_db cannot get the correct name. Could someone help to check this? Thanks.
DB
DB
NodeJS
NodeJS
Python
Python

A: The hex value \xCD is an (extended) ASCII value. In UTF-8 you would need \xC3\x8D. In UTF-16 you would need \x00\xCD.
https://en.wikipedia.org/wiki/%C3%8D#Character_mappings
Do note that some Windows native programs will display invalid UTF-8 bytes as valid characters, when strictly they should be displaying � or similar.
If you use a JDBC based SQL editor, you would see � (or a null value) in your string


text:
Q: Cross-domain authentification with Spring Security I have a web application built on Spring framework and running on Tomcat (lets call it exampleA.com). It has an API method for authentification - /securityLogin
And i have another site on a different domain (exampleB.com) that have an ability to send authentification request to examleA.com via API. And if the authentification is succesfull, user must be redirected to exampleA.com and be already authentificated. It all works fine by this point, session is created on the server, but user is not authentificated on examleA.com after redirect. I understand that this is because of my applications based on different domains, but i have no idea how can i fix this. Any suggestions?

A: OK, i have found the solution. I've just added
xhrFields: {
              withCredentials: true
}

to my jQuery AJAX call, in order to allow JavaScript to pass my JSESSIONID cookie to the server


text:
Q: Run-time Error '1004': Method 'SaveAs' of object '_Workbook' failed I have a downloaded CSV file that I am trying to open and then save as an .xlsx file using code.  I am very very new to VB, and have just modified code that I have found to make things work.  Yesterday the code worked great, but today it stalls out on the "wb.SaveAs" line.  The odd thing about the error is that the file actually saved to the folder.  Any help would be appreciated.
Public Function Upload_New_Orders_Excel()

'the path to the excel workbook

Dim XcelFile As Excel.Application
Dim wb As Excel.Workbook
Dim strExcelPath As String

Set XcelFile = New Excel.Application

Set wb = XcelFile.Workbooks.Open("C:\Users\mpdav\downloads\orders_export_1.csv")

wb.SaveAs FileName:="C:\Users\mpdav\OneDrive\Documents\R&M Hospitality\At Your Door\Daily Reports\orders_export_1.xlsx", FileFormat:=51

wb.Close

Set XcelFile = Nothing

Kill "C:\Users\mpdav\downloads\orders_export_1.csv"

strExcelPath = "C:\Users\mpdav\OneDrive\Documents\R&M Hospitality\At Your Door\Daily Reports\orders_export_1.xlsx"

'import data from excel

Call DoCmd.TransferSpreadsheet(acImport, acSpreadsheetTypeExcel8, "temp_tbl_orders_export", "C:\Users\mpdav\OneDrive\Documents\R&M Hospitality\At Your Door\Daily Reports\orders_export_1.xlsx", True, "A1:BP1000")

Kill "C:\Users\mpdav\OneDrive\Documents\R&M Hospitality\At Your Door\Daily Reports\orders_export_1.xlsx"

End Function


text:
Q: Building a desktop app using ParaView API under the hood I have this workflow with ParaView where I
1) load a dicom,
2) load a state where I perform actions on the dicom (sources, filters, custom filters, etc).
3) apply a custom macro where I initialize everything.

Then I have some custom macros that moves lines in the final result.
I would like to make a desktop app with a simple UI where a I have one button that executes the 3 necessary steps to initialize everything. And then I have three buttons that executes the custom macros.
So I'm basically making a simpler ParaView.
I have used the trace function that ParaView has to make a python script with all the steps and then executing them in the pvpython shell to test if I reach the same result that in the ParaView GUI.
But a simple script that just load the dicom makes the windows (Visualization Toolkit - Win320OpenGL) not responding.
What do you think is the best approach to do this?

A: This is fully supported by ParaView, as ParaView is not only an application but also a framework.
This is documented here : https://www.paraview.org/Wiki/Writing_Custom_Applications
Examples are in ParaView code : https://gitlab.kitware.com/paraview/paraview/tree/master/Examples/CustomApplications
For follow-up questions, I would suggest asking on the ParaView Discourse : https://discourse.paraview.org/


text:
Q: Custom validation errors gets set multiple times I created a custom validation for one of my models properties the following way:
Model.validateAsync('minOsVersion', validateMinimumOsVersion, {message: 'Minimum OS Version incorrect'});
function validateMinimumOsVersion(err, done) {
    var requiredVersion = "some version";
    var givenVersion = this.minOsVersion;
    if (validator.validateSemanticVersionString(givenVersion, requiredVersion) < 0) {
      err('too_low');
    }
    done();
  }

This validation works fine, except the validation gets called multiple times (still no problem) but then adds the "minimum os version too low" error multiple times to the returned error object ob loopback.

Am i missing something or why is this error populated 12 times? if the validation for this specific case fails it should only be added once.
Any ideas? Thanks in advance.
Edit:
As per request, here is the other code that gets called after my upload method
Model.observe('before save', function(ctx, next) {
    if (ctx.instance) {
      analyseMetadata(ctx.instance, function(error, model) {
        if (error) { return next(error); }
        next();
      });
    } else {
      next();
    }
  });

  function analyseMetadata(model, cb) {
    extractMetadata(model, function(error, data){
      if (error) { return cb(error); }

      if (data && data.provisioning && data.metadata && data.entitlements) {
        model.updateAttribute("expires", data.provisioning.ExpirationDate);
        model.updateAttribute("created", data.provisioning.CreationDate);

        model.updateAttribute("appIdentifier", data.entitlements['application-identifier']);
        model.updateAttribute("teamIdentifier", data.entitlements['com.apple.developer.team-identifier']);

        model.updateAttribute("bundleIdentifier", data.metadata.CFBundleIdentifier);
        model.updateAttribute("displayName", data.metadata.CFBundleDisplayName);
        model.updateAttribute("bundleName", data.metadata.CFBundleName);
        model.updateAttribute("shortVersion", data.metadata.CFBundleShortVersionString);
        model.updateAttribute("bundleVersion", data.metadata.CFBundleVersion);
        model.updateAttribute("minOsVersion", data.metadata.MinimumOSVersion);
        model.updateAttribute("builtOsVersion", data.metadata.DTPlatformVersion);
      }
      cb(null, model);
    });
  }

what would be a better way to update attributes while uploading but not generating the validations multiple times

A: As I mentioned in the comment, the reason you're getting multiple validation errors is that you're calling updateAttribute() multiple times. Instead, consider using updateAttributes() (plural form) which should only invoke the validation method(s) once:
function analyseMetadata(model, cb) {
  extractMetadata(model, function(error, data){
    if (error) { return cb(error); }

    if (data && data.provisioning && data.metadata && data.entitlements) {
      model.updateAttributes({
        "expires": data.provisioning.ExpirationDate,
        "created": data.provisioning.CreationDate,
        "appIdentifier": data.entitlements['application-identifier'],
        // ...
      }, function updateCallback(updateErr, updatedModel) {
        if (updateErr) { return cb(updateErr); }

        cb(null, updatedModel);
      });
    }
  });
}

Note also that I added the callback for updating attributes. This is an asynchronous function and actually performs the update, so you need to execute your cb() callback after it is complete.


text:
Q: Enable sharing Spotify listening activity on Facebook via API? Is it possible to enable sharing listening activity with Facebook from the Spotify API?
SPSession seems to have functions around scrobbling:
-(void)setScrobblingState:(sp_scrobbling_state)state forService:(sp_social_provider)service callback:(SPErrorableOperationCallback)block;

If not, is it possible to know if a user has enabled sharing to Facebook?
Edit: Thanks for the answer! Looks like there's an enum sp_social_provider that has a possible value SP_SOCIAL_PROVIDER_FACEBOOK for use with the following functions:
setScrobblingUserName:password:forService:callback:
setScrobblingState:forService:callback:

A: You can use SPSession's fetchScrobblingStateForService:callback: to find out if scrobbling to a particular service is enabled.
To enable scribbling if it isn't enabled, you need to call  setScrobblingUserName:password:forService:callback: to set credentials for the service, then setScrobblingState:forService:callback: to enable it.
Set the state to SP_SCROBBLING_STATE_USE_GLOBAL_SETTING to keep the user's global preferences in your session (which is preferred).


text:
Q: Invalid patch path with AWS CLI? I am looking to rename some API Gateway API Keys that were kicked out automatically and named horribling. I tried using a patch op but I receive the following.
$ aws --region $REGION --profile $PROFILE apigateway update-api-key \
--api-key $KEY --patch-operations op=replace,path=/name,value=MessengerAPI

A client error (BadRequestException) occurred when calling the UpdateApiKey operation:
Invalid patch path  '/name' specified for op 'replace'. Must be one of:
[/description, /enabled]

Evidently this is not the way to do it? Is there another way to rename  keys that have already been generated?

A: Yes, there is currently no way to update the name of the API key. But I agree that this is suboptimal. We will look into it and try to address this issue, but cannot commit to a timeline.
I will update this post when we have more information.
Thanks,
Jurgen, API Gateway


text:
Q: How to attach window into the main window using tkinter? I want to know how to make my second window attach within my main window.
this is what i have done so far. i can't attach the second window into the main window
from tkinter import *
root = Tk()
root.title("Main Window")
width_value = root.winfo_screenwidth()
height_value = root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (width_value, height_value))

def new():
    floor_plan = Toplevel(root)
    floor_plan.title("Second Window")
    floor_plan.geometry("500x500+100+200")

class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        menu = Menu(self.master)
        self.master.config(menu=menu)
        fileMenu = Menu(menu, tearoff = 0)
        fileMenu.add_command(label="New", command=new)
        fileMenu.add_command(label="Exit", command=root.quit)
        menu.add_cascade(label="File", menu=fileMenu)

app = Window(root)
root.mainloop()


text:
Q: How to partition $[a,b]$ into $m$ equal sub-intervals and count the number of sub-intervals that intersect with a subset of $[a,b]$? Suppose we have a subset of $[a,b]$, where $a=0$ and $b=1$, such as
$$A_1=\left\{\frac{1}{2^x}+\frac{1}{2^y}+\frac{1}{2^z}:x,y,z\in\mathbb{Z}\right\}\cap[0,1]$$
Which is a subset of $[0,1]$
If we partition $[a,b]$ into $m$ sub-intervals of equal length, where in this case $a=0$ and $b=1$, how do we count the number of sub-intervals which interesect with $A_1$?
How do we generalize this for any $A_1$? Such that the function inside the brackets in the definition of the set is arbitrary?
Take for example:
$$A_1=\left\{\frac{x^2+xy+y^2}{xy}+\frac{\sqrt{2}}{2}:x,y\in\mathbb{Z}\right\}\cap[0,1]$$
(Note the number sub-intervals that intersect with $A_1$ should be less than $m$)
Attempt
generateA[c_Integer] :=
 Select[Union@
   Flatten[Table[
     1/2^x + 1/2^y + 1/2^z, {x, 1, c}, {y, x, c}, {z, y, c}]],
  0 <= # <= 1 &]

This generates $A_1$.
P[m_] := Interval /@ Partition[Subdivide[m], 2, 1]

This takes the $m$ sub-intervals, of equal length, of $[a,b]$
Total[Table[
Sign[Total[
Boole[Table[
IntervalMemberQ[P[m][[s]], generateA[100][[g]]], {g, 1,
Length[generateA[5]]}]]]], {s, 1, m}]]

This shows whether each element, for every c-value of $A_1$, belongs to one of the $m$ sub-intervals. If one element is in the $m$ sub-intervals, it is counted using boole; and, if multiple elements are counted, we add them up and using Sign to convert them to 1. If no elements are in the $m$ sub-intervals, the boole of all elements are zero and the sum of these booles is zero, hence the Sign is zero. We add the Signs of all sub-intervals to get the total number of sub-intervals intersecting with $A_1$.
The problem is as $m \to \infty$, it takes too much time to calculate all the sub-intervals that intersect with $A_1$. Is there a better way of doing this?

A: BinCounts is a bit of overkill but still efficient.  Beware the bins in the partition are disjoint.  I assumed the number 1 was meant to be in the last bin of the partition.
Block[{m = 1000},
  With[{seq = 2^Range[-Ceiling@Log2@N@m - 2., -1.]},
   Total[#] + 1 - Last[#] &@Unitize@BinCounts[
      Flatten@Outer[Plus, seq, seq, seq],
      {0., 1., 1./m}]
   ]] // RepeatedTiming

(*  {0.00024, 170}  *)

Floating-point is faster than exact integer/rational arithmetic, but you have to worry about round-off error.  Once m gets to 10^15 or 16^16, we need to switch to arbitrary-precision:
Block[{m = 10^16},
  With[{prec =
     If[# > MachinePrecision, #, MachinePrecision] &@Log10[10. m]},
   With[{seq = 2^Range[-Ceiling@Log2@N@m - SetPrecision[2, prec], -1]},
    Total[#] + 1 - Last[#] &@Unitize@BinCounts[
       Flatten@Outer[Plus, seq, seq, seq],
       {0, SetPrecision[1, prec], N[1/m, prec]}]
    ]]] // RepeatedTiming

(*  {0.29, 25024}  *)

Here's an exact rational-number computation:
Block[{m = 10^16},
  With[{k = Ceiling@Log2@N@m + 2},
   Total[#] + 1 - Last[#] &@Unitize@BinCounts[
      Total[Tuples[2^Range[-k, -1], 3], {2}],
      {0, 1, 1/m}]
   ]] // RepeatedTiming

(*  {0.646, 25024}  *)

If the end-points are supposed to belong to each bin, then this would need adjustment (and the bins would not, strictly speaking, form a partition).
P.S. I tried it with Tuples instead of Outer, but it was slower, especially for large m.
With[{k = Ceiling@Log2@N@m + 2.},
 Total[#] + 1 - Last[#] &@Unitize@BinCounts[
    Total[Tuples[2^Range[-k, -1.], 3], {2}],
    {0., 1., 1./m}]
 ]

P.P.S. Another way, with Floor:
Block[{m = 10^16},
  With[{prec =
     If[# > MachinePrecision, #, MachinePrecision] &@Log10[1000. m]},
   With[{seq = 2^Range[-Ceiling@Log2@N@m - SetPrecision[2, prec], -1]},
    Total[
     UnitStep[m - #] UnitStep[#] &@DeleteDuplicates@Floor[
        m*Flatten@Outer[Plus, seq, seq, seq]
        ]
     ]
    ]]] // RepeatedTiming

(*  {0.269, 25024}  *)


text:
Q: Crop JavaFX Image to square or Circle I need a function.
import javafx.scene.image.Image;

private Image cropImage(Image image) {
    // Cut Image to max Circle or square
    return Image;
}

The important thing is that I don't want to change the scale of the image but cut the maximum circle or square in the middle of the image.
I have been trying to do this for two days now.
Can you help me with this?
Thank you very much. Rene

A: Something like this:
public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Image img = new Image("https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Osias_Beert_the_Elder_-_Dishes_with_Oysters%2C_Fruit%2C_and_Wine_-_Google_Art_Project.jpg/350px-Osias_Beert_the_Elder_-_Dishes_with_Oysters%2C_Fruit%2C_and_Wine_-_Google_Art_Project.jpg");
        Image img2 = crop(img, false);
        Image img3 = crop(img, true);
        HBox box = new HBox(8, new ImageView(img),new ImageView(img2),new ImageView(img3));
        Scene scene = new Scene(box);
        stage.setScene(scene);
        stage.show();
    }

    private Image crop(Image img, boolean toCircle) {
        double d = Math.min(img.getWidth(),img.getHeight());
        double x = (d-img.getWidth())/2;
        double y = (d-img.getHeight())/2;
        Canvas canvas = new Canvas(d, d);
        GraphicsContext g = canvas.getGraphicsContext2D();
        if (toCircle) {
            g.fillOval(0, 0, d, d);
            g.setGlobalBlendMode(BlendMode.SRC_ATOP);
        }
        g.drawImage(img, x, y);
        return canvas.snapshot(null, null);
    }
}

A: You can do that via the setClip method of the ImageView.