text:
Q: javac -version command not found error in rhel 7.3 I followed this documentation to install java-1.8.0-openjdk-1.8.0.272.b10-1.portable.jdk.el.x86_64.tar.xz into RHEL 7.3.
In section 2.4. Installing OpenJDK on RHEL using an archive,
at the last step, 7.Verify that javac -version works without supplying the full path:
$ javac -version
-bash: javac:command not found

I have appended the .bashrc file in the respective user account as follows:
export JAVA_HOME=~/jres/java-8
export PATH="$JAVA_HOME/bin:$PATH"

The full path for JAVA_HOME was: /home/myaccount/jres/java_8
I also edited the .bash_profile inside the /root folder with the
export JAVA_HOME=/home/myaccount/jres/java-8

This helped root account user receive a valid response when typing echo $JAVA_HOME. But it did not solve the java command not found issue.
Will appreciate any inputs to help.


text:
Q: How to copy one NSMutablearray to another NSMutablearray? I know that you guys may feel that this is repetitive question. But I'm screwed up with this issue with my project.
Now moving to the issue, I have taken an NSMutableArray named arr1 that contains string values such as @"34", @"40" and so on. Now, I have second NSMutableArray named arr2. I have already tried below code.
[arr1 initWithObjects:@"1",@"2", nil];
arr2 = [[[NSMutableArray alloc] initWithArray:arr1 copyItems:YES] autorelease];

Then, I tried
NSString  *no = [arr2 objectAtIndex:0];
tst.text = no;

However, it gives me no value in my textbox.
If any1 can help me out with this would be great help.

A: [arr1 initWithObjects:@"1",@"2", nil];

makes no sense, what you probably want is to use the NSMutableArray:
NSArray *arr1 = [NSArray arrayWithObjects:@"1",@"2", nil];
NSMutableArray *arr2 = [arr1 mutableCopy];

NSLog(@"arr1: %p, %@", arr1, arr1);
NSLog(@"arr2: %p, %@", arr2, arr2);

NSLog output:
arr1: 0x7924c50, (
                 1,
                 2
                 )
arr2: 0x7924f00, (
                 1,
                 2
                 )

A: Your arr1 might be nil. It should be
arr1 = [[NSArray alloc] initWithObjects:@"1", @"2", nil];

A: Your arr1 must be nil otherwise you would crash, but more to the point you are creating the NSMutableArray incorrectly:
You should not really do alloc and init on separate lines
NSMutableArray *myArray = [NSMutableArray alloc];

NSLog(@"%@", [myArray class]);

//=> __NSPlaceholderArray

In this case the myArray pointer is pointing at a flyweight of type __NSPlaceholderArray which is most likely not what you want. You would prefer:
---------------------------------------

myArray = [[NSMutableArray alloc] init];

NSLog(@"%@", [myArray class]);

//=> __NSArrayM

You will also crash if you do have a legitimate NSMutableArray and you call initWithArray:  with:
[NSMutableArray initWithCapacity:]: method only defined for abstract class.

This is because the method is most likely defined on __NSPlaceholderArray

A: Are you trying [arr2 objectAtIndex:0] in the same method where arr2 is being created?
Maybe the problem is that you are using autorelease on your arr2. So, in other methods it may have lost its values.
I tried the following and it works for me:
NSMutableArray * arr1 = [[NSMutableArray alloc]initWithObjects:@"1", @"2", nil];
NSMutableArray * arr2 = [[[NSMutableArray alloc] initWithArray:arr1 copyItems:YES] autorelease];
NSString * no = [arr2 objectAtIndex:0];
NSLog(@"%@", no);

A: In addition to tia's answer: you need to allocate it first.
The method 'mutableCopy' will create a copy of the array, not of the elements inside it.
You could create a new immutable array with 'initWithArray:arr1 copyItems:YES' and subsequently create a mutable version of it by calling 'mutableCopy'.:
NSArray *arr1 = [[NSArray alloc] initWithObjects:@"1",@"2", nil];
NSMutableArray arr2 = [[[NSArray alloc] initWithArray: arr1 copyItems:YES] mutableCopy];

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access a variable in initializer file in Rails I have Devise and Devise_RPX_Connectable (https://github.com/chrisdebruin/devise_rpx_connectable) working (users can login with their facebook account). I'm using
rails -v 2.3.5 devise --version 1.0.8 devise_rpx_connectable --version 0.1.3

My question is how do I access the advanced user information in my controllers? Specifically the ones listed below are in my devise.rb file in the initializers directory.
config.rpx_auto_create_account = true # false if you don't want to create users automaticaly. True by default.
config.rpx_additional_user_data = [:verifiedEmail, :url, :providerName,:photo] # default [], get some extra profile info from RPXnow, default only a few fields are available in the rpx_user object (https://rpxnow.com/docs#profile_data)
config.rpx_extended_user_data = true # false by default, extended data only available for Plus and Pro RPX users (https://rpxnow.com/docs#api_auth_info)

Thanks,

A: I checked out the Devise source and it looks like those are using Rails' mattr_accessor method which should expose them publicly on the Devise module. You should be able to access them like so:
Devise.rpx_auto_create_account # returns true


text:
Q: How to get the size of kernel functions when compiling linux kernel? I know I can get the size of functions after compiling the kernel by using the command readelf -s vmlinux|grep "some function".
However, the question is:
I have a function pointer array which is like:
void* function_pointer[]={(void*)foo1,(void*)foo2,...(void)*foon}

and I have a array which needs to store the size of functions above which is like: int function_size[]={foo1_size,foo2_size...foon_size};
how can I know each function's size so I can give the function_size array values. Besides, the CONFIG_KALLSYMS is off, so I can not use symbol table.
Update:The reason why I want to get the size of a function is :
In the caller stack of a function, we can get the return address of the function, and the return address of the function's caller and etc. But in the code, we don't know these return addresses, we can only use function pointers which are the start addresses of these functions instead. To compare which function a return address in the caller stack belong to, my idea is get each function's size and check if a return address is within the scope of a function.


text:
Q: Too many initialisers error I am trying to run below code. I am getting too many initialiser error. I know some problem initialise the array here.
#include<stdio.h>
#include<conio.h>
#include<time.h>

int array[16][5]={
    {0,0,0,0,0},
    {0,0,0,0,1},
    {0,0,0,1,0},
    {0,0,0,1,1},
    {0,0,1,0,0},
    {0,0,1,0,1},
    {0,0,1,1,0},
    {0,0,1,1,1},
    {0,1,0,0,0},
    {0,1,0,0,1 },
    {0,1,0,1,0},
    {0,1,0,1,1},
    {0,1,1,0,0 },
    {0,1,1,0,1},
    {0,1,1,1,0 },
    {0,1,1,1,1},
    {1,0,0,0,0}
};

int main()
{
    int i,j;

    for(i=0;i<16;i++)
    {
        for(j=0;j<5;j++)
        {
            printf("welcome");
        }

    }
    return(0);

}

A: Your array has 17 elements, not 16

A: You've declared an array with 16 rows of 5 ints in each row. But you wrote 17 rows instead, exactly as the error message says - You're defining it with more elements than it should accept.
           ↓
int array[16][5]={
    {0,0,0,0,0},   //0
    {0,0,0,0,1},   //1
    {0,0,0,1,0},   //2
    {0,0,0,1,1},   //3
    {0,0,1,0,0},   //4
    {0,0,1,0,1},   //5
    {0,0,1,1,0},   //6
    {0,0,1,1,1},   //7
    {0,1,0,0,0},   //8
    {0,1,0,0,1 },  //9
    {0,1,0,1,0},   //10
    {0,1,0,1,1},   //11
    {0,1,1,0,0 },  //12
    {0,1,1,0,1},   //13
    {0,1,1,1,0 },  //14
    {0,1,1,1,1},   //15
    {1,0,0,0,0}    //16
    //Total of 17 elements
};


text:
Q: How to get the image of a window when we only know its window handle I am developing an application in C# and want to know how to get the screen shot image of any window when we only know its window handle. The functionality I am trying to achieve is to be able to just copy the screen shot of any window (it can be a whole application or a control inside an application) when I only know its window handle.
Example: I am running a calculator application, and Spy++. When I use find window functionality of the Spy++ and hover my mouse over different buttons of the calculator, it show different window handles. Lets say I hover mouse over "9" button in the calculator. Now as I know its window handle, I want to get image of the "9" button only. If I have window handle of the complete application then I want to be able to get the screen shot of that application only. Similar to Alt+PrintScr.

A: You'll need to use GetWindowRect.
Just like shown in this example.
Then you can use Graphics.CopyFromScreen as shown in this SO post c# Take a screenshot of specific area.
Putting it all together, you call GetWindowRect, which accepts an HWnd to get the rect of the window you want. Then you use those rect values with CopyFromScreen to capture your image.


text:
Q: How to Thumb Preview in Picture Box From Thumb Impression Device I am trying to preview an image in picture box from Thumb Impression device. I am doing this successfully on button click which shows an image of my thumb on button click. But my requirement is, when i keep my thumb it should immediately shows my thumb without button click. Following is the code which i am using in button click. Please anyone guide.
   private void GetMinDataBtn_Click(object sender, EventArgs e)
        {
            SGFingerPrintManager manager = new SGFingerPrintManager();
            int deviceInfo = manager.Init(SGFPMDeviceName.DEV_AUTO);
            deviceInfo = manager.OpenDevice(0);
            try
            {
                this.m_TestMin.Initialize();
                SGFPMDeviceInfoParam pInfo = new SGFPMDeviceInfoParam();
                deviceInfo = manager.GetDeviceInfo(pInfo);
                byte[] buffer = new byte[pInfo.ImageWidth * pInfo.ImageHeight]; //Here sometime it fails to load image through device. And sometimes it continously works without an issue.
                deviceInfo = manager.GetImageEx(buffer, 0x1388, (int)this.FDxPicBox.Handle, 50);
                if (manager.CreateTemplate(buffer, this.m_TestMin) == 0)
                {
                    this.FdxToFIRBtn.Enabled = true;
                    this.VerifyBtn.Enabled = true;
                    this.StatusBar.Text = "Get Minutiae Data Success";
                    deviceInfo = manager.CloseDevice();
                }
            }
            catch (Exception ex)
            {
                deviceInfo = manager.CloseDevice();
                MessageBox.Show(ex.ToString());
                this.StatusBar.Text = "Thumb data failed to get";
            }

        }


text:
Q: Upload image from C# program to SAP WSDL Web Service I would like to develop a C# app that uploads binary files (pdf/jpg) to an (SAP) WSDL WebService. What datatype should I use for this. Does someone has some examples?

A: You can use WCF to bind to the SAP service, and transport binary files between the two. Here are some links to start you off:
SO thread discussion on Binary Encoding in WCF
Working with Binary Data (WCF Data Services)
WCF BizTalk SAP Adapter
Let us know if you have a specific problem with any of these approaches.


text:
Q: Local complementation group of simple graphs This is my first time posting a question, so please excuse me for any incomplete or confusing descriptions.
Let's assume we start with one simple graph(no multi-edges and no loops of a vertex to itself), call this $g_1$, on $v$ vertices.
There are exactly $v$ local complementation operations ($lc$) for such a graph.
Now let us obtain all possible graphs, by repeated action of the $lc$'s, on $g_1$. This set, by definition is an orbit. Let's assume this results in $k$ graphs (which must be finite).
If we number these graphs, $1,\cdots,k$, we see that we can write the associated $lc$'s as permutations. Ex/ $lc_1 =(1,5)(3,8)\cdots$.
These $lc$'s therefore form the set of generators for the local complementation group that acts on the $k$ graphs.
The question is, what is this group?
We've done some numerical work on graphs up to and including 6 vertices. Amazingly (unless if there is a trivial reason for this) we always find either $S_k$ (the permutation group) or $A_k$ (the alternating group). We know what causes the distinction; namely whenever all the $lc$ generators are of even length we get $A_k$. In this sense we always get the maximal group on $k$ elements.
Thanks in advance for any help.
P.H.

A: This is not really an answer, but I strongly suspect that Theorem 14 in
Transitivity of local complementation and switching on graphs
Andrzej Ehrenfeucht , a, Tero Harju , b and Grzegorz Rozenberg , c
(discrete mathematics 2004)
Is fairly close to what you need.


text:
Q: How to skip the OPTIONS preflight request? I had developed a PhoneGap app which is now being transformed to a mobile website. Everything works smoothly besides one small glitch. I use a certain third party API via a POST request, which works fine in the app, but fails in the mobile website version.
After a closer look it seems like AngularJS (I guess the browser actually) is first sending an OPTIONS request. I learned a lot today about CORS, but I can't seem to figure out how to disable it altogether. I do not have access to that API (so changes at that side are impossible), but they have added the domain I am working on to their Access-Control-Allow-Origin header.
This is the code I am talking about:
        var request = {
                language: 'fr',
                barcodes: [
                    {
                        barcode: 'somebarcode',
                        description: 'Description goes here'
                    }
                ]
            };
        }
        var config = {
            headers: {
                'Cache-Control': 'no-cache',
                'Content-Type': 'application/json'
            }
        };
        $http.post('http://somedomain.be/trackinginfo', request, config).success(function(data, status) {
            callback(undefined, data);
        }).error(function(data, status) {
            var err = new Error('Error message');
            err.status = status;
            callback(err);
        });

How can I prevent the browser (or AngularJS) from sending that OPTIONS request and just skip to the actual POST request? I am using AngularJS 1.2.0.

A: When performing certain types of cross-domain AJAX requests, modern browsers that support CORS will insert an extra "preflight" request to determine whether they have permission to perform the action.
From example query:
$http.get( 'https://example.com/api/v1/users/' +userId,
  {params:{
           apiKey:'34d1e55e4b02e56a67b0b66'
          }
  }
);

As a result of this fragment we can see that the address was sent two requests (OPTIONS and GET). The response from the server includes headers confirming the permissibility the query GET. If your server is not configured to process an OPTIONS request properly, client requests will fail. For example:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: accept, origin, x-requested-with, content-type
Access-Control-Allow-Methods: DELETE
Access-Control-Allow-Methods: OPTIONS
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Methods: GET
Access-Control-Allow-Methods: POST
Access-Control-Allow-Orgin: *
Access-Control-Max-Age: 172800
Allow: PUT
Allow: OPTIONS
Allow: POST
Allow: DELETE
Allow: GET

A: I think best way is check if request is of type "OPTIONS" return 200 from middle ware. It worked for me.
express.use('*',(req,res,next) =>{
      if (req.method == "OPTIONS") {
        res.status(200);
        res.send();
      }else{
        next();
      }
    });

A: As what Ray said, you can stop it by modifying content-header like -
 $http.defaults.headers.post["Content-Type"] = "text/plain";

For Example -
angular.module('myApp').factory('User', ['$resource','$http',
    function($resource,$http){
        $http.defaults.headers.post["Content-Type"] = "text/plain";
        return $resource(API_ENGINE_URL+'user/:userId', {}, {
            query: {method:'GET', params:{userId:'users'}, isArray:true},
            getLoggedIn:{method:'GET'}
        });
    }]);

Or directly to a call -
var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': 'text/plain'
 },
 data: { test: 'test' }
}

$http(req).then(function(){...}, function(){...});

This will not send any pre-flight option request.
NOTE: Request should not have any custom header parameter, If request header contains any custom header then browser will make pre-flight request, you cant avoid it.

A: The preflight is being triggered by your Content-Type of application/json.  The simplest way to prevent this is to set the Content-Type to be text/plain in your case. application/x-www-form-urlencoded & multipart/form-data Content-Types are also acceptable, but you'll of course need to format your request payload appropriately.
If you are still seeing a preflight after making this change, then Angular may be adding an X-header to the request as well.
Or you might have headers (Authorization, Cache-Control...) that will trigger it, see:

*

*https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Preflighted_requests

A: Preflight is a web security feature implemented by the browser. For Chrome you can disable all web security by adding the --disable-web-security flag.
For example: "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\newChromeSettingsWithoutSecurity" . You can first create a new shortcut of chrome, go to its properties and change the target as above. This should help!

A: setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation
$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);


text:
Q: How can I find a new base location? I have picked up my old savegame for No Man's Sky: NEXT, and my existing base has been archived, as per the introduction screen, and I have the following quest.

So I assume I just need to find a base area with the beginning base building to restore my base. However, when I scan a planet, I can get a message telling me there is a location, but it does not show up on my radar.

So I have no way of finding it without just flying around in circles scanning constantly. How can I accurately and easily locate a new secure base location?

A: The process for building bases has changed in the NEXT update.
Starting a new base
Just find a spot you like the look of and build a Base Computer. It's in the quick build menu, z on PC, I believe is d-pad down on a controller.
Build your case computer, and interact with it. This will kick off the process, where the game will allow you to claim the area. After this your build menu will include all your base items and you're ready to start construction.
Recalling an existing base
You will need to obtain Navigation Data items, either from finding them in Outposts and containers, or buying them from the Galactic Trade Network. Buy quite a few, about 30.
Go to your chosen planet and build a Signal Booster from your quick build menu. Place this and interact with it. Select the option to use 1 Navigation Data, and proceed to scan the planet for 'Habitable outposts'. Hopefully you'll see 'Shelter found' and it will be marked as 'Habitable base'.
You are looking for a Habitable Base to show up. Just keep trying until you find one. If you feel unlucky, pickup your Signal Booster, and fly to another area.
Once you've identified the spot, fly over there, and you should see a huge flat open area, just like in the Foundation update. There should be a Base Computer in the middle of the area.
Interact with this base computer and you'll be able to restore your base.
Video for reference
It seems that existing bases are re-loaded 'as-is' meaning all your storage is restored as well.
The process is detailed in this Reddit post.

A: I stumbled upon a way to reclaim your archived base with one scan and one scan data by utilizing the new feature of uninhabited star systems.

*

*travel to an uninhabited solar system (system without dominant species and without space station);

*land on a planet that is not marked as "dead";

*build a signal booster and scan for habital outpost;

*a base terminal will show up on first try.

My understanding of this is that since it is an uninhabited solar system, "habital" structures can only be "future" habitats = base terminals


text:
Q: Pass dynamic module into another module I don't know how to phrase this or even how to start, I'm trying to figure out how to use the dynamic module:
import('./icons/checkmark').then((module) => { return module.default() })

and pass that module into another module:
render() {
   return <Valid icon={<Checkmark />} />
}

for the life of me, I don't even know where to begin searching.


text:
Q: Find the angle in the triangle The triangle $ABC$ is isosceles at $A$ with $\angle BAC=20^o$. The points $D$ and $E$ are on the sides $[AB]$ and $[AC]$, respectively. We know that $\angle EBC=40^o$ and $\angle BCD=50^o$. What is the measure of $\angle BED$?
What I did: since $ABC$ is isosceles at $A$ and $\angle BAC=20^o$, we get that $\angle ABC=\angle BCA=80^o$. Therefore, we have $\angle DBE=40^o$ and $\angle BCD=50^o$. Moreover, the lines $(EB)$ and $(CD)$ are perpendicular. It follows that $\angle BEC=60^o$ and $\angle BDC=50^o$.
All the angles of the "butterfly" BDCE are known, and we know the angle $\angle EBC$. So the $\angle BED$ should not be too complicated to get, but I am stuck. Any idea?

A: This is an easier version of the classical problem since one of the lines is an angle bisector and can be solved using congruences.
Let $BE$, $CD$ intersect in $O$. $\triangle BOD  \cong \triangle BOC$ using $ASA$ since $BE$ is angle bisector. Hence $OD=OC$.
Thus $\triangle DOE \cong \triangle COE$ using $SAS$. Hence
$$\angle BED = \angle BEC=60^{\circ}$$

A:
As $\angle BCD = 50^0, \angle CBE = 40^0$, we have $\angle BFC = 90^0$.
Please note as $\angle DBF = \angle CBF$ and $BF \perp CD$, $BF$ is perpendicular bisector of $CD$. So, $DF = FC$ and $EF \perp CD$.
That leads to $\triangle DFE \cong \triangle CFE$. So, $\angle CDE = \angle DCE = 30^0$ and $\angle BED = \angle BEC = 60^0$.


text:
Q: limit of expression with first and second derivatives I got the expression: $$\frac{X'(t) X''[t]+Z'(t) Z''(t)}{\sqrt{X'(t)^2+Z'(t)^2}}$$
How do I find the limit when I get to a point with $X'(t)=Z'(t)=0$, it's like everytime it happens, the limit is $\pm\sqrt{X^{\prime\prime }(t)^2+Z^{\prime\prime }(t)^2}$ is this explainable?

A: I'd suggest the following. First, let $t_0$ be a value such that $X'(t_0)=Z'(t_0)=0$. Evaluate the following limit :
$$\begin{eqnarray} L^2 &=& \lim_{t\to t_0} \left(\frac{X'(t)\, X''(t) + Z'(t)\, Z''(t)}{\sqrt{X'(t)^2 + Z'(t)^2}} \right)^2 \\ &=& \lim_{t\to t_0} \frac{\left(X'(t)\, X''(t) + Z'(t)\, Z''(t)\right)^2}{X'(t)^2 + Z'(t)^2}\end{eqnarray}$$
Apply l'Hospital rule to get :
$$\begin{eqnarray} L^2 &=& \lim_{t\to t_0} \frac{2\, \left(X'(t)\, X''(t) + Z'(t)\, Z''(t)\right)\left(X''(t)^2 + X'(t)\, X'''(t) + Z''(t)^2 + Z'(t)\, Z'''(t)\right)}{2 X'(t)\, X''(t) + 2 Z'(t)\, Z''(t)} \\ &=& \lim_{t\to t_0} \left(X''(t)^2 + X'(t)\, X'''(t) + Z''(t)^2 + Z'(t)\, Z'''(t)\right) \end{eqnarray}$$
Knowing that $X'(t_0)=Z'(t_0)=0$, you can conclude that $L^2 = X''(t_0)^2  + Z''(t_0)^2$.


text:
Q: Adding Label (Text box style) to Folium Output I have a folium map on which I am trying to add a textbox which I would always like on screen with additional details and can't seem to find a way to get one to popup.
I tried something like a colormap
import branca.colormap as cm
colormap = cm.linear.Set1.scale(0, 35).to_step(10)
colormap.caption = 'A colormap caption'
map.add_child(colormap)

or an image by the following
FloatImage(img_link, bottom=60, left=70).add_to(map)

It seems that adding a text box with 4/5 lines of information should be pretty simple, but I can't seem to find a way to overlay one over Folium. So I really hope someone could point me to the right direction.
The one idea I possibly had left would be to add in iFrame, but not too sure how I could get that to work.

A: The following code should work:
import folium

from folium import IFrame

text = 'your text here'

iframe = folium.IFrame(text, width=700, height=450)
popup = folium.Popup(iframe, max_width=3000)

Text = folium.Marker(location=[lat,lon], popup=popup,
                     icon=folium.Icon(icon_color='green'))
Yourmap.add_child(Text)

Yourmap.save('mymap.html')


text:
Q: Что такое множество классов вычетов по модулю n? Что такое сравнимы 2 числа по модулю я знаю, это когда a ≡ b (mod n)
если n делит (a - b)
Что такое множество классов вычетов по модулю n?
с источников я понял что обозначаеться как Zn, где n - это и есть модуль.
пример Zn = {[0], [1],  [2]},  каждый єлемент называеться классом эквивалентности?
И что такое класс вычетов?
это когда в каждом классе єквивалентности  есть множество в котором каждые 2 пары элементов сравнимы  по модулю?
пример:
[0] = [....-6,-3,0, 3,6.....]   тут модулю n = 3.
И что в теме сравнимости значит этот символ "⊕"???. это операция с классами эквивалентности?

A: Множество классов вычетов по модулю m - это множество чисел 0,1,...,m-1. Обозначается
На множестве Z/mZ определены операции сложения, вычитания, умножения и деления. Я обозначу их [+], [-], [*] и [/], чтобы отличать от обчных операций сложения и умножения целых чисел:

*

*a [+] b = (a+b)%m - остаток от деления обычной суммы a и b на m,

*a [*] b = (a*b)%m - остаток от деления обычного произведения a и b на m,

*[-]a = m - a, и [-]0 = 0. Соответственно a [-] b = a [+] ([-]b)
Деление - самая хитрая операция в множестве вычетов. a [/] b - это такое число c, что b [*] c = a. Так вот, в отличие от целых чисел, которые делятся друг на друга довольно редко, классы вычетов делятся друг на друга почти всегда. Для этого необходимо и достаточно, чтобы a и b не имели общих делителей с m. Если m - простое число, то все ненулевые пары a и b можно делить. Для деления Z/mZ используется расширенный алгоритм Евклида.
Как это связано с классами эквивалентности. Возьмем ваш пример Z3 = {[0],[1],[2]}
Класс эквивалентности [0] обозначает все те целые числа, которые при делении на 3 дадут остаток 0: [0] == {0, ±3, ±6, ±9, ...}
Класс эквивалентности [1] обозначает все те целые числа, которые при делении на 3 дадут остаток 1: [1] == {1, -2, 4, -5, 7, -8, 10 ...}
Класс эквивалентности [2] обозначает все те целые числа, которые при делении на 3 дадут остаток 2: [2] == {2, -1, 5, -4, 8, -7, 11 ...}
Операции с классами эквивалентности определяются так (для определённости рассмотрим сумму): давайте возьмём из каждого класса по одному представителю, сложим их и в качестве результата возьмём класс эквивалентности получившейся суммы. Например [1] [+] [2] - возьмём из [1] число 1, а из [2] возьёмем 2. 1+2 = 3. Класс эквивалентности, к которому принадлежит 3 - это [0]. Следовательно, [1] [+] [2] = [0]
Несложно доказать, что эти операции сводятся к операциям по модулю, как я написал выше, за исключением деления. Поэтому в реальной жизни никто не морочит себе голову классами эквивалетности, а просто рассматривают числа по модулю.


text:
Q: get thumbnail original image I need to get the original image for the image type attribute like the default one of thumbnail or small_image on the admin side.  You can't seem to use $_prod->getMediaGalleryImages() because if the image is marks as excluded then it an image will not show up there, which makes sense since it's to excluded it from the gallery.  You can do something like this
<?php
        $_prod = Mage::getModel('catalog/product')->load($product->getId());
        $types=array();
        foreach ($_prod->getMediaAttributes() as $attribute) {
            $types[] = $attribute->getAttributeCode();
        }

        echo "PROD", PHP_EOL;
        echo  "id=>",$product->getId(), PHP_EOL;
        echo  "imageTypes=>",$product->getId(), PHP_EOL;

        //var_dump($imageTypes);
        $attrImgs=array();
        foreach ($types as $type){
            $imgHelper = Mage::helper('catalog/image');
            $filename = "";
            try{
                $filename = Mage::helper('catalog/image')->init($_prod, $type);
            }catch(Exception $e){}
            echo " ==>",$type, PHP_EOL;
            $attrImgs[$type] = $filename."";//force string output
            echo "  ==>",$filename, PHP_EOL;
        }

Which will get you all the assigned images but, they are the cached url paths.  Not what I want.  I know the image name is in the url as /n/a/name-of-original-file/cached.jpg where name-of-original-file is the original name with out the but processing the string to get that is well not what I want to do.  looking at Mage::helper('catalog/image')->init($_prod, $type);  shows there is a protect var of _imageFile which is what I seem to need.
I can't seem to find out where I can grab file path or name with out having to pull it through Mage_Catalog_Helper_Image.  What I want to end up with is a list of images and the type it belongs to.  I have the types done, but I can only get the cached url for the image.  Any ideas?

A: You can use
$product->getImageUrl();

If you just need the main image, otherwise:
$product->getMediaGallery('images');

Which will return an array, even if marked as exclude.


text:
Q: Hard disk's too slow to play a huge raw AVI file I have a huge AVI file. The video player (VLC) stops every about 10 seconds because the HDD doesn't read fast enough. (details here)
I want to be able to play this video. Anyone knows a workaround?
Is it possible to load up a larger part of the video in the RAM maybe? Is there a way to do that in VLC? Or another Video player that can do that?
edit:
here's part of the output of running vlc with the -vvv parameter. I captured the part when the playback stopped. The output covers two stops.
[0x19159f8] pulse audio output debug: resuming after 68308432 us
[0x19159f8] pulse audio output debug: suspended
[0x19159f8] pulse audio output debug: started
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: changing sink 2: alsa_output.usb-0d8c_USB_PnP_Sound_Device-00-Device.iec958-stereo (CM108 Audio Controller Digital Stereo (IEC958))
[0x7fa92c001248] main vout display debug: auto hiding mouse cursor
[0x19159f8] main audio output debug: resampling stopped (drift: -786 us)
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 56 ms)
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 39 ms)
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 22 ms)
[0x7fa980c56038] main video output debug: picture might be displayed late (missing 6 ms)
[0x19159f8] pulse audio output debug: underflow
[0x7fa9400009b8] main input error: ES_OUT_SET_(GROUP_)PCR  is called too late (pts_delay increased to 361 ms)
[0x7fa9400009b8] main input error: ES_OUT_RESET_PCR called
[0x7fa938c0bfe8] main decoder warning: early picture skipped
[0x7fa938c0bfe8] rawvideo decoder warning: invalid frame size (128 < 3110400)
[0x7fa938da48b8] main decoder debug: End of audio preroll
[0x19159f8] pulse audio output debug: underflow
[0x7fa9400009b8] main input debug: Buffering 0%
[0x7fa938c0bfe8] main decoder debug: End of video preroll
[0x7fa938c0bfe8] main decoder debug: Received first picture
[0x7fa9400009b8] main input debug: Buffering 6%
[0x7fa9400009b8] main input debug: Buffering 13%
[0x7fa9400009b8] main input debug: Buffering 20%
[0x7fa9400009b8] main input debug: Buffering 27%
[0x7fa9400009b8] main input debug: Buffering 34%
[0x7fa9400009b8] main input debug: Buffering 41%
[0x7fa9400009b8] main input debug: Buffering 48%
[0x7fa9400009b8] main input debug: Buffering 55%
[0x7fa9400009b8] main input debug: Buffering 62%
[0x7fa9400009b8] main input debug: Buffering 69%
[0x7fa9400009b8] main input debug: Buffering 76%
[0x7fa9400009b8] main input debug: Buffering 82%
[0x7fa9400009b8] main input debug: Buffering 89%
[0x7fa9400009b8] main input debug: Buffering 96%
[0x7fa9400009b8] main input debug: Stream buffering done (375 ms in 471 ms)
[0x7fa9400009b8] main input debug: Decoder buffering done in 0 ms
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 49 ms)
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 33 ms)
[0x7fa980c56038] main video output debug: picture might be displayed late (missing 16 ms)
[0x7fa980c56038] main video output debug: picture might be displayed late (missing 3 ms)
[0x7fa9400009b8] main input error: ES_OUT_SET_(GROUP_)PCR  is called too late (pts_delay increased to 362 ms)
[0x7fa9400009b8] main input error: ES_OUT_RESET_PCR called
[0x7fa938c0bfe8] main decoder warning: early picture skipped
[0x7fa938c0bfe8] rawvideo decoder warning: invalid frame size (128 < 3110400)
[0x7fa938da48b8] main decoder debug: End of audio preroll
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x7fa9400009b8] main input debug: Buffering 0%
[0x7fa938c0bfe8] main decoder debug: End of video preroll
[0x7fa938c0bfe8] main decoder debug: Received first picture
[0x7fa9400009b8] main input debug: Buffering 6%
[0x7fa9400009b8] main input debug: Buffering 13%
[0x7fa9400009b8] main input debug: Buffering 20%
[0x7fa9400009b8] main input debug: Buffering 27%
[0x7fa9400009b8] main input debug: Buffering 34%
[0x7fa9400009b8] main input debug: Buffering 41%
[0x7fa9400009b8] main input debug: Buffering 48%
[0x7fa9400009b8] main input debug: Buffering 55%
[0x7fa9400009b8] main input debug: Buffering 62%
[0x7fa9400009b8] main input debug: Buffering 68%
[0x7fa9400009b8] main input debug: Buffering 75%
[0x7fa9400009b8] main input debug: Buffering 82%
[0x7fa9400009b8] main input debug: Buffering 89%
[0x7fa9400009b8] main input debug: Buffering 96%
[0x7fa9400009b8] main input debug: Stream buffering done (375 ms in 436 ms)
[0x7fa9400009b8] main input debug: Decoder buffering done in 0 ms
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] main audio output warning: playback way too early (-390096): playing silence
[0x19159f8] main audio output debug: inserting 17203 zeroes
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 21 ms)
[0x7fa980c56038] main video output debug: picture might be displayed late (missing 4 ms)
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 56 ms)
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 39 ms)
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 23 ms)
[0x7fa980c56038] main video output debug: picture might be displayed late (missing 6 ms)
[0x7fa9400009b8] main input error: ES_OUT_SET_(GROUP_)PCR  is called too late (pts_delay increased to 363 ms)
[0x7fa9400009b8] main input error: ES_OUT_RESET_PCR called
[0x7fa938c0bfe8] main decoder warning: early picture skipped
[0x7fa938c0bfe8] rawvideo decoder warning: invalid frame size (128 < 3110400)
[0x7fa938da48b8] main decoder debug: End of audio preroll
[0x19159f8] pulse audio output debug: underflow
[0x19159f8] pulse audio output debug: underflow
[0x7fa9400009b8] main input debug: Buffering 0%
[0x7fa938c0bfe8] main decoder debug: End of video preroll
[0x7fa938c0bfe8] main decoder debug: Received first picture
[0x7fa9400009b8] main input debug: Buffering 6%
[0x7fa9400009b8] main input debug: Buffering 13%
[0x7fa9400009b8] main input debug: Buffering 20%
[0x7fa9400009b8] main input debug: Buffering 27%
[0x7fa9400009b8] main input debug: Buffering 34%
[0x7fa9400009b8] main input debug: Buffering 41%
[0x7fa9400009b8] main input debug: Buffering 48%
[0x7fa9400009b8] main input debug: Buffering 55%
[0x7fa9400009b8] main input debug: Buffering 61%
[0x7fa9400009b8] main input debug: Buffering 68%
[0x7fa9400009b8] main input debug: Buffering 75%
[0x7fa9400009b8] main input debug: Buffering 82%
[0x7fa9400009b8] main input debug: Buffering 89%
[0x7fa9400009b8] main input debug: Buffering 96%
[0x7fa9400009b8] main input debug: Stream buffering done (375 ms in 486 ms)
[0x7fa9400009b8] main input debug: Decoder buffering done in 0 ms
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 56 ms)
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 39 ms)
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 23 ms)
[0x7fa980c56038] main video output debug: picture might be displayed late (missing 6 ms)
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 65 ms)
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 49 ms)
[0x7fa980c56038] main video output warning: picture is too late to be displayed (missing 32 ms)
[0x7fa980c56038] main video output debug: picture might be displayed late (missing 15 ms)
[0x7fa9400009b8] main input error: ES_OUT_SET_(GROUP_)PCR  is called too late (pts_delay increased to 364 ms)
[0x7fa9400009b8] main input error: ES_OUT_RESET_PCR called
[0x7fa938c0bfe8] rawvideo decoder warning: invalid frame size (128 < 3110400)
[0x19159f8] pulse audio output debug: underflow
[0x7fa938da48b8] main decoder debug: End of audio preroll
[0x7fa938c0bfe8] main decoder debug: End of video preroll
[0x7fa938c0bfe8] main decoder debug: Received first picture
[0x7fa9400009b8] main input debug: Buffering 0%
[0x19159f8] pulse audio output debug: underflow
[0x7fa9400009b8] main input debug: Buffering 6%
[0x7fa9400009b8] main input debug: Buffering 13%
[0x7fa9400009b8] main input debug: Buffering 20%
[0x7fa9400009b8] main input debug: Buffering 27%
[0x7fa9400009b8] main input debug: Buffering 34%
[0x7fa9400009b8] main input debug: Buffering 41%
[0x7fa9400009b8] main input debug: Buffering 48%
[0x7fa9400009b8] main input debug: Buffering 54%
[0x7fa9400009b8] main input debug: Buffering 61%
[0x7fa9400009b8] main input debug: Buffering 68%
[0x7fa9400009b8] main input debug: Buffering 75%
[0x7fa9400009b8] main input debug: Buffering 82%
[0x7fa9400009b8] main input debug: Buffering 89%
[0x7fa9400009b8] main input debug: Buffering 96%
[0x7fa9400009b8] main input debug: Stream buffering done (375 ms in 440 ms)
[0x7fa9400009b8] main input debug: Decoder buffering done in 0 ms
[0x19159f8] pulse audio output debug: changing sink 2: alsa_output.usb-0d8c_USB_PnP_Sound_Device-00-Device.iec958-stereo (CM108 Audio Controller Digital Stereo (IEC958))
[0x7fa92c001248] main vout display debug: auto hiding mouse cursor
[0x19159f8] pulse audio output debug: suspended
[0x19159f8] pulse audio output debug: changing sink 2: alsa_output.usb-0d8c_USB_PnP_Sound_Device-00-Device.iec958-stereo (CM108 Audio Controller Digital Stereo (IEC958))

A: Unfortunately I'm not able to comment yet. Can you run VLC with -vvv option:
vlc -vvv video.avi

and provide some output so we can better understand what is happening there. Thanks.
Edit:
You also could try to increase Caching value in VLCs settings. Go to Media -> Open Multiple Files then go to File tab and set the checkbox Show more options:


text:
Q: How can I send a struct of arrays into a function when using the String object? I'm learning to code c++ and I've come to this problem:
I have this struct:
struct storeData
{
  string name;
  string username;
  string fav_food;
  string fav_color;

}data[30];

And I need to check if two usernames are equal so I made this statement:
  for(i=0;i<c;i++){

          if(data[c].username.compare(data[i].username)==0){
            cout<<"Username already taken"<<endl;
          }
  }

And it works well, the problem that I have is that I'm required to make a function let's call it: isTaken that returns the error message, so I can use it whenever I need to for example delete a username so I don't have to copy/paste the code again.
So I began looking for an answer for that, many forums present a way to send the whole struct like this:
void isTaken(struct storeData *data)
which I understand but because I'm using string is not working, so I guess it's because string is an object? I'm using the library <string> I'm sorry if I'm not being that clear at the moment, I'm looking for a way to use isTaken(data[c].user); but I don't know how to declare the function, I think is also because string is not the same as C string but I'm not really sure I've been looking for a solution and could not find it.
I tried: void isTaken(struct storeData *data) but I got an error saying that I can't convert std::string to basic_string which makes sense if I'm correct about string I tried converting string into c string but could not get anywhere. I'm open to suggestions/corrections because I want to improve my code, also I could not find the answer here, so If someone's got a link to a problem like this please let me know.
Thank you so much for you time, have a good day.

A: Do you mean an array of structs instead of a struct of arrays?
In the example you are giving I see only an array of structs each of which has multiple string objects in it. You see, a string is a class coming from std and I wouldn't call it an array. If you want to know how to pass an array to a function, you should read about it (I'm sure you can find such a question in SO). If you want to have an array within your struct, then the struct will take care of the memory of the array, but you should definitely read about constructors.

A: You got an error because you are passing an string argument to a function which requires struct pointer
void isTaken(struct storeData *data);
...
isTaken(data[c].user);

but what you actually need is to have a function which takes an array of your users, its size and username you want to check
bool IsUsernameTaken(struct storeData data[], int dataSize, const string &username){
    for(int i = 0; i<dataSize; i++){
        if(username == data[i].username)
            return true;
    }
    return false;

}

A: A C string looks like this
data

A C++ string usually looks like this
size
capacity
ptr
 |
 v
data

or if using short string optimization and the string is short enough
size
data
data

all are zero terminated.
Making a shallow copy a C string only cost the copy of the pointer to it. Where a copy of a might cost just copying the 3 members and possible an allocation of data, which is not ideal, therefor most C++ functions use a reference to a string making the cost equivalent to the C string.
All code is untested.
bool Find(const std::string& target);

Making a deep copy of a C string would also cost an allocation.
In C++ you have many options to do a search, for your struct it could look like this. In case your member variables are private you must use an access function
auto found = std::find(std::begin(data), std::begin(data)+c, [&target](const storeData& auser) { return auser.GetName() == target });
return (found != std::begin(data)+c);

The first two parameters are the range that is search, not including the 2nd. A lambda is used to check the name, a free function with the right declaration would also do.
std::string& GetName() { return name; }

The higher C++ protection schemes would advice adding 2 consts to that in case you don't need to change name.
const std::string& GetName() const { return name; }

Meaning the returned string cant be changed and the 2nd says it wont change anything in your class. This const version would be required as I used a const storeData& auser in the lambda to satisfy the constness of the struct.


text:
Q: jquery form validation and php script in one page after implementing a jquery form validation and redirecting with function btn_onclick()
{ window.location.href = "http://localhost/loginprivate.php";} from index.php to loginprivate.php my webapps php script wont be executed. The user become trough a javascript function and window.location.href from index.php redirected loginprivate.php you can see here. After the first pageload the page become loaded again with  this works fine too.
Now the problem is that if I click the submit button the php code wont become executed, that can I see because no cookies become created, and the user become redirected to index.php.
my php code:
    if(isset($_POST["submit"]))
    {
            $hostname='localhost';
            $username='root';
            $password='';

            unset($_POST['password']);
            $salt = '';
            for ($i = 0; $i < 22; $i++) {
                    $salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', mt_rand(0, 63), 1);
            }
            $_POST['password'] = crypt($_POST['password'],'$2a$10$'.$salt);
            $new = 0;
            try {
                    $dbh = new PDO("mysql:host=$hostname;dbname=search",$username,$password);
                    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
                    $sql = "INSERT INTO users (username, password)
                    VALUES ('".$_POST["username"]."','".$_POST["password"]."')";
                    if ($dbh->query($sql)) {
                            echo "New Record Inserted Successfully";
                    }
                    else{
                            echo "Data not successfully Inserted.";
                    }
                    $new = $dbh->lastInsertId();
                    $dbh = null;
            }
            catch(PDOException $e)
            {
                    echo $e->getMessage();
            }
            if ($new > 0)
            {

                $t = time() + 60 * 60 * 24 * 1000;
                setcookie("username", $_POST['username'], $t);
                setcookie("userid", $new , $t);
            }
        else
            {

            }
    }

my html code:

        <meta charset="UTF-8" />
        <title>
        HTML Document Structure
        </title>
        <link rel="stylesheet" type="text/css" href="style.css" />
        <link rel="stylesheet" href="themes/my-costum-theme.min.css" />
        <link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />

        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />

        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

localcorps

                    <form  name="login-form" id="myform" class="login-form" action="./loginprivate.php" method="post">

                                Username:
                                <input name="username" type="text" class="input username" id="username"/>

                            Password:
                            <input name="password" type="password" class="input password" id="password"/>

                            <input type="submit" name="submit" value="Login" class="button"/>

                    </form>

A: According to your comment, I get now only this "Array ( )" on my screen. it means that you ain't posting anything to PHP page.
That's just because, you're redirecting the control to PHP page instead of submitting the form.
so, you can validate the code using jQuery and on successful validation do a ajax post request instead of shifting the control.window.location.href = "http://localhost/lak/main.php";
instead of shifting control, do a post.
$.ajax({
    type: 'post',
    url: 'loginprivate.php'    //url where you want to post the stuff.
    data:{
        username: 'someUserName',
        password: 'xxxxxxxxxxxx'
    },
    success: function(res){
        //here you will get res as response from php page, either logged in or some error.
        //and if you're logged in successfully, redirect here now.
    }
});

Hope this will help.


text:
Q: Correct way of writing PL SQL conditions Below is the condition for my table Request.
level of     till 300$       301-500$      501-3400$
credit card
usage in
3 month

0%            0%               0%             0%
1-30%         30%              0%             0%
31-50%        50%              0%             0%
51-60%        50%              15%            0%
61-70%        100%             15%            0%
70%~          100%             30%            30%

My task is to retrieve all information I mentioned above in one table using PL SQL. I have table Request which consists of 3 columns as client_id, level_3m and credit_limit So the output(for example) should look like this using above information:
level_3m     credit_limit($)      new_limit(%)

0                50                 0
45               400                0
45               250                50
65               350                15
80               1500               30

What have I done so far? Here is my own script:
DECLARE
    v_level        VARCHAR2(100);
    v_credit_limit VARCHAR2(100);
    v_id           VARCHAR2(100);
    new_limit      VARCHAR2(100);
BEGIN
    SELECT level_3m,
           credit_limit
    INTO   v_level, v_credit_limit
    FROM   request a
    WHERE  v_id = a.client_id;

    --this is for "till 300$" condition
    IF v_level = 0
       AND v_credit_limit =< 300 THEN
      new_limit := 0;
    ELSIF v_level >= 1
          AND v_level <= 30
          AND v_credit_limit =< 300 THEN
      new_limit := 30;
    ELSIF v_level >= 31
          AND v_level <= 50
          AND v_credit_limit =< 300 THEN
      new_limit := 50;
    ELSIF v_level >= 51
          AND v_level <= 60
          AND v_credit_limit =< 300 THEN
      new_limit := 50;
    ELSIF v_level >= 61
          AND v_level <= 70
          AND v_credit_limit =< 300 THEN
      new_limit := 100;
    ELSIF v_level >= 70
          AND v_credit_limit =< 300 THEN
      new_limit := 100;
    END IF;
END;

/

--the other conditions were written same manner as the above one.

I am new to PL/SQL so please tell is my condition right? Or is there another more simple way to write those conditions?

A: You're doing If statements right.
Another option is using CASE. It's basically the same but sometimes looks a little neater, especially if you're writing out many ELSIF clauses.
    CASE
      WHEN v_level=0  and v_credit_limit=<300 then new_limit:=0
      WHEN v_level>=1 and v_level <=30 and v_credit_limit =<300 then new_limit:=30
      WHEN v_level>=31 and v_level<=50 and v_credit_limit=<300 then new_limit:=50
      WHEN v_level>=51 and v_level<=60 and v_credit_limit=<300 then new_limit:=50
      WHEN v_level>=61 and v_level<=70 and v_credit_limit=<300 then new_limit:=100
      WHEN v_level>=70 and v_credit_limit=<300 then new_limit:=100
    END CASE

It doesn't really matter all that much whether you use IF or CASE in my opinion.

A: Personally I would have a table with the v_level and credit limit in it and join to that to get new_limit out.
That's the relational way, and therefore the "proper way" in this context.


text:
Q: As good as it gets. What's the meaning of this sentence?
As good as it gets.

What's the meaning of this sentence?
Does the sentence mean "It is good only to the degree that it gets." or " It is good without limit(i.e. The more it gets the better it is)."

A: "This is the most good it's going to be"
As good as it gets (Merriam-Webster)
1 —used to say that nothing better is possible or available It's not a great restaurant, but in this part of the city, it's as good as it gets.
2 —used to say that something is very good and cannot be improved

A: It means "nothing better is available".  The sense can range from positive to weakly negative:

It's not a great bike, but for £700, it's as good as it gets.

This means that the bike is good value, but not as good as a more expensive bike.

This restaurant is as good as it gets in our town.

Perhaps other cities have better restaurants, but this one is pretty good, it is the best one locally.


text:
Q: Implement a simple echo server using asyncio I am trying to implement a simple echo server using asyncio. Here's my attempt:
import asyncio

async def process(reader, writer):
    while True:
        data = await reader.readline()
        writer.write(data)

loop = asyncio.get_event_loop()
listener = asyncio.start_server(process, host=None, port=2500)
loop.run_until_complete(listener)
loop.run_forever()

This starts the server and I can connect from multiple clients, also the clients have their messages echoed back to them. The problem is when I close one of the clients, the echo messages stop appearing on the other connected clients too. Why does that happen and how can I prevent that?

A: The server hangs because the loop is not exited when a connection is closed. The convention is when a network read function returns no data, it means EOF. The server must handle it, e.g.:
while True:
    data = await reader.readline()
    if not data:
        break
    writer.write(data)

Without the break the loop is executed again and again, because the EOF state will not change.
Please note that each connection is handled by its own process which is called with a reader and a writer belonging to that connection.


text:
Q: Why does this Embed.set_footer call fail in my Discord bot? I send nearly all bot output via embeds, using the below method:
async def show_message_embed(self, ctx: commands.Context, message, title=None):
    if title is None:
        title = f"Command Output"
    em = discord.Embed(title=title, description="```\n" + message + "\n```", colour=0xBD362F)
    #em.set_footer("ChatNote (c) 2020 Erisia")
    em.timestamp = datetime.utcnow()
    await ctx.send(embed=em)

The #em.set_footer line is commented out because if I uncomment it, I get the following error message:
TypeError: set_footer() takes 1 positional argument but 2 were given

I am quite obviously, to me, only passing 1 positional argument - the only argument, so what is wrong here?

A: set_footer takes text as a parameter and an optional icon_url.
em.set_footer(text="ChatNote (c) 2020 Erisia")


text:
Q: Can't connect to this network - better diagnosis? I can't connect to my wifi anymore. It used to work, now it doesn't. I have a TP-Link Archer T9E wireless card. I can't really try to connect to other networks as it is not a laptop. The only thing I can do is setting my phone as hotspot, and this works. I've tried disable/reenabling the wireless card, forgetting the network, restarting the router, and reinstalling the card's driver. None of this worked. I've seen several people with similar problems, I've tried everything I could find, nothing worked. Is there a way to get a better diagnosis? Like why it can't connect to the network, at which phase it fails, or something? Thanks.

A: I had the same issue several times.  What fixed it for me was a series of command-line interface networking commands followed by a reboot.  Give 'em a try, you've got nothing to lose!
netsh winsock reset
netsh int ip reset
netsh winsock reset catalog
netsh int ip reset reset.log hit.

I also entered the following commands, but I don't believe they did anything:
ipconfig /release
ipconfig /renew

... the Dell tech who helped me fix this the first time it happened used them.  This command does do something, though:
netsh /flushdns

Now reboot the machine and it should connect to your Wi-Fi without any problem.  Worked for me at least four times (until now, anyway... tried to install Windows Subsystem for Linux, rebooted, and now I've got the old "can't connect to this network" thing again, and none of these commands helps.  Restoring to an earlier restore point didn't help, nor did removing the subsystem.

A: I know it's 3 years late, but I've got a fix. First you have to download the driver mentioned in this page: https://community.tp-link.com/en/home/forum/topic/204498?fbclid=IwAR33oT9VjdsGEZZTkgs0uR07bbmCbQy4IeVWQ-Rm_crY3W9_7QVYSClKk8g
Especifically: https://static.tp-link.com/2019/201911/20191129/Archer T6E T9E_ASUS driver_7.35.351.0.zip
Then you have to install it using this instructions: https://www.tp-link.com/support/faq/2722/
After that, remove the middle antenna, you have to leave only the edge antennas. If your problem was similar to mine, then you'll be able to connect to your wifi again.


text:
Q: Service Fabric ETW Logs are always incomplete We have just started using Service Fabric and the only pain point so far has been ETW with WAD, which always seems to log out with missing data (message, eventmessage.)
Our experience so far has that it always works in visual studio (sometimes you have to add the provider name) and that it rarely works when deployed to a cluster in Azure. When it does work in Azure - versioning & updating a function on the event source or adding another will then log out with empty data points.
This is the section we have in our ARM script for ETW/WAD which we are deploying using the Azure CLI.
"name": "[concat('VMDiagnosticsVmExt','_vmNodeType0Name')]",
"properties": {
    "type": "IaaSDiagnostics",
    "autoUpgradeMinorVersion": true,
    "protectedSettings": {
        "storageAccountName": "[parameters('applicationDiagnosticsStorageAccountName')]",
        "storageAccountKey": "[listKeys(resourceId('Microsoft.Storage/storageAccounts', parameters('applicationDiagnosticsStorageAccountName')),'2015-05-01-preview').key1]",
        "storageAccountEndPoint": "https://core.windows.net/"
    },
    "publisher": "Microsoft.Azure.Diagnostics",
    "settings": {
        "WadCfg": {
            "DiagnosticMonitorConfiguration": {
                "overallQuotaInMB": "50000",
                "EtwProviders": {
                    "EtwEventSourceProviderConfiguration": [
                        {
                            "provider": "Microsoft-ServiceFabric-Actors",
                            "scheduledTransferKeywordFilter": "1",
                            "scheduledTransferPeriod": "PT5M",
                            "DefaultEvents": {
                                "eventDestination": "ServiceFabricReliableActorEventTable"
                            }
                        },
                        {
                            "provider": "Microsoft-ServiceFabric-Services",
                            "scheduledTransferPeriod": "PT5M",
                            "DefaultEvents": {
                                "eventDestination": "ServiceFabricReliableServiceEventTable"
                            }
                        },
                        {
                            "provider": "Company-Project-API",
                            "scheduledTransferPeriod": "PT1M",
                            "DefaultEvents": {
                                "eventDestination": "ApiEventTable"
                            }
                        }
                    ],
                    "EtwManifestProviderConfiguration": [
                        {
                            "provider": "cbd93bc2-71e5-4566-b3a7-595d8eeca6e8",
                            "scheduledTransferLogLevelFilter": "Information",
                            "scheduledTransferKeywordFilter": "4611686018427387904",
                            "scheduledTransferPeriod": "PT5M",
                            "DefaultEvents": {
                                "eventDestination": "ServiceFabricSystemEventTable"
                            }
                        }
                    ]
                }
            }
        },
        "StorageAccount": "[parameters('applicationDiagnosticsStorageAccountName')]"
    },
    "typeHandlerVersion": "1.5"
}

This is our EventSource, though we have tried a ton of variations.
using Microsoft.Diagnostics.Tracing;

namespace Project.API

[EventSource(Name = "Company-Project-API")]
public sealed class ApiEventSource : EventSource
{
    public static ApiEventSource Current = new ApiEventSource();

    [Event(1, Level = EventLevel.Informational, Message = "{0}", Version = 1)]
    public void Log(string message)
    {
        this.WriteEvent(1, message);
    }
}

This is what we get in WAD every time.

Running .NET 4.5.2 / .net core.
Please assist.
EDIT - Okay, we've had some success moving up to .NET 4.6 - it looks as if the message payload is being logged out. All we're missing now is the eventmessage field. It also seems that the "message" field is always null now in VS.
EDIT2 - It seems that the message field is missing when using EventSourceSettings.EtwSelfDescribingEventFormat as a constructor argument to your event source like below. This seems to be the case in VS & in WAD.
public sealed class ApiEventSource : EventSource
{
    public ApiEventSource() : base(EventSourceSettings.EtwSelfDescribingEventFormat) {}
}

At the moment I can either choose between no eventmessage (Self Describing) or not being able to version the methods (even with incrementing the attribute, empty lines are still dumped into WAD when using manifest style.

A: Self-describing ETW is not currently designed to support the EventAttribute.Message property.    Message is a manifest based concept (that is they are not logged in the event, but rather placed in the manifest.   Since Self-describing ETW does not have a manifest, the Message property effectively gets ignored.
One could imagine extending the Meta-data associated with Self-describing ETW events so it could hold the Message string, but that does not currently exist and would require a change to ETW.
Simply embedding the message in the payload is the expected way to avoid the issue.


text:
Q: "ValueError: setting an array element with a sequence" when trying to train model for CarRacing-v2 with OpenAI Gym I'm trying to train RL-agent to play Car Racing environment with OpenAI Gym and been using following code:
import gym
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import VecFrameStack
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.evaluation import evaluate_policy
import os

environment_name = "CarRacing-v2"
env = gym.make(environment_name)

used this for testing de environment
episodes = 5
for episode in range(1, episodes+1):
    state = env.reset()
    done = False
    truncated = False
    score = 0

    while not done and not truncated:
        env.render()
        action = env.action_space.sample()
        observation, reward, done, truncated, info = env.step(action)
        print(done)
        score+=reward
    print('Episode:{} Score:{}'.format(episode, score))
env.close()

Then Trying to Train a model like so:
env = gym.make(environment_name)
env = DummyVecEnv([lambda: env])

log_path = os.path.join('Training', 'Logs')

model = PPO("CnnPolicy", env, verbose=1, tensorboard_log=log_path)
model.learn(total_timesteps=3000000)

Im getting this error after the last line of code where I'm trying to get the model to learn:
model.learn(total_timesteps=3000000)
model.learn(total_timesteps=3000000)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-59-262f6d03e40c> in <module>
----> 1 model.learn(total_timesteps=3000000)

~\anaconda3\lib\site-packages\stable_baselines3\ppo\ppo.py in learn(self, total_timesteps, callback, log_interval, eval_env, eval_freq, n_eval_episodes, tb_log_name, eval_log_path, reset_num_timesteps, progress_bar)
    315     ) -> PPOSelf:
    316
--> 317         return super().learn(
    318             total_timesteps=total_timesteps,
    319             callback=callback,

~\anaconda3\lib\site-packages\stable_baselines3\common\on_policy_algorithm.py in learn(self, total_timesteps, callback, log_interval, eval_env, eval_freq, n_eval_episodes, tb_log_name, eval_log_path, reset_num_timesteps, progress_bar)
    244         iteration = 0
    245
--> 246         total_timesteps, callback = self._setup_learn(
    247             total_timesteps,
    248             eval_env,

~\anaconda3\lib\site-packages\stable_baselines3\common\base_class.py in _setup_learn(self, total_timesteps, eval_env, callback, eval_freq, n_eval_episodes, log_path, reset_num_timesteps, tb_log_name, progress_bar)
    487         # Avoid resetting the environment when calling ``.learn()`` consecutive times
    488         if reset_num_timesteps or self._last_obs is None:
--> 489             self._last_obs = self.env.reset()  # pytype: disable=annotation-type-mismatch
    490             self._last_episode_starts = np.ones((self.env.num_envs,), dtype=bool)
    491             # Retrieve unnormalized observation for saving into the buffer

~\anaconda3\lib\site-packages\stable_baselines3\common\vec_env\vec_transpose.py in reset(self)
    108         Reset all environments
    109         """
--> 110         return self.transpose_observations(self.venv.reset())
    111
    112     def close(self) -> None:

~\anaconda3\lib\site-packages\stable_baselines3\common\vec_env\dummy_vec_env.py in reset(self)
     62         for env_idx in range(self.num_envs):
     63             obs = self.envs[env_idx].reset()
---> 64             self._save_obs(env_idx, obs)
     65         return self._obs_from_buf()
     66

~\anaconda3\lib\site-packages\stable_baselines3\common\vec_env\dummy_vec_env.py in _save_obs(self, env_idx, obs)
     92         for key in self.keys:
     93             if key is None:
---> 94                 self.buf_obs[key][env_idx] = obs
     95             else:
     96                 self.buf_obs[key][env_idx] = obs[key]

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.

Does anyone know how I can get around this?
OBS1:
I found that it has to do with the reset method on the env. When I run
env.reset()

I'm getting the same error


text:
Q: Optimization for large strings C/C++ I'm looking for a way to optimize my implementation. Basically this is a "reduce"-like (from Map Reduce framework) function. It takes a key and its values. The goal is to check all the values if they are distinct and output them in a form of an list: value1;value2;value3;...valuen; as a string. n can be very large (in 1000s)
void unique(char *key, int keybytes, char *multivalue, int nvalues,

        int *valuebytes, KeyValue *kv, void *ptr) {

    char * value = NULL;
    char * elem[nvalues];

    int i, j, cx;
    char adj[3858905] = "";

Big problem is that I have to specify char adj[] length for every input and I don't know ahead how big a number of values is. (That takes huge amount of memory)
    for (i = 0; i < nvalues; i++) {
        if (i == 0) {
            value = multivalue;
        } else {
            value = multivalue + valuebytes[i - 1];
            multivalue = multivalue + valuebytes[i - 1];
        }
        elem[i] = value;
    }

    size_t elem_length = sizeof(elem)/sizeof(char *);
    qsort(elem, elem_length, sizeof(char *), cstring_cmp);

    cx = sprintf(adj, "%s;", elem[0]);

    j = 0;
    for (i = 1; i < nvalues; i++) {
        bool matching = false;
        if (!strcmp(elem[i], elem[j]))
            matching = true;
        j++;
        if (!matching) //{;}
            cx += snprintf(adj + cx, 3858905 - cx - 1, "%s;", elem[i]);
    }

adj is an output string - list of values.
    kv->add(key, keybytes, adj, strlen(adj) + 1); //this outputs key-value pairs.
}

I have to use C/C++ only though.

A: Try to use Huffman Codification. It's a complex thing and old, but I think that's efficient. I don't know if there's new or/and better algorithms to do that.
http://www.cprogramming.com/tutorial/computersciencetheory/huffman.html
http://en.wikipedia.org/wiki/Huffman_coding

A: struct node {
  int value;
  struct node *next;
};

i suggest to use linked list to store all the values and then convert it into string...
you can keep count of number of stored values in linked list and using that calculate the string length...and then allocate enough memory using malloc().....
and later on..while more values are added to list you can modify the memory allocated using calloc()....
i dont know if its what you exactly wanted....but it looks feasible to me


text:
Q: Display 1,2,3,4 as 1-4 in oracle pl/sql I have a requirement as- if the user selects checkboxes containing 1,2,3,4 of type 1 and 2,3 of type2 then I should display as (1-4)type1 , (2-3)type2 as the output. We have to do it in backend. I have used LISTAGG but couldn't achieve the desired output. The user selects the checkbox and we have the values stored in Oracle database. Any inputs will be greatly helpful.
For Ex, the following is my data.

Type
Options

1
1

1
2

2
2

1
3

2
3

1
4

Using LISTAGG I could obtain :
select
Type  ,
listagg (Option, ',')
WITHIN GROUP
(ORDER BY Type) selectedOption from ( select .... )

Type
selectedOption

1
1,2,3,4

2
2,3

Desired Output:

Type
selectedOption

1
1-4

2
2-3

A: You can use MATCH_RECOGNIZE to find the range boundaries and then aggregate:
SELECT type,
       LISTAGG(
         CASE
         WHEN range_start = range_end
         THEN TO_CHAR( range_start )
         ELSE range_start || '-' || range_end
         END,
         ','
       ) WITHIN GROUP ( ORDER BY mn ) AS grouped_values
FROM   table_name
MATCH_RECOGNIZE(
  PARTITION BY type
  ORDER BY value
  MEASURES
    FIRST( value ) AS range_start,
    LAST( value )  AS range_end,
    MATCH_NUMBER() AS mn
  ONE ROW PER MATCH
  PATTERN ( successive_values* last_value )
  DEFINE successive_values AS NEXT( value ) <= LAST( value ) + 1
)
GROUP BY type

Which, for the sample data:
CREATE TABLE table_name ( type, value ) AS
SELECT 1, COLUMN_VALUE
FROM TABLE( SYS.ODCINUMBERLIST( 1, 2, 10, 17, 3, 15, 4, 16, 5, 7, 8 ) )
UNION ALL
SELECT 2, COLUMN_VALUE
FROM TABLE( SYS.ODCINUMBERLIST( 2, 3 ) )

Outputs:

TYPE | GROUPED_VALUES
---: | :---------------
   1 | 1-5,7-8,10,15-17
   2 | 2-3

db<>fiddle here


text:
Q: Why does my correlated subquery never finish? I have a table that looks like this
Directory nvarchar(max)
Extension nvarchar(10)
Length bigint
I also have another table that provides the type of file (lookup table)
extension nvarchar(10)
FileType nvarchar(50)
That being said I have a correlated subquery I wanted to migrate to a sproc that takes in the levels from the root and gives you back the directories and their file types at that specific level.  There are about 400k rows in the main table and about 800 extensions in the lookup table.
The query is this:
declare @levelsFromRoot as int = 7
--declare @auditName as varchar(max) = 'Aetna'

select
    ef.Type,
    sf.Directory,
    (select count(distinct part)
     FROM dbo.vwAuditView
     cross APPLY dbo.SplitPath( substring([Directory],1,LEN([Directory])

                        -CHARINDEX('\',REVERSE([Directory]))) ,'\') AS Results
                                where Directory = sf.Directory) as [LevelsFromRoot]
from dbo.FS02V_SourceFiles sf
inner join dbo.ExtensionFix ef
    on sf.Extension = ef.Extension
Where (select count(distinct part)
     FROM dbo.vwAuditView
     cross APPLY dbo.SplitPath( substring([Directory],1,LEN([Directory])

                        -CHARINDEX('\',REVERSE([Directory]))) ,'\') AS Results
                                where Directory = sf.Directory) = @levelsFromRoot
order by Directory asc

The cross apply section in the subquery counts the levels in each path starting from the root.  you should be able to pass in how many levels from the root and pass back a list of directories at that level and their corresponding file types.  This query has already been running 25 minutes.  It is returning data to me.  Is there anything I can do to improve this one?  I'm fairly new at correlated subqueries and figure I am doing something wrong here.
For clarity the view looks like this:
select    Directory
        --, ef.Extension
        , ef.Type
        , sum(Length) as [Size - Bytes]
from dbo.FS02V_SourceFiles sf
INNER JOIN dbo.ExtensionFix ef
    on sf.Extension = ef.Extension
group by ef.type, Directory

Function:
ALTER FUNCTION [dbo].[CHARINDEX2]
(
    @TargetStr varchar(8000),
    @SearchedStr varchar(8000),
    @Occurrence int
)

RETURNS int
AS
BEGIN

    DECLARE @pos INT, @counter INT, @ret INT

    set @pos = CHARINDEX(@TargetStr, @SearchedStr)
    set @counter = 1

    if @Occurrence = 1 set @ret = @pos
    else
    begin

        while (@counter < @Occurrence)
        begin

            select @ret = CHARINDEX(@TargetStr, @SearchedStr, @pos + 1)

            set @counter = @counter + 1

            set @pos = @ret

        end

    end

    RETURN @ret

A: That splitter is very likely the root of your problem. You should consider replacing that with a set based splitter. Here are many great examples. http://sqlperformance.com/2012/07/t-sql-queries/split-strings


text:
Q: How To Get Window handles In Mozilla Firefox How to get handles of all the child windows in Mozilla firefox. Spy++ is showing only one class and window caption for all the windows. I tried using GetWindow and FindWindowEx but got nothing. I want to read URL from mozilla firefox.

A: Spy++ uses standard Windows API calls to inspect window hierarchies (EnumWindows, EnumChildWindows, etc.). If Spy++ doesn't show any native windows, then there aren't any native windows. Consequently, you cannot find any native windows either. Firefox uses what's called Windowless Controls.
If you need to automate a GUI (which is likely the reason why you wish to find native windows), use the standard infrastructure available: UI Automation.

A: I got this answer from hazzey's answer and Ignas2526's comment on this post here
import win32gui
import win32ui
from ctypes import windll
from PIL import Image
import numpy as np

tab_name= '''[4k][60FPS] Optimus prime vs Lockdown Final Fight 4K 60FPS HFR[UHD] ULTRA HD - YouTube — Mozilla Firefox'''
hwnd= win32gui.FindWindow(None, tab_name)

window_rect = win32gui.GetWindowRect(hwnd)
w = window_rect[2] - window_rect[0]
h = window_rect[3] - window_rect[1]

hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()

saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)

saveDC.SelectObject(saveBitMap)

result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 2)

# print(result)
bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)

im = Image.frombuffer(
    'RGB',
    (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
    bmpstr, 'raw', 'BGRX', 0, 1)
im.shape = (h, w, 4)
# im= np.array(im)

win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)

if result == 1:
    # PrintWindow Succeeded
    im.save("test.png")

For mozilla (or at least for my computer) the third parameter for this statement is 2 to make it work, but if not you can play and try another number with it.
result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 2)

The test.png:


text:
Q: Настройка BrowserSync, Gulp. функция обратного вызова Была проблема со сборкой Gulp, в частности при изменении scss файлов - BrowserSync перезагружал браузер до того как файл изменился - то есть до того как задача по scss закончила выполняться. Решил проблему благодаря этой статье https://github.com/gulpjs/gulp/blob/master/docs/recipes/minimal-browsersync-setup-with-gulp4.md
Вот код
import babel from 'gulp-babel';
import concat from 'gulp-concat';
import del from 'del';
import gulp from 'gulp';
import uglify from 'gulp-uglify';
import browserSync from 'browser-sync';

const server = browserSync.create();

const paths = {
  scripts: {
    src: 'src/scripts/*.js',
    dest: 'dist/scripts/'
  }
};

const clean = () => del(['dist']);

function scripts() {
  return gulp.src(paths.scripts.src, { sourcemaps: true })
    .pipe(babel())
    .pipe(uglify())
    .pipe(concat('index.min.js'))
    .pipe(gulp.dest(paths.scripts.dest));
}

function reload(done) {
  server.reload();
  done();
}

function serve(done) {
  server.init({
    server: {
      baseDir: './'
    }
  });
  done();
}

const watch = () => gulp.watch(paths.scripts.src, gulp.series(scripts, reload));

const dev = gulp.series(clean, scripts, serve, watch);
export default dev;

Объясните, пожалуйста зачем тут нужен "done", если он нигде больше не вызывается. Я читал много про обратные функции, но так и не понял как тут это работает.


text:
Q: capistrano not running migrations in staging I am using capistrano 3 and I run cap staging deploy. After various commands, it then runs rake db:migrate, which looks like this:

INFO [f67aeefb] Running /usr/local/rvm/bin/rvm ruby-2.1.2@core do
  bundle exec rake db:migrate as deploy@10.10.4.131 DEBUG [f67aeefb]
  Command: cd /var/www/mysite_staging/releases/20150617233945 && (
  RAILS_ENV=staging /usr/local/rvm/bin/rvm ruby-2.1.2@core do bundle
  exec rake db:migrate ) DEBUG [f67aeefb]   "Env => staging"

The problem is the migration appears to have run in production, not in staging.
How can I ensure capistrano runs the migrations in staging when I specify staging during the deploy?

A: I'm not sure which of it did it, but by adding the following to staging.rb:
set :rails_env, 'staging'
set :database_name, 'core_staging'

And then in my apache virtual host adding:
RailsEnv staging

It seems to now recognize the staging database.


text:
Q: Why am I getting gibberish characters? I'm making a PHP script to reverse the text within an HTML document to handle badly converted Hebrew PDFs. (sigh :))
Everything works, however the script has a very strange output. Only SOME of the characters, instead of staying Hebrew letters, turn into blank characters (those black diamonds with question marks).
I tried some solution I could find on SO and beyond but nothing changed. Perhaps you can enlighten me?
You can check the script in action here: pilau.phpnet.us/html_invert.php, and this is the entire source code:
<!DOCTYPE html>
<html lang="he-IL">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <form action="html_invert.php" method="post" enctype="application/x-www-form-urlencoded">
        <textarea id="html_code" name="html_code" rows="30" cols="80"><?php
            if (isset($_POST['html_code']))
            {
                function invert_string ($str) {
                        $new_str = '';
                        $i = strlen($str);
                        while ($i > 0) {
                            $new_str .= substr($str, --$i, 1);
                        }
                        return '>'.$new_str.'<';
                    }

                    echo htmlspecialchars(preg_replace('/>(\s*.*\s*)</imUue', 'invert_string("$1")', stripslashes($_POST['html_code'])));
            }
            else { echo 'paste your text here'; }
        ?></textarea>
        <br />
        <input type="submit" value="Process HTML" />
    </form>
</body>
</html>

A: Looks like there is something wrong with the charset I guess.
Look for default_charset in the php.ini, this might be set to iso-8859-1.
Edit: now I think of it, you could also try sending this header:
header('Content-Type: text/html; charset=utf-8');

A: I wanted to mark this question as answered, so here is the solution, courtesy of Wooble and Matthew as described in the comments on the question above:
I used mb_substr('UTF-8') and mb_strlen('UTF-8'), as well as replaced stripslashes() with this regular expression: preg_replace(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $_POST['html_code']).
Thus the complete code is as follows:
    <textarea id="html_code" name="html_code" rows="30" cols="80"><?php
        if (isset($_POST['html_code']))
        {
            function add_delimiters ($str, $deli, $optional_suffix) {
                return (isset($optional_suffix) ? $deli.$str.$optional_suffix : $deli.$str.$deli);
            }

            function reverse_string ($str) {
                $new_str = '';
                $i = mb_strlen($str, 'UTF-8');
                while ($i > 0) {
                    $new_str .= mb_substr($str, --$i, 1, 'UTF-8');
                }
                return $new_str;
            }

            function utf_stripslashes ($str) {
                return preg_replace(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $str);
            }

            function strip_blank_lines ($str) {
                return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/u", "\n", $str);
            }

            function reverse_html_content ($html) {
                return preg_replace('/>(\s*.*\s*)</imUue', 'add_delimiters(reverse_string("$1"), ">", "<")', utf_stripslashes($html));
            }

            function clear_unsupported_css ($style) {
                return preg_replace(array('/top:\s{0,1}([0-9]*(?!px));{0,1}/iu', '/left:\s{0,1}([0-9]*(?!px));{0,1}/iu'), array('top:$1px;', 'left:$1px;'), $style);
            }

            function process_inline_style ($html, $func) {
                return preg_replace('/style="[a-zA-Z0-9:;\s{0,1}]*"/imUue', $func.'("$0")', $html);
            }

            echo strip_blank_lines(htmlspecialchars(process_inline_style(reverse_html_content($_POST['html_code']), 'clear_unsupported_css')));
        }
        else { echo 'paste your text here'; }
    ?></textarea>


text:
Q: CentOS 8 Chrony - how to query servers for time difference? We are moving from CentOS 7 to CentOS 8 for our monitoring servers (Zabbix) and we use ntpdate to query for time to detect if our local time provider for all devices (Cisco device) hasn't started drifting.
Basically query pool server, query local device and do math to determine if difference is greater than X.
Input:
ntpdate -p 1 -q 0.centos.pool.ntp.org | grep -oP '(?<=offset ).*?(?= sec)'
Output:
0.006313
Is there a way to query time (without setting server as source) using chrony or other tool in CentOS 8 that would work in similar fashion?

A: To adapt your existing command, try something like:
[root@localhost ~]# chronyc ntpdata 2001:418:3ff::53 | grep -oP '(?<=Offset          : ).*?(?= sec)'
+0.000654742

The address given must be one of your configured NTP servers. To do this, you should add the server to your sources list with the noselect option. This will tell chronyd to monitor the server but never synchronize from it. For example:
server cisco-ntp-server.example.com iburst noselect

Of course you can always continue to use ntpdate, and your question didn't specify why you are not willing to do this.


text:
Q:  not trigering my .js I have the following HTML code (using jquery 2.1.1 and bootstrap)

                     Documentos de Recolha de Dados

Lista de Documentos Necessários (316KB)

Recolha Dados SIIE (221KB)

Ficha de Saúde (850KB)

                  Regulamentos e Estatutos do CNE

Estatutos do CNE (113KB)

Regulamento Geral CNE (592KB)

Regulamento do Uniforme CNE (4MB)

                  Actividades de Agrupamento

Plano de Actividades Agrupamento (451KB)

Plano de Actividades 1ª Secção (440KB)

Plano de Actividades 2ª Secção (202KB)

Plano de Actividades 3ª Secção (443KB)

                  Cancioneiro 358

Cancioneiro = 1 Escuta

Encomendas para geral@agr358.cne-escutismo.pt

Entrege em mão na sede do 358

and the folowing aditional js
$(document).ready(function() {
    $('#scroll').click(function() {
        $('html, body').animate({
            scrollTop: '+=400'
        }, 1000);
    });
});

for some reason the first collapse block works on scrolling down the page, but the others dont trigger the js.
What am i doing wrong.
Thanks in advance

A: IDs in html must be unique. You need to do class='scroll' instead of ID and then use $(".scroll")

A: ID must be unique. Change your a tags id property (id="scroll") to class (class="scroll") it should be work
and change your selector $('#scroll') to $('.scroll')


text:
Q: How to use query in couchbase lite I'm working on couchbase lite wpf project.
I want to get appointments by date. So I created a view with below code.
appointments.AddRange(App.StorageRepository.Query<AppointmentModel>(map, limit, offset, TodayWhere));

bool TodayWhere(IDictionary<string, object> accessDoc, IDictionary<string, object> parameters)
            {
                var tableName = parameters["table"].ToString();
                if (!accessDoc["_id"].ToString().Contains(tableName))
                {
                    return false;
                }
                var startDay = Convert.ToDateTime(accessDoc["startDate"].ToString());
                var today = Convert.ToDateTime(parameters["today"].ToString());
                if (startDay.Date != today.Date)
                {
                    return false;
                }
                return true;
            }

public List<T> Query<T>(IDictionary<string, object> map, int limit, int offset, Func<IDictionary<string, object>, IDictionary<string, object>, bool> monitoring)
        {
            List<T> list = new List<T>();
            var viewName = map["view"].ToString();
            var view = Manager.SharedInstance.GetDatabase(DatabaseName).GetView(viewName);
            view.SetMap((doc, emit) =>
                {
                    if (!monitoring(doc, map))
                    {
                        return;
                    }
                    emit(doc, null);
                }, "1.0");

            var query = view.CreateQuery();
            query.Limit = limit;
            query.Descending = true;
            var queryResult =
                query
                .Run()
                .ToList();
            foreach (var item in queryResult)
            {
                var doc = GetObject<T>(item.Document.UserProperties);
                list.Add(doc);
            }
            return list;
        }

So this code is working, but there is a problem.
For example. I created the view in 2016.05.06. The view returns appointments of the day correctly.
But It returns same data in today too. I'm not sure what is wrong.
I'm confused about View and query.
I can't use the view like SQL view table?

A: Views build a static index that is persistent.  The map function for a View must be a pure function, meaning it can't depend on anything but the document passed in.  If your map function relies on anything (like the current date), you'll get inconsistent results.  It looks like this may be what's happening in your case.
Rules for Couchbase Lite View map functions:

*

*It must be a "pure" function: That means any time it's called with the same input, it must produce exactly the same output. In other words, it can't use any external state, just its input JSON.

*It can't have side effects: It shouldn't change any external state, because it's unpredictable when it's called or how often it's called or in what order documents are passed to it.

*It must be thread-safe: It may be called on a background thread belonging to the indexer, or even in parallel on several threads at once.

See the documentation on Couchbase Lite Views.


text:
Q: SVN - want to extract only project name/path and date of commit im trying to get an extract with the SVN command line, where i can limit the output to only the project name and the date of the commit.
I dont want to see all file changes and comments.
Anyone know how that can be done without using another program to filter the output of a svn log command ?

A: Try
svn info url --xml
See doc


text:
Q: Springboot RabbitMq Consumer consuming only at first time.please help me to get the configurations right and how can configure multiple listners Springboot RabbitMq Consumer consuming only at first time.please help me to get the configurations right and how can  configure multiple listners.I am developing an Automated Mapping solution for which i Execute various jobs .and in a need to put those jobs in queue
Here's my application class:Application.java
@SpringBootApplication
@ComponentScan(basePackages = { "com.fractal.sago", "com.fractal.grpc" })
public class Application extends SpringBootServletInitializer {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);

    }

RabbitMqConfig class:

@Configuration
public class RabbitMqConfig {
    public final static String JOB_QUEUE_NAME = "jobQueue";
    public final static String JOB_EXCHANGE_NAME = "jobExchange";

    @Bean
    Queue jobQueue() {
        return new Queue(JOB_QUEUE_NAME, true);
    }

    @Bean
    DirectExchange jobExchange() {
        return new DirectExchange(JOB_EXCHANGE_NAME);
    }

    @Bean
    Binding jobBinding(DirectExchange directExchange) {
        return BindingBuilder.bind(jobQueue()).to(jobExchange()).with(jobQueue().getName());
    }

    @Bean
    SimpleMessageListenerContainer jobQueueContainer(ConnectionFactory connectionFactory,
            MessageListenerAdapter joblistenerAdapter) {
        SimpleMessageListenerContainer jobQueueContainer = new SimpleMessageListenerContainer();
        jobQueueContainer.setConnectionFactory(connectionFactory);
        jobQueueContainer.setQueueNames(JOB_QUEUE_NAME);
        jobQueueContainer.setMessageListener(joblistenerAdapter);
        return jobQueueContainer;
    }

    @Bean
    MessageListenerAdapter joblistenerAdapter(JobQueueConsumer messageReceiver) {
        MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(messageReceiver, "receiveMessage");
        messageListenerAdapter.setMessageConverter(producerJackson2MessageConverter());
        return messageListenerAdapter;
    }

    @Bean
    public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

}

producer : JobProducer

@Component
public class JobQueueProducer {
    @Autowired
    RabbitTemplate rabbitTemplate;

    public void sendMessage(String message) {

        Message messageToSend = MessageBuilder.withBody(message.getBytes())
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
        rabbitTemplate.convertAndSend(RabbitMqConfig.JOB_EXCHANGE_NAME, RabbitMqConfig.JOB_QUEUE_NAME, messageToSend);
        //rabbitTemplate.convertAndSend(RabbitMqConfig.JOB_QUEUE_NAME, messageToSend);

    }

}

Consumer :JobQueueConsumer

    enter code here

@Component
public class JobQueueConsumer implements MessageListener {
    @Autowired
    SagoAlgo sagoAlgo;

    @Autowired
    CCDMappingService ccdMappingService;

    @RabbitListener(queues = { RabbitMqConfig.JOB_QUEUE_NAME })
    public void receiveMessage(Message message) throws SQLException {
        System.out.println("Received Message: " + new String(message.getBody()));
        Integer jobId = Integer.parseInt(new String(message.getBody()));
        System.out.println(jobId);
        CCDMappingVO ccdVo =ccdMappingService.fetchCCDWithCategoriesById(jobId);
        sagoAlgo.execAlgo(ccdVo);  //my Algo to be executed

    }

//when I implement MessageListener default method to be executed
    public void onMessage(Message message) {
        // System.out.println("Received Message: " + new
        // String(message.getBody()));

    }
}


text:
Q: Explicit delete on JPA relationships I am a bit confused about managing relationship in JPA.
basically I have two entities with a One to Many relationship
A configuration can have have a one or many email list associated with it.
@Entity
public class Config {
    @OneToMany(mappedBy="owner",cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    private List<Email> emailReceivers;
}
@Entity
public class Email {
    @ManyToOne
    private Config owner;
}

In an EJB and during update/merge operation wherein I would edit the list of emails associated with a configuration,
I thought that I dont need to explicitly call the delete operation on my  email Entity and I would just manage the relationship by deleting the email in my configuration email list.
@Stateless
public class ConfigFacadeImpl implements ConfigFacade{
    @EJB
    private ConfigDao configDao;
    @EJB
    private EmailDao emailDao;

    @Override
    public void update(Config Config, List<Email> emailsForDelete) {
        if(emailsForDelete!=null && emailsForDelete.size() > 0){
            for(Email emailTemp: emailsForDelete){
                Email email = emailDao.find(emailTemp.getId());
                emailDao.delete(email);  // Do I need to explicitly call the remove??
                config.getEmailReceivers().remove(email);
            }
        }
        configDao.update(config);
    }
}

If I don't execute the delete and only remove it from the list, it wont erase my table row.
The UI and the database is now not in sync as the UI would not show the email(s) that I have deleted but when you check the database, the row(s) are still there.
Is it required? I thought JPA would handle this for me if I would just remove it in my entities.
UPDATE
I have tweaked my code to get the entity from the database first before making any changes but still it is not deleting my child email entities.  I wonder if this is an apache derby issues.  (This is the correct way right as I am passing my entities from my JSF managed bean into my EJB so I need to get the sync from the DB first.)
@Override
public void update(Config config, List<Email> emailsForDelete) {
    Config configTemp = configDao.find(config.getId());
    if(emailsForDelete!=null && emailsForDelete.size() > 0){
        for(Email emailTemp: emailsForDelete){
            configTemp.getEmailReceivers().remove(emailTemp);
        }
    }
    configDao.update(config);
}

A: Since you have already defined cascade type = CascadeType.ALL, JPA should take care of the deletion. Explicit Delete statement is not required.
These two statements are not required:
     Email email = emailDao.find(emailTemp.getId());
     emailDao.delete(email);  // Do I need to explicitly call the remove??

Instead, you may want to just find the matching emailReceiver in config.getEmailReceivers() and remove the matching EmailReceivers as you are doing. There is no need to load the Email entity from the database.
EDIT: To delete orphan objects, you may want to include CascadeType.DELETE_ORPHAN cascade attribute along with CascadeType.ALL.

A: This is the same issue as in Why merging is not cascaded on a one to many relationship
Basically, JPA can only cascade over entities in your collection. So changes to child objects removed from the collection are never putinto the context, and so can't be pushed to the database.  In this case, the oneToMany is controlled by the manytones back pointer, so even collection changes won't show up unless the child is also merged.  Once a child is pruned from the tree, it needs to be managed and merged individually for changes to it to be picked up.

A: With JPA 2.0, you can use the option orphanRemoval=true in parent entity
Example:
@Entity
public class Parent {
    ...

    @OneToMany(mappedBy="parentId",cascade=CascadeType.ALL, orphanRemoval=true)
    private List<Child> childList;
    ...

}


text: Q: Кластеризация меток Yandex Mapkit (Android, Java) Нужно реализовать кластеризацию меток на карте Yandex Mapkit в приложении Android (Java). Пример найти не могу, по документации понять не получается. Подскажите или поделитесь примером, пожалуйста.


text:
Q: Is the on-screen version of Annville, Texas faithful to the comic? I haven't read more than a couple of "Preacher" comics, but I'm currently about halfway through Season 1 of the tv show. I can't help but notice that the town of Annville is rife with Hollywood stereotypes of Southern people. So far, the show has included:

*

*a racist, sexist Sheriff who ignores a report of possible spousal abuse

*townspeople who enjoy beating up their new politically correct mascot

*numerous hypocrites in Custer's congregation, including a child molester, said Sheriff, and a couple who are into S&M

*a local "cattle baron" who rules his company with an iron fist

*the employees of said cattle baron, who literally get away with murder

*a whorehouse

I often see these stereotypes in films and on TV, and as someone who grew up in Texas, I can assure you that they're no more the norm there than they are anywhere else.
Is the on-screen version of Annville, Texas faithful to the Preacher comics, or is this just Hollywood stereotyping of small Texas (or even just Southern in general) towns?

Note: I realize that the nature of this topic could easily devolve into a political discussion, so in advance, let's try to keep comments and answers on-topic.

A: Many of the characters of Annville in the TV series are actually taken from later on in the Comics, and in some cases are in fact toned down a bit.
For instance in the comics the Cattle Barons assistant is a hardcore Dominatrix who ends up submitting to Custer. That same cattle baron is found making love to a mannequin made of meat, throughout the books many characters throughout the world are depicted as being deviant, twisted, perverted and with no morales and in regards to Southern characters they are depicted as all the above and more.