text:
Q: Google Analytics Ecommerce / Difference between 'ec:addItem', 'ec:addTransaction' and 'ec:send' I would look for some feedback on tracking user activity on an commerce website using th google analytics commerce capabilities.
I can't fully understand those 3 parts :

*

*Adding an item (ecommerce:addItem) : obviously when some user add a thing to the cart

*Adding a Transaction (ecommerce:addTransaction) : that's where I'm very confused

*Sending the data (ecommerce:send) : that's obvious

Can those 3 event append at a different moment ? in what manner ?
What would be a real-world use case that would make you use execute ecommerce:addTransaction and  ecommerce:send at a different moment ?
This thing makes me wonder a lot, and I'd like to have some experienced feedback on this as you tend to easily break your stats if something is not done week enough
Thanks in advance
EDIT
So the main purpose right here is to get stats for the pending orders (you add stuff to your cart), and the complete orders (you paid for the things you added).
Right now I only send it all when the order is complete, and things are working pretty good in analytics, but I just don't know anything about the ones that did not complete.

A: This question was a lack of knowledge.
Simple ecommerce plugin  has nothing to do with the enhanced ecommerce plugin
You won't track that much with the first one, except the checkouts. A plain, one order at a time, revenue value.
If you want a deep insight on your users behaviors (when i say deep, I mean it), You have to go for the second one.
We might be able to debate over the unusefullness of the first one; and the fact that its existence in itself compared to the second is completely misleading, as when you first get in, as usual with google, you get flooded by an endless documentation

A: ecommerce:addItem does not add items to a cart; it adds items to a transaction (with "conventional" ecommcerce tracking there is no cart tracking, you'd have to use enhanced ecommerce tracking. Actually your title refers to enhanced ("ec:") and your question to conventional ecommerce ("ecommerce:") tracking).
So ecommerce:addTransaction starts a transaction; here goes the stuff that affects the transaction as a whole, like transaction id, tax on the total purchase or shipping costs.
Now that you have started the transaction you can add items to it that are associated via the transaction id.
Finally the ecommerce:send command tells Universal Analytics that the transaction should be processed on the server. "send" is actuall a misnomer; addItem and addTransaction do already send data to the server (they each create an request to the tracking server and thus count towards your hit quota).
The reason for this is, as far as I can tell, that the information is transmitted via url parameters (you call the Google Analytics endpoint which returns an transparent pixel). The maximum length for an url request is limited (actual limits depend on browser and browser version).
So the transaction is broken up into multiple parts not because you want to execute the commands at different moments but so it can be transmitted via Url parameters without being truncated. The send command merely tells that you are now finished adding new parts to the transaction and the data can now be processed.


text:
Q: iOS HTTP Post encoding for Hebrew characters I need to do a HTTP Post from my iPhone app to a Google Doc. It works fine for English, but the Hebrew shows as question marks in the Google Doc.
This is what I'm doing:
NSString *post = [Util append:@"&entry.xxxxx=", self.firstName.text, @"&entry.yyyyyyy=", self.phone.text, @"&entry.zzzzzzzz=", self.email.text, nil];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://docs.google.com/forms/d/FORM_ID/formResponse"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

What am I missing?
EDIT: I tried the solution offered here and looked at ahmedalkaf's link here but no luck.

A: Option 1
You have set your Content-Type to application/x-www-form-urlencoded, but you haven't url-encoded your contents.
URL-encoding your post NSString and changing the Encoding to UTF-8 (I cant tell you why, but it's needed to make it work) should do the job.
NSString *post = [Util append:@"&entry.xxxxx=", self.firstName.text, @"&entry.yyyyyyy=", self.phone.text, @"&entry.zzzzzzzz=", self.email.text, nil];
post =[post stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

Everything else can stay the same. However you should think about using an asynchronous request. When using a synchronous request, your user interface will become unresponsive, until the request is finished. This doesn't happen with an asynchronous request.
Option 2
For HTTP-Requests I usually use the ASIHTTPRequest Library: http://allseeing-i.com/ASIHTTPRequest/
It takes a couple of minutes to integrate into your project, but it makes everything way more simple. You don't have to mess around with encodings etc.
NSURL *url =[NSURL URLWithString:@"https://docs.google.com/forms/d/FORM_ID/formResponse"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

[request addPostValue:self.firstName.text forKey:@"entry.xxxx"];
[request addPostValue:self.phone.text forKey:@"entry.yyyy"];
[request addPostValue:self.email.text forKey:@"entry.zzzz"];

[request startAsynchronous];

That's it.
To set up ASIHTTPRequest follow these instructions http://allseeing-i.com/ASIHTTPRequest/Setup-instructions and remember to add a -fno-objc-arc compiler flag to the libraries files under Project Settings -> Build Phases -> Compile Sources if you are using ARC.

A: (This mainly explains why UTF-8 encoding is needed over ASCII. I'm not going to explain about the URL-encoding part of this problem, as Tim Bodeit already did nicely.)
Basic Explanation:
ASCII encoding only contains English, unaccented characters, while UTF-8 contains characters for most languages.
Details:
ASCII has only the characters shown from the image below, although it fits into only seven bits (or eight, depending on which way you look at it).

(ASCII Characters and how they are encoded. From the blog post by Joel Spolsky in the link below)
However, both Unicode and UTF-8 can contain any characters from almost all major languages.
UTF-8 is preferred over Unicode, because when your app is using characters that are in ASCII (English), it will be only one byte. When your app is using Hebrew, the string will be a few bytes longer. If you use Unicode, your string will ALWAYS have more than one byte, whether its in English or in Hebrew.
The solution? Just change everything that says ASCII to UTF8.
You (and every other programmer) should absolutely read this article.
It's by Joel Spolsky (co-founder of Stack Exchange), and it's very beneficial for any program using strings, which is most programs. You especially will benefit if you are doing work using both Hebrew and English.

A: Swift 4 Solution for escaping string that contains Hebrew
let dataString = "firstname=בני&lastname=דוידוביץ".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""

let urlString = "http://be.repoai.com:5080/WebRTCAppEE/streams/home/משדר_מיוחד_לכבוד_יום_הזעכרון_לחללי_מערכות_ישראל_ופעולות_האיבה.mp4".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""

A: For Hebrew character to post data on  server used NSUTF8StringEncoding

NSString *post = [Util append:@"&entry.xxxxx=", self.firstName.text, @"&entry.yyyyyyy=", self.phone.text, @"&entry.zzzzzzzz=", self.email.text, nil];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

A: You can use AFNetworking, this will send your data as utf-8 encoding i use this library for my projects in spanish and always get the correct character for áéóúñ:
NSString *encodeUrl  = [@"document/d/Hphb4NsfxZLxTl7p3LMCWCpm9MCWskgoTFWzhP1Fpqap/edit" stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

//setup the post using AFHTTPClient
AFHTTPClient *afHttpRequest = [[[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://docs.google.com"]] autorelease];
NSURLRequest *request = [afHttpRequest requestWithMethod:@"POST" path:encodeUrl parameters:post];

//loading indicator
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
[[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];

[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){
        //some response
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
        //the request fails
    }
];
//fire the request
[operation start];

what does [Util append] ? add some extra encoding to the fields ? or just append

redpajama_set_name: RedPajamaStackExchange


text:
Q: Refer coin Firebase database multiples the coins until app crashes I've added refer coin system to my app in which if you refer it to someone you get 100 coins & the person refers code you were using get's the same. Bu the issue is when I run the app and use the referral code coins keep on increasing unless the app crashes. Coins should be added 100 in both accounts but they go from 0 to 24000 or more unless the app crashes.
The following code is :
reference
                        .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {

                        ProfileModel model = snapshot.child(oppositeUID).getValue(ProfileModel.class);
                        ProfileModel myModel = snapshot.child(user.getUid()).getValue(ProfileModel.class);

                        int coins = model.getCoins();
                        int updatedCoins = coins + 100;

                        int myCoins = myModel.getCoins();
                        int myUpdate = myCoins + 100;

                        HashMap<String, Object> map = new HashMap<>();
                        map.put("coins", updatedCoins);

                        HashMap<String, Object> myMap = new HashMap<>();
                        myMap.put("coins", myUpdate);

                        reference.child(oppositeUID).updateChildren(map);
                        reference.child(user.getUid()).updateChildren(myMap)
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        dialog.dismiss();
                                        Toast.makeText(InviteActivity.this, "Congrats", Toast.LENGTH_SHORT).show();
                                    }
                                });

                    }

A: The problem in your code lies in the fact that you are using addValueEventListener. This means that you are listening for changes in real-time. Every time something changes in your database, the listener fires. Since you are listening to the same location you are performing the updates, the listener fires over and over again. What you need is addListenerForSingleValueEvent, to get the data exactly once.
To solve this, simply change the call to:
addValueEventListener()

To:
addListenerForSingleValueEvent()

And your code will work perfectly fine.


text:
Q: C# WPF.Net Core cannot Close window from other thread Currently I'm working on the WPF on .net core.
My application have to start Cef core to run the UI (instead of using WPF form).
Before of that I want to display a simple WPF window that say "Loading..."
So in the application start up, I have to start a thread like this
        Thread thread = new Thread(() =>
        {
            try
            {
                DisplayLoader = true;
                var f = new Loading();
                f.Loaded += (a, b) =>
                {
                    Task.Run(() =>
                    {
                        while (DisplayLoader)
                            Thread.Sleep(250);
                        f.Dispatcher.BeginInvoke(() =>
                        {
                            f.Close();
                        });
                        f.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate ()
                        {
                            f.Close();
                        }));
                    });
                };
                f.Show();
                Dispatcher.Run();
            }
            catch
            {
                Loader.Close();
            }
        });

The point is, when the DisplayLoader become false, I saw the Dispatcher invoke the Close function too, however, nothing happened. I already follow a lot of answer on stackOverflow, but none of them works.
Below the thread start is this function, It will invoke Cef and display a Cef Window
        thread.Start();
        var assembly = Assembly.GetExecutingAssembly();
        CefApp
           .Run(assembly)

When the CefApp Loaded, the DisplayLoader will be set to false.
        protected override void OnLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode)
        {
            base.OnLoadEnd(browser, frame, httpStatusCode);
            if (frame.IsValid)
            {
                if (App.DisplayLoader)
                {
                    App.DisplayLoader = false;
                }
            }
        }

EDIT:
The problem actually come from the CefAppBuilder, it embedded C++ code from CefGlue, then may cause some issue with C# function. Just do not modify any C# variable in C invoke function then it's fine.

A: The thread that executes a Window must be a UI thread which must be a STA thread.
You have to mark the thread as STA using Thread.SetApartmentState:
App.xaml
private void Run(object sender, StartupEventArgs e)
{
  Thread uiThread = new Thread(DoWork);
  uiThread.SetApartmentState(ApartmentState.STA);
  uiThread.IsBackground = true;
  uiThread.Start();
}

But my recommended approach is to execute the initialization asynchronously. This avoids the overhead of creating additional UI threads and is also more compact in terms of lines of code and readability:
App.xaml
private TaskCompletionSource TaskCompletionSource { get; set; }

private async void Run(object sender, StartupEventArgs e)
{
  Window splashScreen = new SplashScreenWindow();
  splashScreen.Show();

  await InitializeCefAppAsync();
  splashScreen.Close();
}

private async Task InitializeCefAppAsync()
{
  this.TaskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.LongRunning);

  var assembly = Assembly.GetExecutingAssembly();
  CefApp.Loaded += OnCefAppLoaded;

  // Consider to implement an awaitable CefApp.InitializeAsync method
  // instead of calling Run directly. This way you can remove the TaskCompletionSource pattern
  CefApp.Run(assembly);

  return this.TaskCompletionSource.Task;
}

private void OnLoaded(object sender, EventArgs e)
{
  this.TaskCompletionSource.SetResult(true);
}


text:
Q: Error while detecting scroll direction From this question on - How can I determine the direction of a jQuery scroll event?, I wrote this code.
var lastS=$(window).scrollTop();

function whatHappened()
{
    var currentS=$(window).scrollTop();
    console.log(lastS,currentS);

    if(currentS>lastS)
    {
       lastS = currentS;
       return "Scroll down";
    }
    else
    {
        lastS = currentS;
        return "Scroll up";
    }
}

$(window).on("mousewheel",function(){
    console.log(whatHappened());
});

This seems to work fine but there is a small problem. If I scroll down more than two times and then scroll up it first shows scroll down then scroll up. Similar happens in vice-versa.
What's wrong?
Please help. Thanks in advance.
JS Fiddle: http://jsfiddle.net/3843e/

A: The mousewheel event is non-standard - in your case, it's probably getting triggered before scroll information is updated, so you're always operating on the "previous" scroll height.


text:
Q: Как определить закрыта ли крышка ноутбука Как в C# определить, закрыта ли крышка ноутбука?
Нужно, чтобы программа выполняла действия только при закрытой крышке.
A: Великий и могучий приходит на помощь:

In Vista you can register for a callback for when the Lid Close Action changes. This is done by calling RegisterPowerSettingNotification (see http://msdn2.microsoft.com/en-us/library/aa373196.aspx for details). The GUID for this power setting you're interested in is GUID_LIDCLOSE_ACTION. This is defined in wdm.h in the Platform SDK.
Once registered, a WM_POWERBROADCAST will be sent to your application with wParam set to PBT_POWERSETTINGCHANGE. This event is sent anytime the value for the lid close action changes. The lParam contains a pointer to a POWERBROADCAST_SETTING structure (see http://msdn2.microsoft.com/en-us/library/aa372723.aspx) containing information on the setting change.

(отсюда)


text:
Q: finalize never called from the object by allocateInstance(Java) pleaes refer to the following code, i just want to do something about unsafe.
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.util.*;

public class A {

    public static void main(String[] args) throws Exception {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe u = (Unsafe) f.get(null);
        System.out.println("the while start at:" + new Date());
        long total = 0;
        while (true) {
            u.allocateInstance(B.class);
            total++;
            if (total % 100000000 == 0) {
                System.out.println(total);
                System.gc();
            }
        }
    }
}

class B {

    private int a;
    private int b;
    private double d;
    private float e;

    @Override
    protected void finalize() {
        try {
            super.finalize();
        } catch (Throwable e) {
            System.out.println("catch excep");
        }
        System.out.println("class B finalize, the a:" + a);
    }
}

the code is never oom, but the finalize of class B is never called.why?
i can not find the key information....

A: This OpenJDK thread notes the following:

Unsafe.allocateInstance() is implemented in HotSpot VM by directly calling JNI's AllocObject() function [1].
  An object instance is allocated in the Java heap, but no constructors are invoked for this instance.

Furthermore, the Java Langauge Specification (§12.6.0) specifically states that:

The completion of an object's constructor happens-before (§17.4.5) the execution of its finalize method (in the formal sense of happens-before).

Given that in your code you never actually call the constructors for the allocated instances, the Object.finalize() method cannot be called without first violating the aforementioned happens-before order (§17.4.5).
Therefore, the Object.finalize() method will never be called.


text:
Q: ANTLR - Populate a Java class while parsing the input message How can I, using ANTLR, populate a class of mine while I'm parsing the input message?
For example, if my input message is: name = Paul AND age = 16 AND country = china;
While I'm parsing this message, can I perform, in the Grammar file, something like:
Person p = new Person();
p.setName("Paul");
p.setAge("16");
p.setCountry("china");

Where Person.java is a class that I built. Or this can only be made in the main Java class where I print the AST?

A: If you want to create instance of your class from name = Paul AND age = 16 AND country = china that kind of script, then you could create yourself method
public <T> T builder(Class<T> clazz, String line)
            throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
        T instance = clazz.newInstance();
        String[] exps = line.split("AND");
        for (String exp : exps) {

            String[] tokens = exp.split("=", 2);
            // TODO check if token has length==2
            tokens[0] = tokens[0].trim();
            tokens[1] = tokens[1].trim();
            String methodName = "set"
                    + (("" + tokens[0].charAt(0)).toUpperCase())
                    + tokens[0].substring(1);
            Method m1 = instance.getClass().getMethod(methodName, String.class);
            m1.invoke(instance, tokens[1]);
        }
        return instance;
    }

and when you call it builder(Person.class,"name = Paul AND age = 16 AND country = china") you will get instance of Person class with populated fields name, age and country.
Is that what you are looking for?


text: Q: How do I configure MySQL to store specific entire InnoDB tables on a different drive in Windows ( Server )? After skimming the MySQL ( 5.5 ) docs on Partitioning, that seems to deal with breaking parts of the same table off onto other drives. I'm struggling to find information on how I pinpoint an incessantly used table in an application and throw it onto its own drive.


text:
Q: Javascript if syntax i have syntax error when i'm trying to run a simple if statements

[Break On This Error] });

invalid assignment left-hand side
[Break On This Error] container +=
what is my problem
and how i can make:
if this.ewCount != 0 then {}
elseif NotDoneh == 0 then {}
ELSE {}

this is my current code:
var conta = '
';
$.each(items, function () {
    if (this.ewCount != 0) {

        if (DoneWidth == 0) {
            conta += '
dddddddddddddddddd

' +
        });
        if (NotDoneh == 0) {
            conta += '
dddddddddddddddddd

' +
        });
    });

    container += '
' +

A: Remove the parentheses after the trailing curly brace of the if block.
 if (NotDoneh == 0) {   conta += '
dddddddddddddddddd

' +
 });

should be
 if (NotDoneh == 0) {   conta += '
dddddddddddddddddd

' +
 } // <-- No ); <-- This is not a smiley, but a parenthesis + semicolon.

A: if (this.ewCount != 0) {
  if (DoneWidth == 0) {
    conta += '
dddddddddddddddddd

';
  }
  if (NotDoneh == 0) {
    conta += '
dddddddddddddddddd

';
  }
}

A: var conta = '
';
    $.each(items, function () {
       if (this.ewCount != 0)
       {
          if (DoneWidth == 0) {
          conta += '
dddddddddddddddddd

'
          }

          if (NotDoneh == 0) {
          conta +=  '
dddddddddddddddddd

'
           }
        }

       else{ //here you do the else  }
     });

A: elseif NotDoneh == 0 then {}

You don't have elseif in JS, you should use else if instead:
else if NotDoneh == 0 then {}

A: To take your pseudo-code:
if this.ewCount != 0 then {}
elseif NotDoneh == 0 then {}
ELSE {}

and turn it into JavaScript:
if (this.ewCount != 0) {
   // do something
} else if (NotDoneh == 0) {
   // do something else
} else {
   // do something else again
}

In your actual JS there are several problems, mainly that you've got the + operator on the end of some lines without another operator after it, and you've closed each of your if statements with }); when they should've just had } - I think you've got that mixed up with how you need to close the $.each since it is a function call with a function as a parameter so it needs to be $.each(items,function() { });.
I'm not sure how to rewrite your JS, because it has an if (DoneWidth == 0) test that isn't in your pseudo-code - is that supposed to be nested inside the first if, or...? Anyway, if you update it to look like the following it should at least be valid, even if not the right algorithm:
$.each(items, function () {
    if (this.ewCount != 0) {
        // note the following if is nested inside the one above: not sure
        // if that's what you intended, but it gives a good example of
        // how to do something like that
        if (DoneWidth == 0) {
            conta += '
dddddddddddddddddd

';
        }
    } else if (NotDoneh == 0) {
            conta += '
dddddddddddddddddd

';
    } else {
        // you don't seem to have any code to go in the final else,
        // unless it was meant to be
        container += '
';
    }

    container += '
';
 }); // note here }); is correct because the } closes the anonymous function
     // and then the ); finishes off the $.each(...

You can put that together with the if/else structure that I showed above, and/or otherwise move things around so the right bit of code ends up inside the right if or else.


text:
Q: Search if jsonb array of string contains value I have arry of strings in a column like :  ["196 2616", "9503744", "36.25260-6027", "2 414 425", "7 034 771 6", "F709714", "1088229", "183144", "505870338", "105075"]
I want to search if this array contains for example 2 414 425.
I tried something like this:
 SELECT * FROM  table_name t where t.numbers @> '2 414 425'
But it doesnt return anything even when it should.

A: I found something like this:
select carat_id from table where (numbers)::jsonb ? '13261999';

A: The @> operator needs a proper JSON object on the right hand side:
where t.numbers @> '["2 414 425"]'

This should work if numbers is defined as jsonb (which it should be). Otherwise cast it numbers::jsonb
Checking if at least one of multiple keys is contained in the JSON array can be done using the ?| operator:
where t.numbers ?| array['2 414 425', '13261999']

The ?& operator will check if all those keys are contained in the JSON array.


text:
Q: Fail creating a SubMenu in a component with antd I'm using antd: ^3.5.4
I have a menu that contains items for user management.
When not logged the menu has a menuItem with a Link to Login page
When logged in, the menu has a SubMenu with several links including Log out
I just make a simple test on my user connected to display the link or the submenu.
I works well when all in the same file
    <Menu mode="horizontal">
      <Menu.Item key="home">
        <Link to={RoutesNames.HOMEPAGE}>Home</Link>
      </Menu.Item>
      {this.props.currentUserIsSignedIn ? (
      <SubMenu key="usermenu" title={<Avatar>A</Avatar>}>
        <Menu.Item key="info">{this.props.currentUserEmail}</Menu.Item>
        <Menu.Item key="logout">
          <Link onClick={this.props.signOutUser}>Log out</Link>
        </Menu.Item>
      </SubMenu>
      ) : (
      <Menu.Item key="login">
        <Link to={RoutesNames.LOGIN}>Signin / Register</Link>
      </Menu.Item>
      )}
    </Menu>

The problems begin when I try to create a Component UserMenu that handle this logic.
What I want to have at the end is
    <Menu mode="horizontal">
      <Menu.Item key="home">
        <Link to={RoutesNames.HOMEPAGE}>Home</Link>
      </Menu.Item>
      <UserMenu user={this.props.currentUser}/>
    </Menu>

I create my sub component UserMenu.
First I have this error:
    Uncaught TypeError: Cannot read property 'isRootMenu' of undefined
at ProxyComponent.render (SubMenu.js:274)

So I updated my UserMenu component to define parentMenu
   <SubMenu parentMenu={this.props.menu}

and set the parent as parentMenu in my header file
   <Menu
     mode="horizontal"
     ref={el => this.menu = el}
   >
     <UserMenu menu={this.menu} user={this.props.currentUser} />
   </Menu>

With this menu props the subMenu is showing but I still got an error when mouseover and mouseout the submenu
    Uncaught TypeError: onItemHover is not a function
at onTitleMouseEnter (SubMenu.js:454)

For this one I have absolutely no idea what to do.
Thanks for your help

A: Menu passes additional props down to it's children. You need to make sure those props are passed down from your UserMenu component to the SubMenu component that you render. You can do this with an object spread operator. Example:
const UserMenu = (props) => {
     const {username, customProp, ...other} = props;

     return <SubMenu {...other}>
          This is my {customProp} for {username}
     </SubMenu>
}


text:
Q: Can this JavaScript be optimized? This JS will be executed on pages with a lot of fields. Can you see anyway to improve the speed of this code? If so, can you explain what you found?
var _TextInputs = null;
function GetTextInputs()
{
    if (_TextInputs == null)
    {
        _TextInputs = jq('input[type=text]');
    }

    return _TextInputs;
}

var _Spans = null;
function GetSpans()
{
    if (_Spans == null)
    {
        _Spans = jq('span');
    }

    return _Spans;
}

function UpdateRate(ratefield, name)
{
    GetTextInputs().filter('[' + name + ']').each(function()
    {
        this.value = FormatCurrencyAsString(FormatCurrencyAsFloat(ratefield.value));
        CalculateCharge(name.replace('Rate', ''), jq(this).attr(name));
    });
}

function CalculateCharge(name, activity_id)
{
    var inputs = GetTextInputs();
    var bill_field = inputs.filter('[' + name + 'Bill=' + activity_id + ']');
    var rate_field = inputs.filter('[' + name + 'Rate=' + activity_id + ']');
    var charge_field = GetSpans().filter('[' + name + 'Charge=' + activity_id + ']');

    charge_field.text(FormatCurrencyAsString(FormatCurrencyAsFloat(bill_field.val()) * FormatCurrencyAsFloat(rate_field.val())));
}

A: You can:

*

*Replace each with while

*Replace val() with .value (should be fine as long as those fields are plain text ones)

*Access elements by class instead of by name/type

*Replace attr() with plain property access; e.g.: this.attr(name) --> this.name
These are all rather unobtrusive changes which should speed things up mainly due to cutting down on function calls.
Don't query elements on every function call if those elements are static (i.e. are not modified during your app life-cycle). Instead, store them outside the loop.

A: I can see that you're using attribute filters everywhere, e.g.:
_TextInputs = jq('input[type=text]');

inputs.filter('[' + name + 'Bill=' + activity_id + ']');

Attribute filters are useful, but not especially 'snappy' when compared to more direct class or ID selectors. I can't see any markup so the best I can do is suggest that you use more IDs and classes, e.g.:
jq('input.textInput');

instead of:
jq('input[type=text]');

A: A little off-topic, but I use and recommend Javascript Rocks. This books contains a TON of awesome JS optimisation advice by the creator of Scriptaculous. Also comes with a tool called DOM Monster which helps track down performance bottlenecks - it's an awesome compliment to Firebug as it actually tracks through the DOM looking for inefficiencies based on heuristics and DOM complexity.


text:
Q: Why is my .trash folder not visible in single user mode? So I booted of to single user mode for fun and I was checking whether my trash folder will be present there but it was not and I also mounted / as read and write but when I boot to my Mac and then use terminal I can see my trash with its contents fine. I am just wondering why I can't access my trash in single user mode?
I actually checked if my trash folder exists by typing ls -a /Users/homedirectoryname/


text:
Q: Using decimal data type to work with monetary values with db2 and delphi 2010 I'm using delphi 2010 with db2 9.7 Express-C and I have a database that has several fields of decimal type to work with monetary values. Now I see that there are some problems using it, like the 9.20 value displays the value 9.19999980926514 in my front-end. I need to change all the fields in my database to DECFLOAT or is there a function, property in tfield or other alternative to solve it ?
Thanks.
Davis

A: working directly with monetary decimals is almost always a problem. due to different conversions made from the database to your front-end application, it is possible to lose or to gain(this applies to most of the financial systems also - see bankers rounding).
I suggest you to use the RoundTo function before making operations/display/etc. A very good article about rounding http://docwiki.embarcadero.com/RADStudio/XE2/en/Floating-Point_Rounding_Issues
Another suggestion will be using of the Currency type. Here is a question on SO with good explanation about this type How to avoid rounding problems when comparing currency values in Delphi?


text:
Q: Get multiple time restarted pod list in kubernate From the below pods, how can we get a list of pods which have been restarted more than 2 times. How can we get in a single line query ?
xx-5f6df977d7-4gtxj                 3/3     Running            0          6d21h
xx-5f6df977d7-4rvtg                 3/3     Running            0          6d21h
pkz-ms-profile-df9fdc4f-2nqvw       1/1     Running            0          76d
push-green-95455c5c-fmkr7           3/3     Running            3          15d
spice-blue-77b7869847-6md6w         2/2     Running            0          19d
bang-blue-55845b9c68-ht5s5             1/3     Running            2          8m50s
mum-blue-6f544cd567-m6lws                  2/2     Running            3          76d

A: Use:
kubectl get pods | awk '{if($4>2)print$1}'

Use -n "NameSpace" if required to fetch pods on the basis of a namespace.
For example:
kubectl get pods -n kube-system | awk '{if($4>2)print$1}'
where $1, $4 : Depends on which column pod name is present , column on which filter is to be done respectively
Note: awk will work in linux whereas

A: Actually is not possible to use field selector to get this result, as mentioned in this github open issue.
You can use kubectl with the option -o jsonpath to get the container name that whas restart more than 2 times. Example:
kubectl get pods -o jsonpath='{.items[*].status.containerStatuses[?(@.restartCount>=2)].name}'


text:
Q: Cakephp url customisation for SEO
I am developing a medical products search site. I need to display my site in search engines whenever a user try to search [COMPANY NAME] medicine [DISEASE]. For this, i created a page in my site which reads COMPANY NAME and DISEASE from url and lists all products.

Now i need to give this page a url like www.sitename.com/[COMPANY NAME]_medicine_[DISEASE].html
I am using Cakephp framework for development. Is there anyway to implement this url formatting in routes.php ? Or is there any other way ? please help.

A: how about separating them with slashes?
// www.sitename.com/[COMPANY NAME]/medicine/[DISEASE]

Router::connect('/:company/medicine/:disease', array('controller' => 'diseases', 'action' => 'index'),
                                               array('pass'=>array('company','disease'),
                                               'company'=>"[a-zA-Z\.]+*",
                                               'disease'=>'[a-zA-Z\.]+'));

and the controller
function diseases($company,$disease){

}

I'm not sure if you can use the underscore instead of the slashes, I have never tried it before. if you do try I'd like to know the results =)
Good Luck
EDITED: ok, i was too curious about this issue and i wrote a route like this
Router::connect('/:company_medicine_:disease', array('controller' => 'pages', 'action' => 'test'),
                                               array('pass'=>array('company','disease'),
                                               'company'=>'[a-zA-Z]+',
                                               'disease'=>'[a-zA-Z]+'));

and its not working u_U
as i suspected, the problem is that Cake thinks that the name of the custom route element is :company_medicine and not :company.. after a few minutes regarding/reading the code of Cake i found out the exact place where Cake parses the route and extracts the names of the passed elements. It's in /cake/libs/router.php in the class CakeRoute, method _writeRoute() (about line 1369):
preg_match_all('#:([A-Za-z0-9_-]+[A-Z0-9a-z])#', $parsed, $namedElements);

so as you can see in the regexp, the names of the elements can contain an underscore,therefore Cake thinks the name of the parameter is ":company_medicine".
So you have four solutions:

*

*use slashes as separators for your urls

*change the order of your parameter so it would be medicine_[COMPANY]_[DISEASE]

*modify the line 1369 of the router.php to this (NOT RECOMENDED, i think it will break routes for plugins):
preg_match_all('#:([A-Za-z0-9]+)#', $parsed, $namedElements);

*use url rewrite in your .htaccess to redirect all [COMPANY]_medicine_[DISEASE] to [COMPANY]/medicine/[DISEASE] so cake will see it separated by slashes and the browser will see it separated bu underscores. (I haven't tested it, i've never added another rule to the .htaccess for Cake =P)


text:
Q: Only gravitation and Newton's $2^{\mathrm{nd}}$ law needed to derive Kepler's laws? It is known that Kepler's laws of planetary motion can be derived from Newton's laws of motion and his law of universal gravitation. However, are all of Newton's laws of motion necessary?
According to this website, all of Kepler's laws can be derived from gravitation and the Newton's second law ($\mathbf{F} = m\mathbf{a}$). Does this mean that Newton's first and third laws are irrelevant for planetary motion?
Perhaps Newton's third law (action-reaction) is necessary to take into account the motion of the Sun as induced by gravitational pull from the orbiting planets, but when deriving Kepler's laws the Sun is assumed to be fixed...


text:
Q: Why are functions run in the module script file not in the window object? The script file embedded directly in the HTML file, the functions contained in the window object. We can check with the following code.
    for(let i in window)
    {
        if ((typeof window[i]).toString() === "function" && !window[i].toString().includes("[native code]"))
        {
            console.log(i);
            console.log(window[i]);
            console.log("\n\n");
        }
    }

But when I run a function indirectly by importing it from module why isn't it in there?
This is my file structure.
 1. index.html
 2. script.js
 3. moduleScript.js
 4. ModuleScript
    - moduleScript01.js
    - moduleScript02.js

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Event Listener</title>
    <script src="moduleScript.js" type="module"></script>s
    <script src="script.js"></script>
</head>
<body>
    <script type="module" defer>
        import * as moduleScript from "./moduleScript.js";

        console.log(moduleScript.moduleScript01.Level01(1,2));
        console.log(moduleScript.moduleScript02.Level02(1,2, 3));
        console.log("\n\n");

        for(let i in window)
        {
            if ((typeof window[i]).toString() === "function" && !window[i].toString().includes("[native code]"))
            {
                console.log(i);
                console.log(window[i]);
                console.log("\n\n");
            }
        }

    </script>
</body>
</html>

script.js
function Level01 (a, b)
{
    return a + b;
}

function Level02 (a, b, c)
{
    return Level01(a,b) - c;
}

function Level03 (a, b)
{
    return  Level02(a,b, 1) * 5;
}

function print ()
{
    console.log("Hello world");
}

moduleScript.js
export * as moduleScript01 from "./ModuleScript/moduleScript01.js";
export * as moduleScript02 from "./ModuleScript/moduleScript02.js";

moduleScript01.js
function Level01 (a, b)
{
    return a + b;
}

export
{
    Level01
}

moduleScript02
function Level02 (a, b, c)
{
    return Level01(a,b) - c;
}

export
{
    Level02
}


text:
Q: .htaccess redirect a clean image url I am trying to do clean URLs for images, where the url also contains a description of the image (for seo purposes).  The only important part of the file name is the start and the extension.
I am trying to get like image URLs such as:

mywebsite.com/seo-images/123-some-description.jpg

to do a clean url rewrite where the image is actually located at

mywebsite.com/uploads/123.jpg

file types can be .jpg or .png or .gif etc.
I also have thumbnails:

mywebsite.com/seo-images/t123-some-description.jpg

to do also do a clean url rewrite in the same way and place

mywebsite.com/uploads/t123.jpg

I have tried putting the following .htaccess file in the seo-images directory
RewriteEngine On
RewriteBase /seo-images/

# match all numbers upto - then get the extension after .
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^([_0-9a-zA-Z-]+/)?-([_0-9a-zA-Z-]+/)?([_0-9a-zA-Z-]+/)\.$ /uploads/$1.$3 [R=301,L]

so far, no good.
I have a .htaccess file in the root that does other clean mod_rewrites.
The "some-description" can be one word or many words separated by - so basically everything after the - and before the . should be disregarded and the new filename used to rewrite using the new filename in a different directory

A: I think you would use rather this simpler rules set in /seo-images/.htaccess, we rewrite only if %{REQUEST_FILENAME} is neither a file nor a directory, not the inverse:
RewriteEngine On
#RewriteBase /seo-images/

# match all numbers upto - then get the extension after .
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^-]+)-.*\.([[:alnum:]]+)$ /uploads/$1.$2 [L]

Without redirect, we use only an internal rewrite, Google will always think about mywebsite.com/seo-images/123-some-description.jpg instead of mywebsite.com/uploads/123.jpg .
Or you prefer absolutely rewriting:
RewriteEngine On
#RewriteBase /seo-images/

# match all numbers upto - then get the extension after .
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^-]+)-.*\.([[:alnum:]]+)$ /uploads/$1.$2 [R=301,L]

It does this:
/seo-images/123-some-description.jpg => /uploads/123.jpg
/seo-images/t123-foo-bar.png => /uploads/t123.png


text:
Q: Refactor Method Complexity in RAILS I synchronized my app with Code Climate for code review.
lib/models/user/synchrony/basecamp_inc.rb
def todo_list(todos,basecamp_account,proj_id)
  todos.map{|todo|
    task = basecamp_tasklist(proj_id,todo['id'],basecamp_account)
    task_list(task['todos']['remaining'],task['name'],'remain') if task['todos']['remaining'].present?
    task_list(task['todos']['completed'],task['name'],'complete') if task['todos']['completed'].present?
  }
end

def task_list(tasks,todo_list,status)
  tasks.map{|task|
    task_created(task,todo_list)
    task['assignee'].present? && user_owner?(task['assignee']['name']) ? save_task_activity('was assigned to a',task,todo_list,task['updated_at'],'assign') : [tasks,todo_list,status]
    status == 'complete' && user_owner?(task['completer']['name']) && current_date?(task['completed_at']) ? save_task_activity('finished',task,todo_list,task['completed_at'],'finished') : [tasks,todo_list,status]
  }
end

The codes above were detected by Code Climate as having complex methods. I don't get why Code Climate thought of it as complex. So then, the rank of that code is still a C and I want to refactor it. How can I improve this?

A: You should consider moving the following conditions into private methods:
task['assignee'].present? && user_owner?(task['assignee']['name']) ? save_task_activity('was assigned to a',task,todo_list,task['updated_at'],'assign') : [tasks,todo_list,status]
status == 'complete' && user_owner?(task['completer']['name']) && current_date?(task['completed_at']) ? save_task_activity('finished',task,todo_list,task['completed_at'],'finished') : [tasks,todo_list,status]

You should consider moving the following calls to a single method taking a status argument for example:
task_list(task['todos']['remaining'], task['name'], 'remain') if task['todos']['remaining'].present?

Would be refactored as:
def build_task_list(tasks, name, status)
  task_list(tasks, name, status) if task.present?
end

build_task_list(task['todos']['remaining'], task['name'], 'remain')
build_task_list(task['todos']['completed'], task['name'], 'complete')


text:
Q: Google Maps lazy loading in angularjs with dynamic geo coordinate updates? I created a directive for lazy loading google maps with angularjs:
http://plnkr.co/edit/1NpquJ?p=preview
Taken from:
AngularJS - load google map script async in directive for multiple maps
Question: How can I dynamically bind the lat/long values to a controller, so that every time the values in the controller change, the map also changes the view?
(eg a backend call serves new lat/long values, which must then be pushed to the map element).
I added to the maps directive:
  scope: {
      lat: '=',
      long: '='
  }

And bind it twoway with:
<div lat="{{lat}}" long="{{long}}" />

Controller:
$http..getBackendData()
    .then(function(data) {
        $scope.lat = data.lat;
        $scope.long = data.long;
    }
);
...

Anyways the map only shows up with the initial value, but is never updated. Example: http://plnkr.co/edit/U31poBpHTfFVQsipLrI4?p=preview

A: For now it works adding a $watch on latitude:
http://plnkr.co/edit/eS18B0Te2l5qaf6wvQIH?p=preview
scope.$watch('lat', function (newVal) {
    initializeMap();
});

But I don't know if this is the correct approach. Feel free to comment if you have betters solutions.


text:
Q: C# - It's not possible to create an object with padding from the keyboard In the Main() method, implement the following algorithm programs:

*

*After starting the program from the keyboard, enter the number
elements (for example, dogs), creates an array of objects of the class
(for example, Dog), the size of the array corresponds to the number of these elements (for example, dogs).

*Several objects of the class (Dog class) are created in the loop depending on the number specified in the previous step, for each of these objects the name, breed, weight and age are set automatically on the keyboard (non-static method Next() of the Random class), these parameters are assigned to each
object through the constructor.

Each newly created object must be stored in an array of objects.
I am new to programming, I will hope for help.
I got this code, I don't know how to create and populate objects:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Dog
    {
        private string name;     // кличка
        private string breed;    // порода
        private double weight;   // вага
        private int age;         // вік
        private char gender;     // стать

        public void Info()
        {
            name = Console.ReadLine();
            breed = Console.ReadLine();
            weight = double.Parse(Console.ReadLine());
            age = int.Parse(Console.ReadLine());
            gender = char.Parse(Console.ReadLine());

            Console.WriteLine($"Кличка: {name} | Порода: {breed} | Вага: {weight} | Вік: {age} | Стать: {gender}");
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            int dogsCount = int.Parse(Console.ReadLine());
            int[] dogs = new int[dogsCount];

            for(int i = 0; i < dogs.Length; i++)
            {
                Console.WriteLine($"Введіть елемент масиву під індексом {i}:\t");
                dogs[i] = int.Parse(Console.ReadLine());
            }

            for(int i = 0; i < dogs.Length; i++)
            {
                Console.WriteLine(dogs[i]);
            }

            //Dog dog = new Dog();
            //dog.Info();
        }
    }
}

A: You should define constructor which save input properties to new dog object. Method GetInfo returns string with complete info about dog.
After start you have to ask to dog count and then in for loop you have to read individual properties for each dog. These properties you should send to the constructor of the dog object. Then you can save new dog to array and show info about dog.
using System;

public class Dog
{
    private string Name { get; set; }
    private string Breed { get; set; }
    private double Weight { get; set; }
    private int Age { get; set; }
    private char Gender { get; set; }

    public Dog(string name, string breed, double weight, int age, char gender)
    {
        Name = name;
        Breed = breed;
        Weight = weight;
        Age = age;
        Gender = gender;
    }

    public string GetInfo()
    {
        return string.Format("Name: {0} | Breed: {1} | Weight: {2} | Age: {3} | Gender: {4}", Name, Breed, Weight, Age, Gender);
    }
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine("How many dogs?");
        int dogsCount = int.Parse(Console.ReadLine());

        Dog[] dogs = new Dog[dogsCount];

        for(int i = 0; i < dogsCount; i++)
        {
            Console.WriteLine("==================================");
            Console.WriteLine(string.Format("Creating dog {0}/{1}", i + 1, dogsCount));

            Console.WriteLine("Name:");
            var name = Console.ReadLine();

            Console.WriteLine("Breed:");
            var breed = Console.ReadLine();

            Console.WriteLine("Weight:");
            var weight = double.Parse(Console.ReadLine());

            Console.WriteLine("Age:");
            var age = int.Parse(Console.ReadLine());

            Console.WriteLine("Gender:");
            var gender = char.Parse(Console.ReadLine());

            var dog = new Dog(name, breed, weight, age, gender);
            dogs[i] = dog;
            Console.WriteLine(string.Format("Created dog -> {0}", dog.GetInfo()));
        }
    }
}


text:
Q: Fundamental theorem of line integral over parabola Let $C$ represent the parabolic path $y = x^2 - 1$ from the $(0,-1)$ to $(1,0)$. Using the fundamental theorem of line integrals, evaluate
$$
\int_C(ye^x-\sin x)dx+(e^x+2)dy
$$
I know that the fundamental theorem of line integrals states that
$$
\int_C\boldsymbol{\nabla} f \cdot dr=f(r(b))-f(r(a))
$$
but how do you apply it to this problem?

A: You want to find a scalar function $f$ such that
$$\nabla f = (ye^x-\sin x, e^x+2).$$
For that, we can take
$$f(x,y) = ye^x + \cos x + 2y.$$
Then,
$$\int_C (ye^x - \sin x) \ dx + (e^x + 2) \ dy = \int_C \nabla f \cdot dr = f(1,0) - f(0,-1) = \cos 1 + 2.$$
You can check this by just parametrizing the curve ($r(t) = (t,t^2-1)$ for $0\leq t\leq1$) and computing the integral:
$$\int_C (ye^x - \sin x) \ dx + (e^x + 2) \ dy = \int_0^1 (t^2-1)e^t - \sin t + 2t(e^t + 2) \ dt.$$
This is obviously more involved, but a few applications of integration by parts should take care of non-trivial parts.


text:
Q: Animating element dimensions using CSS transform transition I'm trying to achieve a smooth animation (60 fps) of header's height, which is initially 100% height of window, while the target (after clicking nav link) is fixed (80px). Simply using css transition on height is just not smooth enough, as well as using jQuery animate function. I'm using transform transitions for other elements, but I just have no idea, how could I make this one work properly. I prefer using css on this, but jq solution would also be fine.
This is the page: http://mariuszbrozek.com/test
HTML looks like this:

    ...

    ...

    ...

At the beginning, content section is not displayed, it appears after clicking nav link.


text:
Q: Как правильно работать с api в react-redux? У меня конкретная проблема, что две перменные props имеют три разных значения в одном компоненте.
Суть такая, что мне нужно принять с сервера массив товаров и вычислить максимальное и минимальное значение цены, чтобы задать дефолтные значения и макс. минимальные для слайдера.
Я предполагаю, что нужно это делать сразу после получения. Я не стал выкладывать сюда функции по нахождению макс. и мин. значению, тк ошибка возникает даже с этим упрощенным кодом. Как видно на скриншоте, второе дефолтное значение у слайдера остается то что задано в initial state.
Если экшн будет синхронным, обычным, то все ок...
Прошу помочь. Как правильно работать с данными полученными с сервера асинхронно ?
Код и скриншот ниже.

Часть кода компонента
max = this.props.max
min = this.props.min

{ min }-

{ max }

            <Slider range step={100}
                defaultValue={[min, max]}
                min={min} max={max}
            />

Actions
export const requestPosts = () => ({
    type: "REQUEST_POSTS"
})

export const receivePosts = (json) => ({
    type: "RECEIVE_POSTS",
    posts: json,
    receivedAt: Date.now()
})

export function fetchPosts() {
    return function (dispatch) {
        dispatch(requestPosts())

        return fetch('http://localhost:3000/studios')
            .then(response => response.json())
            .then(json => dispatch(receivePosts(json)))
    }

}

Reducers
const INITIAL_STATE = {
    list: [],
    min: 1400,
    max: 1700,

};

const receivePosts = (state, action) => {

    return {...state,
        list: action.posts,
        max: 1800,
        min: 1500
    }

}

export default (state = INITIAL_STATE, action) => {
    switch (action.type) {
    case 'CHANGE_VALUE':
        return changeValue(state,action)
    case 'RECEIVE_POSTS':
        return receivePosts(state,action)

    }

    return state

}


text:
Q: Bash verbose command with evaluating parameters I am trying to log the command with its parameters (after evaluating if necessary) in Bash.
I am trying to use set -v:
$ variable=2
$ set -v
$ sleep $variable
sleep $variable

As you can see, it prints sleep $variable. I want to log sleep 2 instead.
My original command is more complex, so I don't want to echo each parameter one by one. (And it is probably more error prone to do so).

A: set -v (or set -o verbose) will output every command as it is read, without expanding things.
set -x (or set -o xtrace) will output the expanded command line before execution.  Each line is prepended by the PS4 prompt (usually a +) and for commands executed as part of command substitutions, the prompt will be "doubled up" (++).
The trace will be written to the file descriptor indicated by $BASH_XTRACEFD (or to the shell's standard error by default).


text:
Q: Pyspark throwing error while trying to read parquet I am a newbie in pyspark, While trying to read parquet file through pyspark I get the below error. I have tried various things like reinstallation of jre and jdk, updating environment variables. Matching winutils.exe but nothing seems to work.
Error: **
An error occurred while calling o60.load.
: java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:793)
    at org.apache.hadoop.fs.FileUtil.canRead(FileUtil.java:1215)
    at org.apache.hadoop.fs.FileUtil.list(FileUtil.java:1420)
    at org.apache.hadoop.fs.RawLocalFileSystem.listStatus(RawLocalFileSystem.java:601)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1972)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:2014)
    at org.apache.hadoop.fs.ChecksumFileSystem.listStatus(ChecksumFileSystem.java:761)
    at org.apache.spark.util.HadoopFSUtils$.listLeafFiles(HadoopFSUtils.scala:225)
    at org.apache.spark.util.HadoopFSUtils$.$anonfun$parallelListLeafFilesInternal$1(HadoopFSUtils.scala:95)
    at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:286)
    at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:62)
    at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:55)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:49)
    at scala.collection.TraversableLike.map(TraversableLike.scala:286)
    at scala.collection.TraversableLike.map$(TraversableLike.scala:279)
    at scala.collection.AbstractTraversable.map(Traversable.scala:108)
    at org.apache.spark.util.HadoopFSUtils$.parallelListLeafFilesInternal(HadoopFSUtils.scala:85)
    at org.apache.spark.util.HadoopFSUtils$.parallelListLeafFiles(HadoopFSUtils.scala:69)
    at org.apache.spark.sql.execution.datasources.InMemoryFileIndex$.bulkListLeafFiles(InMemoryFileIndex.scala:158)
    at org.apache.spark.sql.execution.datasources.InMemoryFileIndex.listLeafFiles(InMemoryFileIndex.scala:131)
    at org.apache.spark.sql.execution.datasources.InMemoryFileIndex.refresh0(InMemoryFileIndex.scala:94)
    at org.apache.spark.sql.execution.datasources.InMemoryFileIndex.<init>(InMemoryFileIndex.scala:66)
    at org.apache.spark.sql.execution.datasources.DataSource.createInMemoryFileIndex(DataSource.scala:565)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:409)
    at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:274)
    at org.apache.spark.sql.DataFrameReader.$anonfun$load$3(DataFrameReader.scala:245)
    at scala.Option.getOrElse(Option.scala:189)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:245)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:188)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
    at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
    at java.lang.Thread.run(Thread.java:750)

**
Edit - code is quite simple:-
python
import pyspark.sql.functions as F
import pandas as pd
from pyspark.sql import SparkSession
from pyspark.sql.types import TimestampType
from pyspark.sql.utils import AnalysisException

spark = SparkSession.builder.getOrCreate()

path = "C:\\ProgramData\\MyData"

df = spark.read.format("parquet").option("header",True).load(str(path))

I am using spark-3.2.1-bin-hadoop3.2. Python version is 3.10.
Solution:- Copy winutils from link and try one by one version and check which version is working. Ideally the version matching with Pyspark version should work but different version worked in my case.
Please help out if you get any clue.


text:
Q: nonblocking BIO_do_connect blocked when there is no internet connected I am using Openssl-0.9.8x as follows:
bio = BIO_new_ssl_connect(ctx);
BIO_get_ssl(bio, & ssl);
SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
BIO_set_nbio(bio, 1);
in_addr_t serverIP =  inet_addr(HTTPS_SERVER_IP);
BIO_set_conn_ip(bio, &serverIP );
BIO_set_conn_port(bio, HTTPS_SERVER_PORT_STR);
while(1) {
    printf("BIO_do_connect start>>>>\n");
    if(BIO_do_connect(bio) <= 0 && BIO_should_retry(bio)) {
        sleep(1);
        printf("BIO_do_connect retry>>>>\n");
    }
    else {
        printf("Connect success.\n");
    }
}

It works fine when the internet connection is OK (i.e. it can connect to the server). But, when the internet connection is limited (i.e. it can't connect to the server), the BIO_do_connect() is blocked after one or more times of retry.
The output as follows:
BIO_do_connect start>>>>
BIO_do_connect retry>>>>
BIO_do_connect start>>>>
BIO_do_connect retry>>>>
BIO_do_connect start>>>>

Finally, it is blocked in BIO_do_connect(...)? why this happened?

A: It is probably your use of SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY).
From the 0.9.8 man page:

SSL_MODE_AUTO_RETRY
Never bother the application with retries if the transport is blocking.
      If a renegotiation take place during normal operation, a
      SSL_read() or SSL_write() would return
      with -1 and indicate the need to retry with SSL_ERROR_WANT_READ.
      In a non-blocking environment applications must be prepared to handle
      incomplete read/write operations.
      In a blocking environment, applications are not always prepared to
      deal with read/write operations returning without success report. The
      flag SSL_MODE_AUTO_RETRY will cause read/write operations to only
      return after the handshake and successful completion.

The effect of SSL_MODE_AUTO_RETRY is to automatically retry operations that would otherwise return back to application code (even when the using blocking connections). It doesn't make any sense to use it when you want non-blocking operation.
Try removing that line completely.
By the way 0.9.8 is out of support and is no longer receiving security updates. You really ought to upgrade to a more recent version.

A: Add the following:
in_addr_t serverIP =  inet_addr(HTTPS_SERVER_IP);
BIO_set_conn_ip(bio, &serverIP );
BIO_set_conn_port(bio, HTTPS_SERVER_PORT_STR);


text:
Q: MySQL Markup Records with Duplicates on Select I have seen MySQL Mark Records with Duplicates question and answers. But I have a different situation.
How to select all records, but have a flag for those records who have duplicates in a given field.
id     name
--------------
1      John
2      Peter
3      John
4      David

And I want something like that:
SELECT
    id,
    name,
  -- IF(~duplicate in name~, 1, 0) AS is_duplicate
FROM tab

A: I assume id is set to auto increment then you can use following query for your desired output
select distinct a.*,
case when b.id is null then 0 else 1 end `duplicate`
from tab a
left join tab b
on a.name = b.name
and a.id > b.id
order by a.id

Demo


text:
Q: eliminar un campo dinamicamente pero a partir de que se agregue otro campo quiero que me aparesca el boton de eliminar a partir del segundo campo porfavor ;v es mi jquery el cual clona el campo , las filas es cada una de mis tablas

    $(function(){

    $("#adicional").on('click', function(){
      $("#tabla tbody tr:eq(0)").clone().removeClass('fila').appendTo("#tabla");
    });
    $("#adicional2").on('click', function(){
      $("#tabla2 tbody tr:eq(0)").clone().removeClass('fila2').appendTo("#tabla2");
    });
    $("#adicional3").on('click', function(){
      $("#tabla3 tbody tr:eq(0)").clone().removeClass('fila3').appendTo("#tabla3");
    });
    $("#adicional4").on('click', function(){
      $("#tabla4 tbody tr:eq(0)").clone().removeClass('fila4').appendTo("#tabla4");
    });

    $(document).on("click",".eliminar",function(){
      var parent = $(this).parents().get(0);
      $(parent).remove();
    });
  });
</script>

parte de mi html

Gastos Velada:

      <select id="letra2" name="tipo_gasto" class="select" required="">
        <option>Gastos velada:</option>
        <option>Tansporte</option>
        <option>Alimentos</option>
         <option>Otros gastos</option>
      </select>

      <input required id="letra2" type="number" class="redondeado" step="any" name="costo" placeholder="Ingrese Costo"/>

     <input type=image src="<?=URL ?>public/img/delete.png" width="35" height="35"/>

     <button  type="button" id="adicional4" class="boton_3" ><img src="<?
    =URL
    ?>public/img/anadir.png" width="25" height="25"/> CAMPOS</button>

A: Puedes esconder el boton en la primera fila y mostrarlo a la hora de clonar.  Algo asi:

$("#adicional4").on('click', function(){
  $("#tabla4 tbody tr:eq(0)")
    .clone().removeClass('fila4').appendTo("#tabla4").find(".eliminar").show();
});

$(document).on("click",".eliminar",function(){
      var parent = $(this).parents().get(0);
      $(parent).remove();
    });

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

Gastos Velada:

      <select id="letra2" name="tipo_gasto" class="select" required="">
        <option>Gastos velada:</option>
        <option>Tansporte</option>
        <option>Alimentos</option>
         <option>Otros gastos</option>
      </select>

      <input required id="letra2" type="number" class="redondeado" step="any" name="costo" placeholder="Ingrese Costo"/>

     <button  type="button" id="adicional4" class="boton_3" > CAMPOS</button>


text:
Q: How to fix invalid SSL record content type hello i am getting this error when trying to connect to SSL in java using the SSLFactory
Stack trace:
javax.net.ssl.SSLHandshakeException: invalid SSL record content type
at com.ibm.j9.jsse.SSLSocketImpl.completeHandshake(Unknown Source)
at com.ibm.j9.jsse.SSLSocketImpl.getInputStream(Unknown Source)

Here's the code error during handshake:
_socket = SocketFactory.getSslSocket( _socket, //Socket created before this call
                                       _address, //host that supports SSL
                                       _port.intValue() );

 SSLSocket tempSocket = (SSLSocket)_socket;

 String[] supportedCipherSuites = tempSocket.getSupportedCipherSuites();

 System.out.println( "Supported Cipher Suites:" );
 for( int i = 0; i < supportedCipherSuites.length; i++ )
 {
    System.out.println( supportedCipherSuites[i] );
 }

 tempSocket.setUseClientMode( true );
 tempSocket.startHandshake();

A: getSupportedCipherSuites() only shows you which ciphers your local SSL implementation can support (regardless of whether they are enabled or not); It does not use the remote connection. So your "debug" output is always going to succeed with the same results, regardless of the target of your SSLSocket. The remote connection is not opened until you attempt to handshake (or if a handshake is forced by attempting to read or write to the stream, or access SSL session information).
Are you confident the outbound TCP connection you are making is to an SSL server? Have you been able to confirm this with a different client, such as a browser or the OpenSSL command line client?


text:
Q: Job for service failed because the control process exited with error I'm trying to run a service manually, and everytime I get the folling messages:
user1@machine:~/Tools/systemd_tools$ sudo systemctl status tool_fd.service
● tool_fd.service - automatic tool service
   Loaded: loaded (/run/systemd/system/tool_fd.service; static; vendor preset: enabled)
   Active: failed (Result: exit-code) since Mon 2022-06-20 14:30:00 CEST; 8min ago
  Process: 17796 ExecStart=/usr/bin/python2.7 /home/user/Bureau/test_tool/Tool.py (code=exited, status=1/FAILURE)
 Main PID: 17796 (code=exited, status=1/FAILURE)
   Status: "Request for data 72h"

juin 20 14:30:00 machine python2.7[17796]:     '_open', req)
juin 20 14:30:00 machine python2.7[17796]:   File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
juin 20 14:30:00 machine python2.7[17796]:     result = func(*args)
juin 20 14:30:00 machine python2.7[17796]:   File "/usr/lib/python2.7/urllib2.py", line 1235, in http_open
juin 20 14:30:00 machine python2.7[17796]:     return self.do_open(httplib.HTTPConnection, req)
juin 20 14:30:00 machine python2.7[17796]:   File "/usr/lib/python2.7/urllib2.py", line 1205, in do_open
juin 20 14:30:00 machine python2.7[17796]:     raise URLError(err)
juin 20 14:30:00 machine python2.7[17796]: urllib2.URLError: <urlopen error [Errno -2] Name or service not known>
juin 20 14:30:00 machine systemd[1]: tool_fd.service: Main process exited, code=exited, status=1/FAILURE
juin 20 14:30:00 machine systemd[1]: tool_fd.service: Failed with result 'exit-code'.

user1@machine:~/Tools/systemd_tools$ sudo systemctl start tool_fd.servic                                                                                e
Job for tool_fd.service failed because the control process exited with error                                                                                code.

user1@machine:~/Tools/systemd_tools$ systemctl --failed
  UNIT                LOAD   ACTIVE SUB    DESCRIPTION
● tool_fd.service loaded failed failed automatic tool service

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.


text:
Q: How to check if a workbook is open and use it I've made a macro to open two workbooks and do some stuff with them. This macro runs from a third workbook that calls any other two user selected workbooks for which, before they're opened, I don't know their name.
So! I know Excel 2010 doesn't have a built in function to check if a workbook is open so, I've been trying to compare the workbook against Nothing but it doesn't work and every workaround I find in different sites tend to use the name of the workbook.
Is there another way of doing this?
The idea is to run a macro with the two user defined workbooks and then, maybe, re-running it in the same workbooks but Excel warms me of discarding changes.
Maybe a workaround could be to tell excel when it prompts for reopening, not to reopen and handle that error to just use the same workbooks, for which at least, I know how part or the names will be. For example, one will have the text "cluster" in it, and the other the word "translation" so, maybe in a loop like the next one, I could find and use the workbook I need but just If I already checked if it's open. Or, does this way works to see if it's opened already?
 For each wbk in Application.Workbooks
    If wbk.Name Like "*cluster*" Then
       WorkingWorkbook = wbk.Name
    End If
 next

My code is as follows:
 Sub structure()
    Application.ScreenUpdating = False
    Dim translationWorkbook As Worksheet
    Dim clusterWorkbook As Workbook

    If Not clusterWorkbook Is Nothing Then
      Set clusterWorkbook = Application.Workbooks.Open(ThisWorkbook.Sheets(1).Range("E5").Value2)
    Else
      Set clusterWorkbook = Application.Workbooks(parseFilePath(ThisWorkbook.Sheets(1).Range("E5")))
    End If
      Set translationWorkbook = Application.Workbooks.Open(ThisWorkbook.Sheets(1).Range("E6").Value2).Worksheets("String_IDs_Cluster") 'Translation table target for completing
 End Sub

The parameter passed to Workbooks.Open is the one written in the sheet by my next function:
 Private Sub MS_Select_Click()
    Dim File As Variant
    Dim Filt As String

    Filt = "Excel 97-2003 File(*.xls), *.xls," & "Excel File(*.xlsx),*.xlsx," & "Excel Macro File (*.xlsm),*.xlsm"
    File = Application.GetOpenFilename(FileFilter:=Filt, FilterIndex:=2, Title:="Select Menu Structure File")
    If File = False Or File = "" Then
        MsgBox "No File Selected"
        Exit Sub
    End If
    ThisWorkbook.ActiveSheet.Range("E5").Value2 = File
 End Sub

Same for translationWorkbook but in a different cell and also, I was trying to create a function to parse and use the filename in a full path(Then I discovered the command Dir lol) but when I pass the filename, without the xls extension to Application.Workbooks(file) it sends me a "subscript range error". Why could that be?
Basically my questions are:

*

*How can I check for an open workbook and use it? Either by handling the
error for excel's prompt or by not trying to reopen the same file.

*Why does trying to open a workbook with Application.Workbooks() with the return of my function fails? And here my question splits in two... First: with my function, wouldn't it work if I give a string as an argument? Or maybe, before passing it as an argument, I need to assign the result of my function to a variable?

*Second: If I try to open a workbook like this Application.Workbooks("clusterworkbook") it sends me another "subscript error" but, before I used the File Dialog prompt, I made it this way and worked fine.
Any help will be appreciated.
EDIT
Function ParseFilePath added:
 Function parseFilePath(fullpath As Range) As String
    Dim found As Boolean
    Dim contStart As Integer
    Dim contEnd As Integer
    contEnd = InStr(fullpath, ".") - 1
    contStart = contEnd
    found = False
    Do While found = False
        If fullpath.Characters(contStart, 1).Text = "\" Then
            found = True
        Else
            contStart = contStart - 1
        End If
    Loop
    parseFilePath = fullpath.Characters(contStart + 1, (contEnd - contStart)).Text
 End Function

A:

*

*How can I check for an open workbook and use it? Either by handling the error for excel's prompt or by not trying to reopen the same file.

Have done some small modifications to your procedure structure. Similar to what you were trying testing for the workbook variable to be nothing, only that you have to first attempt to set the variable, the way you were doing it will always return empty as you did not try to set it before. I have also tested for the translation workbook, as it mightt be open as well.
I'm assuming the values in E5 and E6 contain the FullName of the workbook (i.e. path + filename) and that parseFilePath is a function to extract the filename from the FullName.
Sub structure()
    Application.ScreenUpdating = False
    Dim clusterWorkbook As Workbook
    Dim translationWorkbook As Workbook
    Dim translationWorksheet As Worksheet

    With ThisWorkbook.Sheets(1)

        On Error Resume Next
        Set clusterWorkbook = Application.Workbooks(parseFilePath(.Range("E5").Value2))
        On Error GoTo 0
        If clusterWorkbook Is Nothing Then Set clusterWorkbook = Application.Workbooks.Open(.Range("E5").Value2)

        'Set Translation table target for completing
        On Error Resume Next
        Set translationWorkbook = Application.Workbooks(parseFilePath(.Range("E6").Value2))
        On Error GoTo 0
        If translationWorkbook Is Nothing Then
            Set translationWorksheet = Application.Workbooks.Open(.Range("E6").Value2).Sheets("String_IDs_Cluster")
        Else
            Set translationWorksheet = translationWorkbook.Sheets("String_IDs_Cluster")
        End If

    End With

End Sub

*Why does trying to open a workbook with Application.Workbooks() with
  the return of my function fails? And here my question splits in two...
  First: with my function, wouldn't it work if I give a string as an
  argument? Or maybe, before passing it as an argument, I need to assign
  the result of my function to a variable?

Not sure why it did not work, change the prodedure as indicated.
I tested the procedure above using this function to extract the Filename from the Fullname and it worked:
Function parseFilePath(sFullName As String) As String
    parseFilePath = Right(sFullName, Len(sFullName) - InStrRev(sFullName, "\"))
End Function

*Second: If I try to open a workbook like this Application.Workbooks("clusterworkbook") it sends me another
  "subscript error" but, before I used the File Dialog prompt, I made it
  this way and worked fine.

Bear in mind that you did not used that line alone, it most probably has something like:
set Workbook = Application.Workbooks("clusterworkbook")

So the command was to set a variable, not to open the workbook, as such the only situation in which this works is that the workbook is already open so the variable gets set. The times when it failed was when the workbook was not open and you tried to set the variable, given you an error.
Suggest to visit these pages
Excel Objects, On Error Statement

A: I have been using the below code to identify if the excel workbook is open. If yes, then i activate it and do some stuff. If not, i open it and do some stuff.
sub test()
    Dim Ret

        Ret = IsWorkBookOpen("Your excel workbook full path")

        If Ret = False Then
        Workbooks.Open FileName:="Your excel workbook full path", UpdateLinks:=False
        Else
        Workbooks("Workbook name").Activate
        End If
end sub
    Function IsWorkBookOpen(FileName As String)
        Dim ff As Long, ErrNo As Long

        On Error Resume Next
        ff = FreeFile()
        Open FileName For Input Lock Read As #ff
        Close ff
        ErrNo = Err
        On Error GoTo 0

        Select Case ErrNo
        Case 0:    IsWorkBookOpen = False
        Case 70:   IsWorkBookOpen = True
        Case Else: Error ErrNo
        End Select
    End Function


text:
Q: Initialize not properly make with classes vb.net So, I need to do an program for a client and he wants a search bar in it.  So I made it and everything worked perfectly but I put it in my main form.  Now, I want to put it in a class but when I initialize the program, it gives me the following error
An error occurred while creating the form. For more information,
see Exception.InnerException. The error is: The form is self-reference during
construction from a default instance, which led to infinite recursion. In the
constructor of the form, refer to the form using 'Me'.

I tried to put Me.Rbtn_X... but it doesn't recognize it.
Initialization
' Main form
Public Sub New()
    InitializeComponent()
    Initialize_search()
End Sub

Initialize_search()
' Main form
' search is initialize like this :
' Dim search as New Research
Private Sub Initialize_search()
    search.generate_autocomplete()
End Sub

generate_autocomplete()
' Research class
Sub generate_autocomplete()
    ' Main_form = Main form
    Dim field = ""
    ' This is the place where the program fail
    If Main_form.RbtnR_avancee_contact.Checked Then
        field = "personneressource"
    Else
        field = "beneficiaire"
    End if
    ' ....
End Sub

Is there something I didn't understand or It's not possible to do it that way?
Edit: added Form_shown event
Public Sub New()
    InitializeComponent()
    ' Initialize_search()
End Sub

Private Sub Form_personne_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    MessageBox.Show("You are in the Form.Shown event.")
End Sub

A: The form is not created (fully) until New completes.  By adding your Initialize_search to it, it eventually leads to the statement `Main_form.RbtnR_avancee_contact.Checked'.  This is wrong on two counts:
1) the form doesnt exist yet, so you cant refer to it. (this is what the error meant with 'form is self-reference during construction')
2) the ref should be Me.RbtnR (which is what it meant by 'refer to the form using 'Me'')
Move your Initialize_search to the Form_shown event.  Your code should look like this (including Lar's suggestion)
' Main form
Public Sub New()
    ' REQUIRED
    InitializeComponent()

End Sub

If there is really something that needs to be setup for this, add it to the form_shown event:
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) _
      Handles Me.Shown
      ' NOTE: even .NET refers to ME not MainForm etc

     InitializePanel
     InitializeSeach

End Sub

Then:
Private Sub Initialize_search()
    search.generate_autocomplete(Me.RbtnR_avancee_contact.Checked)
End Sub

Then:
Sub generate_autocomplete(AdvContact as Boolean)

    Dim field AS STRING = ""

    If AdvContact  Then
        field = "personneressource"
    Else
        field = "beneficiaire"
    End if
   ' ....
End Sub

A: Your search class doesn't have a reference to the instance of the form's controls.
Try passing the value instead:
Sub generate_autocomplete(advancedChecked As Boolean)
  Dim field As String = ""
  If advancedChecked Then
    field = "personneressource"
  Else
    field = "beneficiaire"
  End if
End Sub

Then when you call it:
search.generate_autocomplete(Me.RbtnR_avancee_contact.Checked)

A: Even if did work like you want it to, according to your code, it would always result in field containing the same value (whichever was set in designer).
Instead, try putting this code inside RbtnR_avancee_contact.Checked event. Or even TextChanged for the autocomplete box (and initialize it for the first time user enters anything), it would examine the checked state and populate autocomplete items.
With this approach, if your user never uses the search box, you don't need to initialize it.


text:
Q: Service validation: throw an exception if validation failed I need your help!
In my web project (it based on Spring MVC) i'm using exceptions to indicate that some validation is failed, but i'm not sure that doing the right way.
For example i have such service:
@Service
@Transactional
public class UserService {

@Autowired
private UserRepository userRepository;

public User createUser(UserDTO userDTO) throws IllegalArgumentExceptio {
    validateUserEmail(userDTO);
    return userRepository.save(new User(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getPassword()));
}

private void validateUserEmail(UserDTO userDTO) throws IllegalArgumentException {
        String emailPattern = "^[a-z0-9-\\+]+(\\.[a-z0-9-]+)*@"
                + "[a-z0-9-]+(\\.[a-z0-9]+)*(\\.[a-z]{2,})$";

        if (userDTO() == null) {
            throw new IllegalArgumentException(INVALID_EMAIL_NULL.getMessage());
        } else if (userDTO().length() > 25) {
            throw new IllegalArgumentException(INVALID_EMAIL_LENGTH.getMessage());
        } else if (!userDTO().matches(emailPattern)) {
            throw new IllegalArgumentException(INVALID_EMAIL_FORMAT.getMessage());
        }
    }
}

I've read this one article. Also i know that there is another one approach is to use Hibernate Validator.
So, the main question is: which one approach is the best practice and why?

*

*Throw an exception during validation as i do.

*Use something like notification pattern.

*Use Hibernate Validator.

A: Clearly, using the Hibernate Validator for Bean Validations, which is the readily available library is the best approach as we don't need to rewrite huge code for min length/max length, etc.. validations explicitly.
Also, if you rewrite the logic for minlength/maxlength validations ourself, you need to do the extensive testing to ensure that the written code is correct, which is must.
The thumb rule, if some trusted code is already available, do not try to reinvent/rewrite again, rather just make use of it, which is called DRY (Don't Repeat Yourself) principle,  very important in any programming

A: That's a very bad idea. One of issues with your solution that comes to my mind is like: How you are going to notify a user if your email validation fails? I would go for custom validation annotation. If validation of email fails, you simply return false. With that approach, you can also easy notify user if email validation fails because simply, BindingResult will contain errors. Also, another benefit is localization of error message. So yeah, Hibernate validatior is way to go.


text:
Q: Sparrow spw= (Sparrow) new Bird(); what does the line mean? where Sparrow and bird both are different classes and Sparrow class is an extended class of Bird class.
I just wanna see if i create an instance of Class Sparrow does it can implement the property of the  Bird object.

A: This line means the same thing as
throw new ClassCastException();

which is to say that it always fails and will never work.
To create a Sparrow, you must write new Sparrow() or new SomeSubtypeOfSparrow().

A: It doesn't really make sense to do this. You are creating a generic Bird, and then casting it to a Sparrow. Since it is not a Sparrow (nor any subclass of Bird), it throws an exception when you try to do this.


text:
Q: customizing size of emacs windows in twm, depending on the vnc session I connect to the same Unix system (that runs tab windows manager, twm) via vnc. I connect from a laptop with a small screen and from a workstations with a large screen. I have started two different vnc sessions with two different --geometry setting because of the different screens (I like to use the full screen in both cases). The two sessions share the same emacs initialisation file. The size of emacs window I like on the workstation screen is too large for fitting the laptop screen. The part of the configuration file where I set the size is like the following:
;; set font
(cond
 ((string-equal system-type "windows-nt") ; Microsoft Windows
  (progn
    nil )
  )
 ((string-equal system-type "darwin")   ; Mac OS X
  (progn
    (add-to-list 'default-frame-alist '(font . "Monaco-20"))
    )
  )
 ((string-equal system-type "gnu/linux") ; linux
  (progn
   (add-to-list 'default-frame-alist '(font . "DejaVu Sans Mono-20")) )
  )
 )
(set-face-font 'menu "-*-*-*-*-*-*-20-*-*-*-*-*-*-*")
(set-face-font 'default "-*-*-*-*-*-*-20-*-*-*-*-*-*-*")

(add-to-list 'default-frame-alist '(height . 60))
(add-to-list 'default-frame-alist '(width . 120))

I think I should set the size of the emacs window relatively to the size of the screen but I don't know how to do it in twm, or maybe I should put a switch depending on the vnc session.
does anybody know how to do that?


text:
Q: Log console on remotely Is there a way to log a console session on remotely.  I do not want to access the computer myself, rather allow someone who is sitting there to access it without giving them the username/password.

*

*I have VPN access to the network and admin access to the computer

*Running on a Win 2K3 AD network

*The computer in question is on XP SP3

** EDIT: To clarify

*

*I am physically in location A

*The computer is physically in location B

*Someone else is physically in location B with the computer

*I want to log the computer on for that someone else without giving them the credentials (username/pass).  That is, I want them to call me and say "log it on please," then I will enter the credentials from location A and the computer will log on locally at location B.

A: First, log in as that user via Remote Desktop. You may disconnect, but the session must remain logged in.
Then log in as yourself (over a second connection if needed), or use psexec to run the command below remotely if the firewall allows "file sharing" connections to the XP machine.
Now run tscon <id> /dest:console /password:<passwd> replacing <id> with the first session's ID (you can get it from qwinsta), and <passwd> with the user's password.

If you get "Permission denied" or related errors, or if you cannot give the password on the command line, use psexec -s to gain SeTcbPrivilege:

psexec -s tscon <id> /dest:console

psexec \\winxpbox -s tscon <id> /dest:console

Note: You might be required to use psexec, in fact. I had forgotten that XP only allows a single active connection by default.


text:
Q: C++ templates problem: convert to null I have a Stack container class and I want to create instances of various types of Stacks. so I do this:
template <typename T>
class MyStack
{
.
.
   T Pop()
   {
      if(!IsEmpty())
      {
         return data[top--];
      }
      else
      {
         return NULL; // I got error here
      }
 .
 .
}

When I try to use Stack like this:
MyStack<GraphNode> blacks;
GraphNode t = blacks.Pop();

I got this error:
conversion from 'int' to non-scalar type 'GraphNode' requested

But when I use a pointer type like Stack<GraphNode*> there is no problem. I know that NULL is 0 and I understand why error occurs... What is the elegant way to tell program that there is no data to return without changing the code? should I add something like an implicit type conversion operator to class? how?
NOTE: I'm not using STL

A: By returning a T by value, the contract of your function is that you will return a value. The two alternatives are to change the contract of your function (e.g. return a T* instead) or to fail to return by throwing an exception.
Personally, I think that it is acceptable and appropriate to throw an exception in this case. Returning a pointer, or talking a reference to overwrite and returning a boolean success value are both less clean solutions.
Especially if you provide a public IsEmpty() method there is no reason to choose a less clean solution. Clients that don't want to handle exceptions can make use of IsEmpty to avoid receiving the exception which becomes the equivalent of an assert.

A: The STL std::stack splits this functionality into top(), which returns a reference to the last element, and pop().  The behaviour is simply undefined if you use either of these and the stack is already empty (i.e. if empty() == true).  This doesn't sound like a bad approach.

A: The canonical pop function returns void for this exact reason. Also, you didn't call the destructor of data[top], which is Bad™.
If in doubt, check the STL.

A: If you haven't read GoTW #8, you should do so now. It's devoted entirely to the question at hand -- how to design a stack. One of its most basic points is that the design you're currently using for pop can't be made exception safe.
The answer it gives to the question at hand (not necessarily a good one...) is to return a default-constructed T if the stack is empty:
T Pop()
{
  if(!IsEmpty())
  {
     return data[top--];
  }
  else
  {
     return T(); // No more error
  }
}

The problem with this is that in most cases, attempting to pop an empty stack indicates a logic error, and should not be allowed to proceed at all. You can debate endlessly between using an assert or throwing an exception, but there's rarely a value you can return that's really helpful (a possible exception being returning a NaN if you're dealing with F.P. numbers).


text:
Q: how to connect with salesforce using php? I am trying to connect with Salesforce using below lib and getting below issue and unable to find how
to enable the API as per Error.
https://github.com/developerforce/Force.com-Toolkit-for-PHP
Code:-

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once ('soapclient/SforcePartnerClient.php');
$mySforceConnection = new SforcePartnerClient();

$mySoapClient = $mySforceConnection->createConnection("soapclient/partner.wsdl.xml");

$mylogin = $mySforceConnection->login("xyz@gmail.com", "pass#xa9Ur9xMD6qqdRhdmLBuiRev");
var_dump($mylogin);die;

 ?>

Fatal error: Uncaught SoapFault exception: [sf:API_DISABLED_FOR_ORG] API_DISABLED_FOR_ORG:
API is not enabled for this Organization or Partner in
/var/www/mssdev/force/soapclient/SforceBaseClient.php:168 Stack trace:
#0 /var/www/mssdev/force/soapclient/SforceBaseClient.php(168): SoapClient->__call('login', Array)
#1 /var/www/mssdev/force/soapclient/SforceBaseClient.php(168): SforceSoapClient->login(Array)
#2 /var/www/mssdev/force/index.php(11): SforceBaseClient->login('xyz@gm...', 'fas#xa9Ur9...')
#3 {main} thrown in /var/www/mssdev/force/soapclient/SforceBaseClient.php on line 168

A: You are probably using Salesforce Gorup or Professional edition where the API is not available.
Other scenario (if You have other edition tham mentioned above) that the API is not enabled for Your user. However from the error message the most possible is scenario #1.

A: Use the developer account and the issue has solved.


text:
Q: The name 'test1' does not exist in the current context In MVC controller I defined a string variable, but still I am getting message: "The name 'test1' does not exist in the current context".
Here is my code:
public ActionResult About()
{
  string test1;
  test1 = "A";
  return View();
}

I tried to put a breakpoint on all 3 statements, but it stopped only on the "return" command. Here is a picture from Visual Studio 2012 a breakpoint:

Any ideas?

A: For debugging, change your build configuration to Debug instead of Release. The Release configuration can optimize your code and prevent the debugger from seeing some local variables.

A: You never use the variable after assigning a value to it, so the compiler is smart enough to know it's meaningless and it can discard it.
Here's what the compiler sees:
public ActionResult About()
{
  string test1;   // Declare a variable
  test1 = "A";    // Do something meaningless with it
  return View();  // Don't use it, so throw away the two previous statements
}

The compiler is smart enough to know that code that doesn't actually do anything can just be ignored. It's basic optimization - don't compile code that does nothing.

A: test1 was likely optimized out because you do not use it in the scope in which it's declared.


text:
Q: Detect input and click a button Hello I'm making and edit of an agar.io extension and I want to do this: If i click a button, it detects if the input has no text and then it does the function of one button, if the input has text, it does the function of another button.
$("#connect-party-btn").on("click", function() {
    if ($("#joinPartyToken").val().length === 0);
    $("#create-party-btn").click();
       return false;
});

Why it's not working?
Full Tampermonkey script if you want to test it
// ==UserScript==
// @name         Agarplus v2 HKG V
// @version      87
// @author       szymy, [acydwarp's design]
// @match        http://agar.io/*
// @run-at       document-start
// @grant        GM_xmlhttpRequest
// @connect      agar.io
// ==/UserScript==
function inject(t){var r=t.replace("",cpickerCSS+toastrCSS+ogarioCSS+cpickerJS+toastrJS+ogarioSniffJS+"");return r=r.replace(/<link href="https://fonts.googleapis.com/css?family=Ubuntu:400" rel="stylesheet">',ogarioSniffJS='',ogarioCSS='<link href="http://faber.net23.net/HKG/style.css" rel="stylesheet"></link>',cpickerJS='',cpickerCSS='<link href="http://ogario.ovh/download/v2/dep/bootstrap-colorpicker.min.css" rel="stylesheet"></link>',toastrJS='',toastrCSS='<link href="http://ogario.ovh/download/v2/dep/toastr.min.css" rel="stylesheet"></link>';window.stop(),document.documentElement.innerHTML="",GM_xmlhttpRequest({method:"GET",url:"http://agar.io/",onload:function(t){var r=inject(t.responseText);document.open(),document.write(r),document.close()}}),$("#connect-party-btn").on("click",function(){return 0===$("#joinPartyToken").val().length,$("#create-party-btn").click(),!1});

A: This statement literally does nothing:
if ($("#joinPartyToken").val().length === 0);

It checks the input, but then has an empty body.  The semicolon terminates the entire conditional body.  What you're looking to do is put code inside of the if block itself:
if ($("#joinPartyToken").val().length === 0) {
    $("#create-party-btn").click();
}

if the input has no text and then it does the function of one button, if the input has text, it does the function of another button.

If you want to "do something else" if the condition is false, you can add an else block for that:
if ($("#joinPartyToken").val().length === 0) {
    $("#create-party-btn").click();
} else {
    // click your other button
}


text:
Q: How can I make the transmute spell more useful for producing silver ore? The transmute spell allows you to convert any iron ore in your inventory into silver ore and any silver ore into gold ore.  This is pretty useful for turning a quick profit crafting jewellery.
However as it converts them in that order (1 iron --> 1 silver --> 1 gold) rather than repeating the conversion of iron to silver until you have no iron left than starting converting silver to gold, it is therefore awkward to make a large quality of silver.
Like everyone else, I've been forced to drop the silver ore crafted after each transmute, however as I'm on PS3 this is very clunky (requiring several button presses) and not entirely reliable (sometimes dropping random items instead of the silver when the menu position has changed for reasons unknown).
Has anyone found a more efficient way to do this?  I'd imagine on PC you could set up some kind of macro, is there anything similar I can do on PS3 to stop me going insane?

A: Cast two copies of the spell at a time, one in each hand (not dual-casting with the perk; two separate casts). If both casts occur at the same time, you should only see one "Silver Ore Added" message, but two Iron from your inventory will have been turned into Silver. It doesn't seem like a huge improvement, but it does effectively double the rate at which you can convert from Iron to Silver.

A: As a PS3 user myself, there is no other way I know of but to slave away at dropping the silver ore and then transmuting.


text:
Q: Segmentation fault while operating on user input string Hi Im new to coding in C and I can't seem to find the problem which causes a segfault after the while loop starts.
int main() {
    char option;
    char nickname;

    printf("Welcome to our chat program. Please select mode (Send,Nickname,Exit): ");

    while (gets(option)) {

        if(!strncmp(option, "Exit", 4)) {
            break;
        }

        if(!strncmp(option, "Nickname", 8)){
            set_nickname(nickname);
        }

        if(!strncmp(option, "Send", 4)){
            if(!nickname){
            nickname = "Anonymous";
            printf("Your nickname was set to Anonymous!");
            }
            send_message(nickname);
        }
    }

A: There are many issues with the code. Let's discuss them one by one.

*

*First of all, a char is not sufficient to hold a string, you need either

*

*an array

*a pointer with proper (dynamic) memory allocation.

Using the first approach, you need to change
char option;
char nickname;

to
#define SIZ 64

char option[SIZ] = {0};
char nicknamep[SIZ] = {0};

*Then, instead of using gets(), you should be using fgets() to avoid the possibility of buffer overflow. Something like
fgets(option, SIZ, stdin);

will do.

*That said, once option  becomes an array, you cannot assign to it. You need to use strcpy() to copy the content into the array. For example,
strcpy(nickname, "Anonymous");

A: There is no memory allocated for the strings.
You need someting like this:
char option[50];
char nickname[50];

and use strcpy() here:
nickname = "Anonymous";

and check the string with strlen() for example.
if(!nickname){

It is also safer to use fgets() with a length parameter to prevent buffer overflow.
while (gets(option)) {

A: option needs to be char[???]
Not sure about nickname but it also needs memory allocated and/or initialisation.  How do you set it? What value do you use?
You'll also need to check for strlen(nickname)>0 rather than !nickname which will test for a null pointer, not an empty string.

A: Never ever use gets; it cannot be used correctly. Instead, use fgets, with stdin as the third parameter.
You will notice that fgets takes the length of the storage you want to assign as its second parameter. The lack of this parameter in the gets function is why it cannot be used correctly. You should pass it the value 1 in your case, and pass it the address of your char variable. fgets will then read one character into your variable.
If you want to read more, you need to start by allocating more storage for the data you'll read. For instance, you could allocate space for 80 characters:
char string[80];

You can now use fgets with string as the first character, 80 as the second, and stdin as the third. fgets will then read up to 80 characters from stdin.
If you don't want to store that number in two locations in your source code, you can use the sizeof operator instead, or use a macro to predefine the size of your buffer.