text:
Q: Change tabbarController's tab programmatically with animation I want to change tab through code with animation. Exact scenario is that there are 2 tabs with below hierarchy.
First tab
  - Navigation controller
    - Login controller
    - Some other controller
Second tab
  - Navigation controller
    - Screen with Logout button

Now, if user presses logout, I need to display login screen. For that I need to switch tab to FirstTab and then popToRootViewController.
So what I am doing is on logout button press I send NSNotification to LoginController which in turn executes below method.
- (void)logoutButtonPressed
{
    // Go to root controller in navigation controller of first tab.
    [self.navigationController popToRootViewControllerAnimated:YES];

    // Change tab to "First tab". This happens sharply without animation.
    // I want to animate this change.
    self.tabBarController.selectedIndex = 0;
}

I tried below method to animate. But this animates only when tab is changed by user but not when changed through code.
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    NSArray *tabViewControllers = tabBarController.viewControllers;
    UIView * fromView = tabBarController.selectedViewController.view;
    UIView * toView = viewController.view;
    if (fromView == toView)
        return false;
    NSUInteger fromIndex = [tabViewControllers indexOfObject:tabBarController.selectedViewController];
    NSUInteger toIndex = [tabViewControllers indexOfObject:viewController];

    [UIView transitionFromView:fromView
                        toView:toView
                      duration:0.3
                       options: toIndex > fromIndex ? UIViewAnimationOptionTransitionFlipFromLeft : UIViewAnimationOptionTransitionFlipFromRight
                    completion:^(BOOL finished) {
                        if (finished) {
                            tabBarController.selectedIndex = toIndex;
                        }
                    }];

    return true;
}

A: Below is the code I used to animate screens with slide in-out effect. Found on SO question.
- (void)logoutButtonPressed
{
    [self.navigationController popToRootViewControllerAnimated:NO];

    [self animateTransitionBetweenControllers];
}

// Animates view transition that happens from screen with logout button to login screen
- (void)animateTransitionBetweenControllers
{
    // Get the views to animate.
    UIView * fromView = self.tabBarController.selectedViewController.view;
    UIView * toView = [[self.tabBarController.viewControllers objectAtIndex:0] view];

    // Get the size of the view.
    CGRect viewSize = fromView.frame;

    // Add the view that we want to display to superview of currently visible view.
    [fromView.superview addSubview:toView];

    // Position it off screen. We will animate it left to right slide.
    toView.frame = CGRectMake(-self.view.bounds.size.width, viewSize.origin.y, toView.bounds.size.width, viewSize.size.height);

    // Animate transition
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionTransitionNone animations:^{
        // Animate the views with slide.
        fromView.frame = CGRectMake(self.view.bounds.size.width, viewSize.origin.y, toView.bounds.size.width, viewSize.size.height);
        toView.frame = CGRectMake(0, viewSize.origin.y, toView.bounds.size.width, viewSize.size.height);
    } completion:^(BOOL finished) {
        if (finished)
        {
            // Remove the old view.
            [fromView removeFromSuperview];
            self.tabBarController.selectedIndex = 0;
        }
    }];
}

A: try this
- (void)logoutButtonPressed
{
    // Go to root controller in navigation controller of first tab.
    [self.navigationController popToRootViewControllerAnimated:YES];

    NSArray *tabViewControllers = self.tabBarController.viewControllers;

    UIView * fromView = self.tabBarController.selectedViewController.view;

    UIView * toView = self.view;

    NSUInteger fromIndex = [tabViewControllers indexOfObject:self.tabBarController.selectedViewController];

    NSUInteger toIndex = [tabViewControllers indexOfObject:self];

    [UIView transitionFromView:fromView
                        toView:toView
                      duration:0.3
                       options: toIndex > fromIndex ? UIViewAnimationOptionTransitionFlipFromLeft : UIViewAnimationOptionTransitionFlipFromRight
                    completion:^(BOOL finished) {

                            self.tabBarController.selectedIndex = 0;

                    }];

}

A: I'm Sorry Geek, I was disconnected on weekend.
The solution that I took in my app was make a method which call to the popToRootViewControllerAnimated: and then send a performSelector: message to self passing that created method as a selector:
- (void)delayPopAnimation {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

// in logoutButtonPressed make some like this
self.tabBarController.selectedIndex = 0;
[self performSelector:@selector(delayPopAnimation) withObject:nil afterDelay:1.5];

Maybe it is not the best and well performed solution, but it's an option because do the work. It will select the tab and after a 1.5 second delay, the animation will take place. Hope it helps.


text:
Q: Need help interpreting a crash log from QuincyKit I recently added QuincyKit (a crash log reporter that sits on top of PLCrashReporter) into an app and I received a crash log that I'm having trouble interpreting.
The crash log seems to be inconsistent - it says it was thread 0 that crashed, but the "Last Exception Backtrace" doesn't match with the thread 0 callstack.  The last exception points to a table method, but thread 0 callstack indicates an abort occurred during the Quincy manager initialization.
Moreover, the "Last Exception Backtrace" doesn't seem to make much sense taken on it's own - the "canEditRowAtIndexPath" method doesn't even include a call to "removeObjectAtIndex" at all (see below for the method).
Can anyone shed any light onto whether or not I should be paying attention to the "Last Exception Backtrace" or is that a red herring, and I should really be looking into why PLCrashReporter aborted during start up?
Many thanks
Crash log excerpt:
Exception Type:  SIGABRT
Exception Codes: #0 at 0x38362df0
Crashed Thread:  0

Application Specific Information:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 7 beyond bounds [0 .. 6]'

Last Exception Backtrace:
0   CoreFoundation                       0x29920fef <redacted> + 126
1   libobjc.A.dylib                      0x37d0cc8b objc_exception_throw + 38
2   CoreFoundation                       0x29833821 -[__NSArrayM removeObjectAtIndex:] + 0
3   DART                                 0x000906b3 -[DeliveryComplete tableView:canEditRowAtIndexPath:] + 262
4   UIKit                                0x2d0a3c25 -[UITableView _canEditRowAtIndexPath:] + 60
5   UIKit                                0x2d0a3a7f -[UITableView _setupCell:forEditing:atIndexPath:animated:updateSeparators:] + 130
6   UIKit                                0x2d0a1179 <redacted> + 2320
7   UIKit                                0x2cf82a31 +[UIView performWithoutAnimation:] + 72
8   UIKit                                0x2d0a0861 -[UITableView _configureCellForDisplay:forIndexPath:] + 336
9   UIKit                                0x2d246383 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 498
10  UIKit                                0x2d24642f -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 54
11  UIKit                                0x2d23b013 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2258
12  UIKit                                0x2d049657 -[UITableView layoutSubviews] + 186
13  UIKit                                0x2cf73023 -[UIView layoutSublayersOfLayer:] + 546
14  QuartzCore                           0x2c993d99 -[CALayer layoutSublayers] + 128
15  QuartzCore                           0x2c98f5cd <redacted> + 360
16  QuartzCore                           0x2c98f455 <redacted> + 16
17  QuartzCore                           0x2c98edf1 <redacted> + 224
18  QuartzCore                           0x2c98ebdf <redacted> + 434
19  UIKit                                0x2cf6b23b <redacted> + 126
20  CoreFoundation                       0x298e6fed <redacted> + 20
21  CoreFoundation                       0x298e46ab <redacted> + 278
22  CoreFoundation                       0x298e4ab3 <redacted> + 914
23  CoreFoundation                       0x29831201 CFRunLoopRunSpecific + 476
24  CoreFoundation                       0x29831013 CFRunLoopRunInMode + 106
25  GraphicsServices                     0x3100d201 GSEventRunModal + 136
26  UIKit                                0x2cfd5a59 UIApplicationMain + 1440
27  DART                                 0x00015491 _mh_execute_header + 25745
28  libdyld.dylib                        0x38298aaf <redacted> + 2

Thread 0 Crashed:
0   libsystem_kernel.dylib               0x38362df0 __pthread_kill + 8
1   libsystem_c.dylib                    0x382fe909 abort + 76
2   DART                                 0x00122dd7 -[PLCrashReporter enableCrashReporterAndReturnError:] + 1294
3   CoreFoundation                       0x2992131f <redacted> + 630
4   libobjc.A.dylib                      0x37d0cf13 <redacted> + 174
5   libc++abi.dylib                      0x37643de3 <redacted> + 78
6   libc++abi.dylib                      0x376438af __cxa_rethrow + 102
7   libobjc.A.dylib                      0x37d0cdd3 objc_exception_rethrow + 42
8   CoreFoundation                       0x2983129d CFRunLoopRunSpecific + 632
9   CoreFoundation                       0x29831013 CFRunLoopRunInMode + 106
10  GraphicsServices                     0x3100d201 GSEventRunModal + 136
11  UIKit                                0x2cfd5a59 UIApplicationMain + 1440
12  DART                                 0x00015491 _mh_execute_header + 25745
13  libdyld.dylib                        0x38298aaf <redacted> + 2

"canEditRowAtIndexPath" method:
-(BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == SIGNER_TABLE_TAG_VALUE)
    {

        RouteStopData *currentStop = [CurrentRoute singleton].selectedStop;
        NSArray *signers = [currentStop signerNamesForStop];

        if (indexPath.row >= [signers count])
        {
            return NO;
        }

        if ([[signers objectAtIndex:indexPath.row] isEqualToString:DARK_DROP_SIGNER_STRING] ||
            [[signers objectAtIndex:indexPath.row] isEqualToString:PAPER_INVOICE_SIGNER_STRING] ||
            [[signers objectAtIndex:indexPath.row] isEqualToString:ADD_NEW_SIGNER_STRING]
            )
        {
            return NO;
        }

        return YES;
    }

    return NO;
}

A: If you are using ios7, it's maybe UIKit's fault.
Tableview  would like to call delegate method before dealloc.
So you can add this code in your Custom class:
- (void )dealloc{
    self.tableView.dataSource = nil;
   self.tableView.delegate  = nil;
}

See more in iOS 7 bug or my bug in UIAlertView

redpajama_set_name: RedPajamaStackExchange


text:
Q: Including diverse unicode symbols inside LaTeX document I write LaTeX on a Ubuntu Linux system using emacs.  I have a LaTeX document where I would like to have some characters from other various numeral systems (cuneiform, hieroglyphic, Chinese, and others, see numeral systems).  Most of my document is English in a default LaTeX font and math typeset as usual in LaTeX.  Initial research has suggested that XeLaTeX might be better than pdfLaTeX. Many of the answers I have found are for including just one family of unicode characters (just cuneiform or just hieroglyphics).  They often suggested installing new fonts which I do not know how to do.  Many of these answers also suggest setting the main font to be one which includes the desired unicode characters.  Since I would like a diverse range of characters and I do not want to change the font for the main body of my text, how do I accomplish this?

A: With xelatex and ucharclasses one can set what fonts to use and when.
% !TeX program = xelatex
% !TeX encoding = UTF-8 Unicode
\documentclass[xetex,a4paper]{article}
\usepackage{fontspec}
\setmainfont[Ligatures=TeX]{Symbola}
\newfontfamily{\defaultfont}{Symbola}
\newfontfamily{\Egyptfont}{Noto Sans Egyptian Hieroglyphs}
\newfontfamily{\Cuneifont}{Noto Sans Cuneiform}
\newfontfamily{\cjkfont}{Noto Sans CJK TC}
\usepackage{polyglossia}
\setdefaultlanguage[variant=british]{english}
\usepackage[Latin, CJK, EgyptianHieroglyphs, NumberForms]{ucharclasses}
\setDefaultTransitions{\defaultfont}{}
\setTransitionsFor{NumberForms}{\defaultfont}{}
\setTransitionsFor{Cuneiform}{\Cuneifont}{\defaultfont}
\setTransitionsFor{EgyptianHieroglyphs}{\Egyptfont}{\defaultfont}
\setTransitionsForCJK{\cjkfont}{\defaultfont}
\usepackage{unicode-math}
\setmathfont[Ligatures=TeX]{STIX Two Math}

\begin{document}

東南西北零一二三四五六七八九十百千萬億

ō α β γ δ ε ϝ ζ η θ ι

{\Cuneifont }

{\fontspec{STIX Two Text}0123456789 ₀₁₂₃₄₅₆₇₈₉}

\end{document}

Link to fonts:
symbola,
Noto Egyptian,
Noto Cunei,
Han Sans

A: XeTeX is not the only option. You may use also LuaTeX, which provides some additional and useful features. With babel you can switch the fonts based on the Unicode ranges, as the following example shows. You need also some fonts with the required characters, and a complete solution is Noto.
\documentclass{article}

\usepackage[english]{babel}

% Declare the locales:
\babelprovide[onchar=fonts]{chinese}
\babelprovide[onchar=fonts]{hieroglyphic}
\babelprovide[onchar=fonts]{cuneiform}

% Declare the fonts:
\babelfont{rm}{FreeSerif}
\babelfont[chinese]{rm}{FandolSong}
\babelfont[hieroglyphic]{rm}{NotoSansEgyptianHieroglyphs-Regular.ttf}
\babelfont[cuneiform]{rm}{NotoSansCuneiform-Regular.ttf}

% The Chinese range is predefined by babel, but not the
% following:
\babelcharproperty{"13000}["1342F]{locale}{hieroglyphic}
\babelcharproperty{"12000}["12474]{locale}{cuneiform}

\begin{document}

Text  text  text 一二三四五.

\end{document}


text:
Q: Replacing logback.xml file directory I am using gradle build tool and standard logback.xml file. Now I want to move logback.xml file to different directory like 'src/main/dist/conf' and let slf4j to use this path instead of default one which is 'src/main/resources'.
Is there any opinion how to do that?

A: It may help someone who may struggle with the same issue.
I overcome this by setting JAVA_OPTS as "-Dlogback.configurationFile=/path/to/config.xml".
Much more useful informations can be found here: http://logback.qos.ch/manual/configuration.html


text:
Q: wso2 esb iterate mediator thread safe? I have below iterate Seq,
  <iterate attachPath="//Test"
    expression="///Test" preservePayload="true">
    <target>
      <sequence>
       <header name="Action" scope="default" value="action1"/>
       <send>endpoint 1</send>
      </sequence>
    </target>
    <target>
      <sequence>
       <header name="Action" scope="default" value="action2"/>
       <send>endpoint 2</send>
      </sequence>
    </target>
  </iterate>

so does the "Action" is thread safe in each iterate target\seq.
if so, in"aggregate", can i access the property/header inside the target\seq?

A: I am not sure whether its thread safe. But to workaround your doubt, I think the following information would help.
There is a property called "Sequential Mediation" in the iterate mediator. If it is set to true, it will process the iterated messaged sequentially. See the following documentation.
https://docs.wso2.com/display/ESB490/Iterate+Mediator


text:
Q: FAILED: Error in metadata: when i am trying to show tables from hive databases the following error displays..
i granted permissions to ware house & Tables even though the error shows
hive> show tables;
FAILED: Error in metadata: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.metastore.HiveMetaStoreClient
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask
Thanks in advance.

A: this error occurs when hive CLI is terminated improperly.
solution:
exit from hive,  give  'jps' command. some  process named runjar will be there.  kill it using ' kill -9 pid'
thats it. you are done.
plz ignore typo- replied from mobile


text:
Q: Using IF statements to reduce no of Loop iterations variable 'size' is the size of the larger list.
for(int x = 0; x < size; x++){

if(employees!= null && employees.size() > x){
//do something
}

if(consultants!= null && consultants.size() > x){
// do something
}

Then i have another way of doing it
for(Object obj : employees){
//do something
}

for(Object obj : consultants){
//do something
}

The second approach seems simpler to me,  but the first approach would result in lower loop iterations. anyways, i would like to know which would be better in a general situation.

A: You should choose the version that's easier to understand - the second one. There won't be much difference in terms of performance, and you shouldn't try to optimize your code unless you really have to.


text:
Q: How to checkbox unchecked without action followed by checking? I want to ask how to unchceck checkbox without action followed by checking checkbox*(i.e. w/o triggering the onCheckChangedListener())*?
I have oncheck action, but i want to disable this action for unchecking. Is it possible ?
Here is my code:
 chb_czy_zamowic.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(
                        final CompoundButton buttonView, boolean isChecked) {
                    // TODO Auto-generated method stub
                    final Dialog d1 = new Dialog(context);
                    d1.setContentView(R.layout.ilosc);
                    d1.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                    d1.setTitle("Wybierz ilość");

                    final EditText et_Ilosc;
                    Button b_Ok;
                    Button b_Odejmij;
                    Button b_Dodaj;

                    if (buttonView.isChecked()) {

                        et_Ilosc = (EditText) d1
                                .findViewById(R.id.et_Ilosc);

                        et_Ilosc.setText(String.valueOf(i));

                        b_Dodaj = (Button) d1.findViewById(R.id.b_Dodaj);
                        b_Dodaj.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                String zmienna_pom = et_Ilosc.getText()
                                        .toString();
                                i = Integer.valueOf(zmienna_pom);
                                setI(i);
                                int k = getI();
                                k++;

                                setI(k);
                                et_Ilosc.setText(String.valueOf(i));

                            }
                        });
                        b_Odejmij = (Button) d1
                                .findViewById(R.id.b_Odejmij);
                        b_Odejmij.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                String zmienna_pom = et_Ilosc.getText()
                                        .toString();
                                i = Integer.valueOf(zmienna_pom);
                                setI(i);
                                i--;
                                setI(i);
                                et_Ilosc.setText(String.valueOf(i));

                            }
                        });
                        b_Ok = (Button) d1.findViewById(R.id.b_Ok);
                        b_Ok.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String zmiennna_pom = et_Ilosc.getText()
                                        .toString();
                                int k = Integer.valueOf(zmiennna_pom);

                                if (k<=0 || k>=100) {

                                                                Toast t = Toast.makeText(getContext(),
                                            "Niepoprawna wartość" ,
                                            Toast.LENGTH_SHORT);
                                    t.show();
                                    view.chb_czy_zamowic.setChecked(false);
                                    d1.cancel();
                                }
                                else if( et_Ilosc.getText().toString().equals(""))
                                {
                                    Toast t = Toast.makeText(getContext(),
                                            "Uzupełnij pole ilość" ,
                                            Toast.LENGTH_SHORT);
                                    t.show();
                                    view.chb_czy_zamowic.setChecked(false);
                                    d1.cancel();
                                }
                                else
                                    view.chb_czy_zamowic.setEnabled(false);
                                    view.chb_czy_zamowic.setChecked(false);

                                    items.get(position).Tow_ilosc -= k;
                                    Towar checkedObject = new Towar();
                                    checkedObject.Tow_ilosc = k;
                                    checkedObject.Kat_id = items
                                            .get(position).Kat_id;
                                    checkedObject.kategoria = items
                                            .get(position).kategoria;
                                    checkedObject.Tow_cena = items
                                            .get(position).Tow_cena;
                                    checkedObject.Tow_id = items
                                            .get(position).Tow_id;
                                    checkedObject.Tow_nazwa = items
                                            .get(position).Tow_nazwa;
                                    MainActivity.lista_wybranych_towarow
                                            .add(checkedObject);
                                    k = 0;
                                    setI(0);
                                    // et_Ilosc.setText("");
                                    if (MainActivity.lista_wybranych_towarow
                                            .size() > 0) {
                                        b_zatwierdz
                                                .setVisibility(View.VISIBLE);

                                        TowarZamowienie.towary_zamowione = new ArrayList<Towar>(MainActivity.lista_wybranych_towarow);

                                        Collections
                                                .copy(TowarZamowienie.towary_zamowione,
                                                        MainActivity.lista_wybranych_towarow);

                                    } else {
                                        Toast t = Toast.makeText(
                                                getContext(),
                                                "Proszę wybrać ilość",
                                                Toast.LENGTH_LONG);
                                        t.show();
                                    }

                                d1.dismiss();

                            }
                        });

                    }
                    ;
                    d1.show();

                }

            });

A: Theres a property, setClickable associated with views which I believe can be used. In the onCheckedChangeListener, see when it gets unchecked and then set this to false. Hope this does the trick for you.

A: Define some boolean field that you could set to true when your are tweaking the check states manually and false when you are not and expecting the user input instead. Now the listener can check the value of this field and ignore "software triggered checks" when the flag is true. The optimal location of the flag (method field, static field, etc) depends on the overall program design.
Be sure your code always sets this flag back to false when you finish tweaking the check boxes manually, so not to stay in the permanently locked state. This is one of the cases when finally statement may be appropriate.
If you only check the boxes programmatically on initialization, such cluttering may be avoided by setting the listeners only after the states are set.


text:
Q: when spawning threads, how do I throttle the maximum number possible? How do I spawn threads to the maximum number possible assuming that each thread may take different time to complete. The idea is to spawn the maximum number of threads possible while not causing any to die.
E.g. While (spawnable) spawn more threads;
I am trying to spawn threads to make calls to ejb, I wish to spawn the maximum number possible to simulate a load while not causing the threads to go into out of memory exception.

A: Executors.newFixedThreadPool() or for finer control, create your own ThreadPoolExecutor.

A: There is no fixed answer. You need to tune the number of threads to your host capabilities.
In response to the memory issue, it is not only a matter of how many threads are there but also of what they do. It is not the same if they perform simple calls or have to deal with huge arrays.
Relative for performance, and supposing that your host is dedicated, a value of one thread per core is a minimum value. Given that they are going to call a remote system most of these threads will spend a time idle; depending of the proportion of idle time you can spawn more or less.
In essence, chech your host performance and tune your thread number in consequence.

A: The Executor framework has been cited here, and it's a wonderful tool indeed (Already +1'ed that answer).
But I believe what the OP wants is a Executors.newCachedThreadPool().
From the docs:

Creates a thread pool that creates new threads as needed, but will
  reuse previously constructed threads when they are available

More on executors here


text:
Q: Socket.BeginSendTo and Socket.BeginReceiveFrom is not sending or receiving the data I am trying to make a dedicated server for my new game using UDP sockets. I am using Socket.BeginSendTo() and Socket.BeginReceiveFrom() methods in order to send my data.
I am receiving the callbacks from both the methods, but when I am trying to Encoding.ASCII.GetString(buffer) it is not showing me any strings. I am not sure if there is a problem while sending, or if there is a problem while receiving.
I know that UDP does not guarantee the transmission, that's why I tried to send my data more then twice more like 10 times. Each time, I receive a callback that the data is sent on the client side and the data is received on the server side. But, as I said, when I am trying to read the data using Encoding, it shows nothing. I tried to do a string null or empty check while receiving the data. It said that the string is not empty, but when I try to Console.WriteLine(), it showed nothing in the console.
Here is the client code, where I am sending the data to the server:
public void SendMessage(Activity activityCode, String inputedString) //I am changed this
{
    byte[] data = readMessage.WriteData(activityCode, inputedString);
    if(data != null)
    {
        Debug.Log(data.Length); //this returned 11
        clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, serverEndpoint, new AsyncCallback(OnSend), null);
    }

    Array.Clear(readMessage.data, 0, readMessage.data.Length);
}

private void OnSend(IAsyncResult ar)
{
    Debug.Log("sent"); //I am getting this callback in my console
}

Here is my server code, where I am receiving the data:
private void StartReceiveingData()
{
    try
    {
        if (!serverSocket.IsBound)
        {
            serverSocket.Bind(localServerIPEndPoint);
        }

        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        //The epSender identifies the incoming clients
        EndPoint epSender = (EndPoint)ipeSender;

        serverSocket.BeginReceiveFrom(StaticTest.byteData, 0, StaticTest.byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

private void OnReceive(IAsyncResult ar)
{
    StaticTest.printDData();
    IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint epSender = (EndPoint)ipeSender;
    serverSocket.EndReceiveFrom(ar, ref epSender);

    StartReceiveingData();
}

And here is where I am reading the data:
static public class StaticTest
{
    static public byte[] byteData = new byte[1024];

    public static void printDData()
    {
        Console.WriteLine("Reding the received data" + Encoding.UTF8.GetString(byteData));
    }
}

UPDATE: I tried this code, but it still does not work:
private void StartReceiveingData()
{
    try
    {
        if (!serverSocket.IsBound)
        {
            serverSocket.Bind(localServerIPEndPoint);
        }

        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        //The epSender identifies the incoming clients
        EndPoint epSender = (EndPoint)ipeSender;

        serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

private void OnReceive(IAsyncResult ar)
{
    IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint epSender = (EndPoint)ipeSender;
    int numData = serverSocket.EndReceiveFrom(ar, ref epSender);

    if (!clientList.ContainsKey(epSender))
    {
        Client client = new Client(epSender);
        clientList.Add(epSender, client);
    }
    if(clientList.TryGetValue(epSender, out Client client1))
    {
        string _receivedData = Encoding.UTF8.GetString(byteData, 0, numData);
        Console.WriteLine(_receivedData + " Data that came");
        //client1.RecieveDataFromMyGameObject(_receivedData);
    }

    StartReceiveingData();
}

And here is where I am reading the data:
public string TakeActions(string _recivedData)
{
    int activityInput = Convert.ToInt32(_recivedData.Substring(0,1)); //there is an error
    ActivityRequest activity = (ActivityRequest)activityInput;
    Console.WriteLine("Current activity Number : " + activity);

    if(activity == ActivityRequest.SetupClient)
    {
        SetupClientDataActivity.setupClientData(client,_recivedData.Substring(1,_recivedData.Length-1));
    }
    else if(activity == ActivityRequest.MatchMaking)
    {
        Console.WriteLine("Asking Room manager to get into a room");
        // roomManager.AddAClientToARoom(client);
    }

    return null;
}

A: Your OnSend callback needs to call Socket.EndSendTo() to finish the send operation and tell you whether the operation was successful or not.
Your OnReceive callback is calling Socket.EndReceiveFrom(), but you are ignoring its result, and you are trying to print the byteData before calling EndReceiveFrom() to finish the read operation and tell you how many bytes were actually written into byteData.
Try this instead:
public void SendMessage(Activity activityCode, String inputedString)
{
    byte[] data = readMessage.WriteData(activityCode, inputedString);
    if (data != null)
    {
        Debug.Log($"sending {data.Length} bytes");

        try
        {
            clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, serverEndpoint, new AsyncCallback(OnSend), null);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    Array.Clear(readMessage.data, 0, readMessage.data.Length);
}

private void OnSend(IAsyncResult ar)
{
    try
    {
        int numBytes = clientSocket.EndSendTo(ar);
        Debug.Log($"sent {numBytes} bytes");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

private void StartReceiveingData()
{
    try
    {
        if (!serverSocket.IsBound)
        {
            serverSocket.Bind(localServerIPEndPoint);
        }

        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        EndPoint epSender = (EndPoint)ipeSender;

        serverSocket.BeginReceiveFrom(StaticTest.byteData, 0, StaticTest.byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

private void OnReceive(IAsyncResult ar)
{
    try
    {
        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        EndPoint epSender = (EndPoint)ipeSender;
        int numBytes = serverSocket.EndReceiveFrom(ar, ref epSender);

        StaticTest.printDData(numBytes);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }

    StartReceiveingData();
}

static public class StaticTest
{
    static public byte[] byteData = new byte[1024];

    public static void printDData(int numBytes)
    {
        Console.WriteLine("Received data: {0}", Encoding.UTF8.GetString(byteData, 0, numBytes));
    }
}


text:
Q: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection This is not making any sense. The query i'm running is shown below. The result of the query is data-bound to a form.
    public Message GetMessage(Guid authorizationKey)
    {
        using (MyEntities context = new MyEntities())
        {
            var result = (from message in context.Messages
                              .Include("Attachments")
                              .Include("Authentication")
                          join authentication in context.Authentications on message.Authentication.AuthenticationId equals authentication.AuthenticationId
                          where authentication.AuthorizationKey == authorizationKey
                          select message).FirstOrDefault();

            return result;
        }
    }

The weird shit: If i put a break-point, step through the query and data-bind everything works. Soon as i remove the breakpoint my Authentication nav property isn't loaded. Can somebody shed some light on why this is occurring?

A: Include and Select do not work together.
You are telling the DataContext to return the message variable that only contains the message (even though you have the include statements on the context.Messages object). Two ways to fix this would be:
1) Project message, Attachments, Authentication into a POCO object in your select statement
        var result = (from message in context.Messages
                          .Include("Attachments")
                          .Include("Authentication")
                      join authentication in context.Authentications on message.Authentication.AuthenticationId equals authentication.AuthenticationId
                      where authentication.AuthorizationKey == authorizationKey
                      select new MessageWithNavigations()
{
Message = message,
Authentication = message.Authentication,
Attachments = message.Attachments,
}).FirstOrDefault();

        return result;

2) Use the fluent notation across the whole queryable
var result = context.Messages
    .Include("Attachments")
    .Include("Authentication")
    .Where(m => m.Authentication.AuthorizationKey == authorizationKey)
    .FirstOrDefault();

The problem with #1 is that you will not be able to do anything with the instances of the object that would fire a query off (like a navigation), or edit any properties on those objects. Projection only gives you essentially read-only objects.
With #2, it might be better to use .SingleOrDefault instead of FirstOrDefault if your AuthorizationKey is a unique value / primary key.
The gist of the problem is that using include with select in the same IQueryable object essentially confuses the query builder expression tree and it chooses to ignore your include statements.


text:
Q: JQuery cut an image w/o cropping plugin I am trying to show just a part of an image with JQuery, for example, from 0 - 200 px of it's width.
I have already solved this problem, so...

*

*I want to know if there's an easier way, instead of creating a div for each image and using the script each time.

*A way of animating it, from right to left, instead of left to right.

This is my script, any suggestion?
$("button").click(function(){
    if($('#hello2').css("opacity") != "0"){
        $('#hello2').animate({
            "width" : "0px",
            "opacity" : "0"
        });
    }
    else{
        $('#hello2').animate({
            "opacity" : "1",
            "width" : "500px"
        });
    }
});

Fiddle
Thanks in advice

A: I changed it to use the background:url() property instead of a separate div, the effect looks a little different though.
but  at least now all you have to do is animate the width of the div.
$(document).ready(function () {
    $("button").click(function () {
        if ($('#img').css("width") == "100px") {
            $('#img').animate({
                "width": "300px"
            }, 'slow');
        } else {
            $('#img').animate({
                    "width": "100px"
            }, 'slow');
        }
    });
});

updated fiddle
I didn't find a 'right to left' animation :(

A: You are making it way too complicated. Just control the size of the container and it is done!
function crop(ele, x1, y1, x2, y2){
   ele.animate({
        width: x2 - x1, height: y2 - y1
   }).find(">img").animate({
        top: -x1, left: -y1
   });
}

http://jsfiddle.net/DerekL/CLFTe/


text:
Q: Was my login account hacked on login.ubuntu.com due to the forums security breach? I was using my https://login.ubuntu.com/ account to connect to http://ubuntuforums.org  which has been corrupted. I've used it also for other services u1, launchpad, etc. After the recent attack, should I consider all my accounts on these sites to be corrupted?

A: No. Your Ubuntu SSO account should be fine, as well as any accounts other than Ubuntu Forums on which you used it.
Ubuntu Single Sign On was not compromised in the attack on Ubuntu Forums. Fortunately, no Ubuntu services other than Ubuntu Forums were affected. This is according to the information page up at the Ubuntu Forums maintenance announcement page, which should be reliable since that domain is no longer controlled by the crackers who perpetrated the attack, nor by the system they compromised. Provided that you never created a separate account on Ubuntu Forums, you should be fine.
However, if you did ever have an account on Ubuntu Forums, and you use the same password on Ubuntu SSO (or any other site, Ubuntu-related or not), then you should make sure to change your password and stop using that password.


text:
Q: Investigate methods for analog Input Overvoltage fault protection I have 8 analog input coming from various 5v and 3.3v sensors that have to be interfaced to a 3.3v micro-controller. The main system voltage is 24v-48v , i need to protect the ADC inputs against over-voltage from misuse , not ESD events. So if by mistake the 48v is connected instead of the sensor.
after looking into the following threads :
How would I design a protection clipper circuit for ADC input?
ADC over-voltage input protection while keeping accuracy
i tried the following :

*

*Approach 1: Resistor and Zener
This approach is fine on digital pins but confirmed what people said in the posts about voltage drop and ADC error. I heard that using a shunt regulator like the TL431 instead could help but haven't tried it!?

*

*Approach 2: Series Resistor and External clipping diodes
The approach works fine it have tries BAS70,BAT54 and similar , in order to get lower drop i have found that using power (1A) schottky is better because they have much lower voltage drop at 1-25mA .

*

*Approach 3: OPAMP, Resistor and diode
this approach i have found is not very common , and work fairly well , similar to approach 2 but more complicated.

*

*Approach 4: Unity Gain opamp with internal Clamp
Texas instruments have a product for this role exclusively.
OP698
BUT: this lowest single supply is 5v not 3.3v , and the maximum clamping voltage is lower than the rail . and it does not tell how much is the maximum input voltage. and it takes PCB space , 4 resistors and 1 SO-08 IC per input.
Question :
At this point of search i got a bit frustrated and i think now that Approach 2 is the best in terms of robustness and space, please help and state any other approach i am missing ??
I am also interested in exotic solutions similar to automotive Input/ Output ICs that have multiple inputs and protection built in to interface the processors to harsh environment. similar to this MAX6816 used for digital signals.


text:
Q: Prevent highlight outside wrapper how do i prevent user try highlighting a text and prevent mouse goes outside the <div> wrapper?
<div id="wrapper">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.
</div>

$(function(){
  $('#wrapper').on('mousedown', function(){
    // prevent mouse goes outside the wrapper box, all only highlight inside the wrapper
  });
});


text:
Q: Remove duplicate records of two column of same table sql I have a table as shown below :

ID    OrderId   IssueId EmployeeId
1      123        123    12098
2      124        123    12098
3      125        123    12098
4      123        124    12098
5      124        124    12098
6      125        124    12098
7      123        126    12098
8      124        126    12098
9      125        126    12098

where against each OrderId there is record inserted for IssueId. Now i want to filter that which IssueId is not matching the OrderId.
i.e Above sample data orderId 125, but issueId 126. I need to filter only this data from the table.
I'm using following query
Select OrderId,IssueId,EmployeeId from IssuesTable where OrderId != IssueId
i'm getting the following result.

OrderId   IssueId EmployeeId
123        126    12098
124        126    12098
125        126    12098

Since each order id has got an issueId i'm getting 3rows for missing issueId.
can anyone help me on this issue. ??

A: Try this query:
SELECT *
FROM <table>
WHERE OrderId = IssueId

Here is a sample SQLFiddle showing how only the rows with the same OrderId and IssueId are being returned.

A: If you want to find the orderid which doesnot match with Issueid in any row then try this
select orderid
from yourtable
group by orderid
having count(case when orderid = IssueId then 1 end) = 0

If you want to select the IssueId along with OrderId then use this
SELECT OrderId,IssueId
FROM   Yourtable A
WHERE  EXISTS (SELECT 1
               FROM   Yourtable B
               WHERE  a.orderid = b.orderid
               GROUP  BY orderid
               HAVING Count(CASE WHEN orderid = issueid THEN 1 END) = 0)


text:
Q: Integral using long division I have the integral
$$\int\frac{x^2+1}{6x-9x^2}\,\mathrm{d}x$$
$$\rightarrow \left(-9x^2+6x\right):\left(1+x^2\right)\ $$
$$+9x^2+0x+9$$
$$\rightarrow6x+9$$
Im tumped here, because I dont know how to continue with the longdivision to get rid of the 'x'-part. It's not like I can multiply $(1+x^2)$ with a square root, or can I (?), if so, how?

A: $$\frac{x^2+1}{6x-9x^2}=-\frac{x^2+1}{9x^2-6x}=-\frac19\frac{9x^2+9}{9x^2-6x}=-\frac19\left(1+\frac{9+6x}{9x^2-6x}\right)$$
$$=-\frac19-\frac19\frac{3+2x}{3x^2-2x}=-\frac19-\frac{(3+2x)}{9x(3x-2)}$$
can you finish it from here?


text:
Q: (hibernate4) org.hibernate.MappingException: Unknown entity I am a newbie to Java EE, please help!
The following code used struts2+hibernate4+oracle11g. After I run this code, it gives me this error message:

org.hibernate.MappingException: Unknown entity

UserDetails.java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

@Entity
@Table(name="users")
public class UserDetails {
    @Id
    private int id;
    private String passwd;
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public void Update(){
        SessionFactory sessionFactory;
        ServiceRegistry serviceRegistry;

        Configuration configuration = new Configuration();
        configuration.configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(this);
        session.getTransaction().commit();
    }
}

hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

  <session-factory>

    <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
    <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="connection.url">jdbc:oracle:thin:@192.168.1.2:1521:orcl</property>
    <property name="connection.username">steve</property>
    <property name="connection.password">steve</property>

    <property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>

    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    <property name="current_session_context_class">thread</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hbm2ddl.auto">create</property>
  </session-factory>

</hibernate-configuration>

Table Structure:
Create table Users (ID int primary key, passwd varchar(45));

A: You need to add the class:
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

@Entity
@Table(name="users")
public class UserDetails {
    @Id
    private int id;
    private String passwd;
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public void Update(){
        SessionFactory sessionFactory;
        ServiceRegistry serviceRegistry;

        Configuration configuration = new Configuration();
        configuration.addAnnotatedClass(UserDetails.class); //<-- Here, adds the class to the Hibernate configuration
        configuration.configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(this);
        session.getTransaction().commit();
    }
}

You definitely do not want to construct a new Hibernate Configuration and SessionFactory each time you want to save something to the table, so move the stuff from Update to an init method somewhere.

A: The problem is that you haven't defined your class to hiberante.
Inside your session-factory add these lines:
<property name="annotatedClasses">
    <list>
        <value>myPackage.UserDetails</value>
    </list>
</property>

A: Hibernate mapping for entity is missing. Alternatively you can use  in your hibernate configuration file.
and define the UserDetails.hbm.xml. I hope this will be helpfull.


text:
Q: the JAR file tomcat-apr-5.5.23.jar has no source attachment OBJECTIVE :
There's an issue I am trying to get through. I have made use of the "tomcat-apr" library in my JAVA program. The build-path for the library is properly configured and class files in this apr project are detectable by the java classes that I have used.
Situation :
Now when I try to compile that .java file that uses this apr library generates an exception named :

Exception in thread "main" java.lang.UnsatisfiedLinkError:
  org.apache.tomcat.jni.Time.now()J     at
  org.apache.tomcat.jni.Time.now(Native Method)     at
  com.nxLog.NxLog_t.nxlog_init(NxLog_t.java:88)     at
  com.mainws.MainWs.main(MainWs.java:35)

Now when I click on the at "native method"

org.apache.tomcat.jni.Time.now(Native Method)

It shows me that the JAR file tomcat-apr-5.5.23.jar has no source attachment. I don't understand when I have the jar file properly build to my project, why this error persists(Expecting this to be a problem related to the jar file configuration...)
Help would be appreciated!!!!


text:
Q: How to format a page using a command? What im going to ask isnt a big deal, i want to know if i can format an html page before the server sends it to the client. here is an example, this is the source code of an aspx page:

שאלות על HTML

בפורום הזה תוכלו לשאול שאלות על HTML

	1	All

שאלות על C#

בפורום הזה תוכלו לשאול שאלות על C#

	1	All

שאלות על ASPX

בפורום הזה תוכלו לשאול שאלות על ASPX

	1	All

דיבורים

פורום דיבורים

	1	All

פורום אדמין

לאדמינים בלבד

	2	Admin

(Ignore the hebrew text), thats how it shows it, but i want it to look that way:

שאלות על HTML

בפורום הזה תוכלו לשאול שאלות על HTML

	1	All

שאלות על C#

בפורום הזה תוכלו לשאול שאלות על C#

	1	All

שאלות על ASPX

בפורום הזה תוכלו לשאול שאלות על ASPX

	1	All

דיבורים

פורום דיבורים

	1	All

פורום אדמין

לאדמינים בלבד

	2	Admin

Its just a  matter of aesthetics and nothing seruios, it looks exactly the same in the browser. is there any kind of command or something that i can put at the end of the document that will format the page before sending it to the client?
(im using C# and asp.net) Thank you! :)

A: You will need to have the aesthetics on the server side too i.e. Edit > Advanced > Format Document
If you are generating this code dynamically, you could look to use the HtmlTextWriter https://msdn.microsoft.com/en-us/library/system.web.ui.htmltextwriter%28v=vs.110%29.aspx


text:
Q: Color table column on input focus I have a table with an <input> in each , I want all of the column s to get the class .highlighted when you are focused on a <input>. And to remove the class from all the other columns and s.
http://jsfiddle.net/amitkeren/c6gbp5kh/

A: fiddle not working so i'll just type it here.

but here you go


text:
Q: Composition of iPhone Accelerometer Values I am receiving accelerometer values with an update interval of 1 second, using the startAccelerometerUpdates() method of CMMotionManager. Does anyone know if the values I get back are the actual values of the time the update takes place or sth. like a mean/min/max value of the time within the update interval?

A: According to the documentation, the values you see are instantaneous values.
https://developer.apple.com/documentation/coremotion/cmmotionmanager


text:
Q: @OneToMany association joining on the wrong field I have 2 tables, devices which contains a list of devices and dev_tags, which contains a list of asset tags for these devices.  The tables join on dev_serial_num, which is the primary key of neither table.  The devices are unique on their ip_address field and they have a primary key identified by dev_id.  The devices "age out" after 2 weeks.  Therefore, the same piece of hardware can show up more than once in devices.
I mention that to explain why there is a OneToMany relationship between dev_tags and devices where it seems that this should be a OneToOne relationship.
So I have my 2 entities
@Entity
@Table(name = "dev_tags")
public class DevTags implements Serializable {

private Integer tagId;
private String devTagId;
private String devSerialNum;
private List<Devices> devices;

@Id
@GeneratedValue
@Column(name = "tag_id")
public Integer getTagId() {
    return tagId;
}

public void setTagId(Integer tagId) {
    this.tagId = tagId;
}

@Column(name="dev_tag_id")
public String getDevTagId() {
    return devTagId;
}

public void setDevTagId(String devTagId) {
    this.devTagId = devTagId;
}

@Column(name="dev_serial_num")
public String getDevSerialNum() {
    return devSerialNum;
}

public void setDevSerialNum(String devSerialNum) {
    this.devSerialNum = devSerialNum;
}

@OneToMany(mappedBy="devSerialNum")
public List<Devices> getDevices() {
    return devices;
}

public void setDevices(List<Devices> devices) {
    this.devices = devices;
}

}

and this one
public class Devices implements java.io.Serializable {

private Integer devId;
private Integer officeId;
private String devSerialNum;
private String devPlatform;
private String devName;
private OfficeView officeView;
private DevTags devTag;

public Devices() {
}

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "dev_id", unique = true, nullable = false)
public Integer getDevId() {
    return this.devId;
}

public void setDevId(Integer devId) {
    this.devId = devId;
}

@Column(name = "office_id", nullable = false, insertable=false, updatable=false)
public Integer getOfficeId() {
    return this.officeId;
}

public void setOfficeId(Integer officeId) {
    this.officeId = officeId;
}

@Column(name = "dev_serial_num", nullable = false, length = 64, insertable=false, updatable=false)
@NotNull
@Length(max = 64)
public String getDevSerialNum() {
    return this.devSerialNum;
}

public void setDevSerialNum(String devSerialNum) {
    this.devSerialNum = devSerialNum;
}

@Column(name = "dev_platform", nullable = false, length = 64)
@NotNull
@Length(max = 64)
public String getDevPlatform() {
    return this.devPlatform;
}

public void setDevPlatform(String devPlatform) {
    this.devPlatform = devPlatform;
}

@Column(name = "dev_name")
public String getDevName() {
    return devName;
}

public void setDevName(String devName) {
    this.devName = devName;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "office_id")
public OfficeView getOfficeView() {
    return officeView;
}

public void setOfficeView(OfficeView officeView) {
    this.officeView = officeView;
}

@ManyToOne()
@JoinColumn(name="dev_serial_num")
public DevTags getDevTag() {
    return devTag;
}

public void setDevTag(DevTags devTag) {
    this.devTag = devTag;
}

}

I messed around a lot with @JoinColumn(name=) and the mappedBy attribute of @OneToMany and I just cannot get this right.  I finally got the darn thing to compile, but the query is still trying to join devices.dev_serial_num to dev_tags.tag_id, the @Id for this entity.  Here is the transcript from the console:
13:12:16,970 INFO  [STDOUT] Hibernate:
select
    devices0_.office_id as office5_2_,
    devices0_.dev_id as dev1_2_,
    devices0_.dev_id as dev1_156_1_,
    devices0_.dev_name as dev2_156_1_,
    devices0_.dev_platform as dev3_156_1_,
    devices0_.dev_serial_num as dev4_156_1_,
    devices0_.office_id as office5_156_1_,
    devtags1_.tag_id as tag1_157_0_,
    devtags1_.comment as comment157_0_,
    devtags1_.dev_serial_num as dev3_157_0_,
    devtags1_.dev_tag_id as dev4_157_0_
from
    ond.devices devices0_
left outer join
    ond.dev_tags devtags1_
        on devices0_.dev_serial_num=devtags1_.tag_id
where
    devices0_.office_id=?
13:12:16,970 INFO  [IntegerType] could not read column value from result set: dev4_156_1_; Invalid value for getInt() - 'FDO1129Y2U4'
13:12:16,970 WARN  [JDBCExceptionReporter] SQL Error: 0, SQLState: S1009
13:12:16,970 ERROR [JDBCExceptionReporter] Invalid value for getInt() - 'FDO1129Y2U4'

That value for getInt() 'FD01129Y2U4' is a serial number, definitely not an Int!  What am I missing/misunderstanding here?   Can I join 2 tables on any fields I want or does at least one have to be a primary key?

A: The short answer is "no, you can't join 2 tables on any fields"; association will always refer to primary key on one side.
"mappedBy" attribute for @OneToMany is used for bi-directional assocations and specifies the name of the property on collection element that maps back to owner entity as @ManyToOne. In your case,
@OneToMany(mappedBy="devSerialNum")

declaration is invalid; it should be changed to
@OneToMany(mappedBy="devTag")

instead if you want to maintain a bi-directional relationship. @JoinColumn can be used with @ManyToOne to specify the name of the (foreign key) column pointing to the other table. In your case,
@ManyToOne()
@JoinColumn(name="dev_serial_num")
public DevTags getDevTag() {

declaration says that you have a column called dev_serial_num in your devices table that  will be a foreign key pointing to dev_tags.tag_id which is also wrong.
I'm not quite clear on what you meant by "devices age out", but it seems to me that you're trying to merge two separate concepts into a single table which is where all these issues stem from. Consider instead separating your "devices" table (and entity) into two:

*

*"Core" device (for the lack of better name) should contain truly unique attributes, like serial number. Your DevTags entity will be linked as one-to-many to this one.

*Device "version" would contain attributes applicable to individual "version". There will be multiple "versions" for each "core" device; "version" is what will be updated every 2 weeks.


text:
Q: What if git repository gets corrupted? Git keeps track of every change you've made to your project. So it feels much safer to work on something knowing that, even if system crashes and current files you were working in get corrupted, there will still be the latest version you've commited in the .git folder. But what if some files in that folder get corrupted. Does git keep an extra backup of them as well?
I'm also curious how git handles writing to files. Does it create backups while writing for in case of a crash it can recover? Or does it just write directly to the files? I know git is open source, but the source code is too overwhelming for a beginner like me to understand...

A: This seems like common misconception about git.
Git is not backup solution.
You can use git to backup things and it (usually) work but there's no dedicated, fool-proof logic to prevent data loss on file corruption. You can (and arguably should) push your local files to some remote (which can be private) which would increase resilience to corruption - but that's it.
If you like versioning using Git and would like to read more on topic of backing it up you can check out Git Backup Guide


text:
Q: Select content from class, then send with help of AJAX I write my code using ASP.NET MVC(Razor) and JS. I have a spreadsheet, from which I must get all content from class .
jtable-column-header, and then send it to "/Template/DataGridSave/@ViewBag.TemplateGuid/@Model.Name" controller with help of ajax.
I try to do this in that way:
function createSaveDialog_@(Model.Name)()
          {
            // Creating diallog form
            $( "#dialog_@Model.Name" ).dialog({
                resizable: false,
                autoOpen: false,
                minHeight: 400,
                closeText: "Close",
                modal: true,
                buttons: [{
                    // Button, that must send content of "th.jtable-column-header"
                    text: 'Save',
                    "class":'btn btn-primary pull-left',
                    click: function() {
                        var abc = $('th.jtable-column-header');
                        $.ajax({
                            url: "/Template/DataGridSave/@ViewBag.TemplateGuid/@Model.Name",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            data: abc,
                       });

                   }},
                    {
                        text: 'Close',
                        "class":'btn btn-primary pull-right',
                        click: function() {
                            $('#DataGridView_@Model.Name').data({RecordEdit:null});
                            $( this ).dialog( "destroy" );
                        }
                    }]
            });
        }

I call this function on form, but works only button "Close". When I press "Save" nothing happens.
What's wrong?


text:
Q: Making Sense of Android meta-viewport scaling: What am I missing? I have been trying to determine how the viewport -- and the contents within -- are affected by the viewport meta tag used for drawing content with WebView or with the native browser.
What I have run in to are some apparent inconsistencies. I created a small page (see below) with an image and some javascript for displaying the viewport size so I can visually see the scaling with the image as well as get the exact numbers.
First, a some observations:

*

*None of the viewport width numbers are exactly what I expected, just close.

*When the numbers are close to the device pixel count, the drawing is actually done one-for-one -- or at least is visibly looks that way.

*If the page size (document size) is under that of the viewport size, the viewport numbers shrink. That is, the viewport doesn't always necessarily represent the maximum possible visible space -- just the current visible space.

*Likewise, in the native browser, the viewport size is adjusted by the top bar. The size increases as it scrolls off the screen. The numbers given are for full screen display.

Device #1: Physical screen is 1024x600 and it's running Android 2.2.

*

*initial-scale=1.0 => 676x400

*initial-scale=1.0, width=device-width => 676x400

*initial-scale=2, width=device-width => 338x200

*initial-scale=2, width=device-width, target-densitydpi=device-dpi
=> 507x300

*initial-scale=0.5, width=device-width,
target-densitydpi=device-dpi => 800x473

*initial-scale=0.9, width=device-width,
target-densitydpi=device-dpi => 800x473

*width=device-width, target-densitydpi=device-dpi => 1014x600

*initial-scale=1.0, width=device-width,
target-densitydpi=device-dpi => 1014x600

*initial-scale=0.5, width=device-width,
target-densitydpi=device-dpi, minimum-scale=0.1 => 2028x768

*initial-scale=0.5, width=device-width,
target-densitydpi=device-dpi, minimum-scale=0.1, user-scalable=no =>
1014x600

Device #2: Physical screen is 800x480 and it's running Android 2.3.2.

*

*initial-scale=1.0 => 527x320

*initial-scale=1.0, width=device-width => 527x320

*initial-scale=2, width=device-width => 263x160

*initial-scale=2, width=device-width, target-densitydpi=device-dpi
=> 395x240

*initial-scale=0.5, width=device-width,
target-densitydpi=device-dpi => 790x480

*initial-scale=1.0, width=device-width,
target-densitydpi=device-dpi => 790x480

*initial-scale=0.5, width=device-width,
target-densitydpi=device-dpi, minimum-scale=0.1 => 1580x768

*initial-scale=0.5, width=device-width,
target-densitydpi=device-dpi, minimum-scale=0.1, user-scalable=no =>
790x480

*width=1580, target-densitydpi=device-dpi => 790x480

*width=1580, target-densitydpi=device-dpi => 790x480

*width=1580, target-densitydpi=device-dpi, minimum-scale=0.1
=>790x480
Of these results, the following don't make sense:

*

*Device #1, items 5, 6, and 10

*Device #2, items 5, 8, 10, 11, 12

Does anyone know what's going on with those that don't make sense?
Does anyone know why many of the values are 10 pixels shy of match the physical pixels, but that result is as if they match? (e.g. 1.7 and 2.6)
Am I doing something wrong, or does it appear that it's impossible to zoom out beyond 1.0 unless the user is also allowed to scale and the minimum-scale value is set?
That is, even though the valid values are 0.01 to 10, initial-scale values under 1.0 are ignored unless you can also set the minimum scale.
The Android docs do say when user-scalable is no that the min/max scale values are ignored. That doesn't seem very useful. And 2.9-2.11 seem to show that you can't just calculate it yourself and set the width.
Finally, the HTML I'm using:

    <meta name="viewport" content="initial-scale=0.5, width=device-width, target-densitydpi=device-dpi, minimum-scale=0.1, user-scalable=no" />

Hello world.

So... what am I missing?

A: $(document).ready(function() {
$('meta[name=viewport]').attr('content','width=1024, user-scalable=no');
});

Seem to work for disabling the user scaling after the correct scaling have been applied

A: Interesting can of worms you've opened up there. As you try out more devices you'll probably see even more weirdness, and random bugs. Interesting times! :-)
I suspect that somewhere down the line you might want to give up, and just try to...

*

*Stick with as simple settings as possible.

*Accept the pixel width the device chooses to report.

*Rely on adaptive/fluid layout and relative widths to make things work across different screen widths.

*Use native CSS properties for a resolution neutral rendering of rounded corners, shadows and gradients.

*Use vector formats (svg, icon-fonts, etc.) as much as possible

*and (important) Use high-res border-images as well as background-images coupled with the well-supported background-size property1 to make things render nice and crisp2.

1) To provide backwards compatibility to older browsers (like MSIE8) you'll need to use double background-image declarations - like:
background-image: url(low-res.png);        /* CSS2 */
background-image: url(high-res.png), none; /* CSS3 */
background-size:  100px 10px;             /* CSS3 */

2) The -webkit-max-device-pixel-ratio media query may also help, but as the name implies it only works for webkit browsers.

Ramble:
The new generation Android and iOS devices have such varying screen DPIs that they've resorted to reporting CSS pixels rather than actual device pixels. This is both good or bad - depending on how you look at it.
It's bad because you're not guaranteed anymore the down-to-the-device-pixel control you were used to having, working with the mostly homogenous screens of yore.
On the other hand, it's good because you know your designs will never render so tiny that they can't be read/used by regular humans.
The problem with using target-densitydpi=device-dpi is that it while it works wonders on a 7inch wide 800px screen, it will completely ruin your application on a 4inch wide 960px screen.


text:
Q: One more skipping jump discontinuity in pgfplots Trying to draw graphs using pgfplots (regarding this library, I am a beginner). I tried to find a solution to my problem (in even offered links), but I was not successful. Is it possible to achieve that when you draw a graph skip discontinuity?
I would like noting that I use pgfplots library only in ConTeXt, but for this need I have prepared an example in LaTeX.
Thanks for the ideas. Jaroslav
\documentclass{minimal}
\usepackage{pgfplots}
\def\AddLabel(#1,#2)#3{\node [align = center] at (axis cs: #1,#2) {#3};}%

\begin{document}
\begin{tikzpicture}
    \def\function{rad(atan((\x)/(2+\x)))}
    \def\functionlabel{\arctan{\frac{x}{2+x}}}

\begin{axis}[
        xmin=-10,
        xmax=10,
        domain=-9.5:9.5,
        ymin=-2,
        ymax=2,
        width=\textwidth,
    height=0.5\textwidth,
        axis x line=middle,
        axis y line=middle,
        axis equal=true,
        xlabel=$x$,
        ylabel=$y$,
        samples=600,
        clip=true,
]
\addplot[color=black, line width=1.5pt]{\function};

\AddLabel(6,2.5){$f\!:\ y=\functionlabel$}
\AddLabel(6,2.5){$f\!:\ y=\functionlabel$}
\end{axis}
\end{tikzpicture}
\end{document}

A: If I understand correctly what you're after, one way is to plot two separate lines, one for x < -2, one for x > -2.

\documentclass[border=2mm]{standalone}
\usepackage{pgfplots}
\def\AddLabel(#1,#2)#3{\node [align = center] at (axis cs: #1,#2) {#3};}%

\begin{document}
\begin{tikzpicture}
    \def\function{rad(atan((\x)/(2+\x)))}
    \def\functionlabel{\arctan{\frac{x}{2+x}}}

\begin{axis}[
        xmin=-10,
        xmax=10,
        ymin=-2,
        ymax=2,
        width=\textwidth,
    height=0.5\textwidth,
        axis x line=middle,
        axis y line=middle,
        axis equal=true,
        xlabel=$x$,
        ylabel=$y$,
        samples=600,
        clip=true,
]
\addplot[color=black, line width=1.5pt,domain=-9.5:-2]{\function};
\addplot[color=black, line width=1.5pt,domain=-2:9.5]{\function};

\AddLabel(6,2.5){$f\!:\ y=\functionlabel$}
\AddLabel(6,2.5){$f\!:\ y=\functionlabel$}
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: How to update an AwsBatchOperator task code in Airflow? I have an airflow-scheduler and airflow-webserver deployed on an EC2 machine on AWS. I use this airflow-scheduler to execute a DAG with an AwsBatchOperator task. This task executes a python script present on EC2 machine. Here is the code of the DAG:
from datetime import timedelta
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.providers.amazon.aws.operators.batch import AwsBatchOperator

default_args = {
    'owner': 'admin',
    'concurrency': 3,
    'depends_on_past': True,
    'email': ['airflow@example.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
    'start_date': None,
    'end_date': None,
    'schedule_interval': None,
}

dag = DAG(
    dag_id='my-dag',
    default_args=default_args,
    description='My DAG',
    schedule_interval='00 03 * * *',
    start_date=days_ago(1),
    tags=['dev'],
)

task = AwsBatchOperator(
  dag=dag,
  job_name= 'my-job-name',
  job_definition= 'arn:aws:batch:eu-central-1:XXXX:job-definition/my-job-name',
  job_queue= 'arn:aws:batch:eu-central-1:XXXX:job-queue/my-job-name',
  region_name= 'eu-central-1',
  task_id= 'my-task-id',
  overrides={
    'command': ['python3', './my_python_script.py']
  },
  parameters= {}
)

The python script my_python_script.py is on the EC2 machine where airflow is deployed, in directory /home/ubuntu.
I had a typo raising an error in this python script. I corrected it and push the corrected script on EC2 machine. However when I execute the DAG, I still get the error caused by the typo I corrected. So here is my question:
How can I refresh my DAG to ensure that it uses the version of my script that is present on my EC2 machine?
What I've tried

*

*Refresh DAG by clicking on "refresh" button on Airflow web interface

*Wait for automatic DAG refresh by airflow-scheduler

*Delete DAG and wait for refresh

*Recompile python script on EC2 machine with command python -m compileall

A: To update code of an AwsBatchOperator task, you need to update docker image used by your AWS batch job with your new code and not the code present on EC2 machine where airflow is deployed
AwsBatchOperator can execute code present in AWS batch job definition docker image but cannot execute code present in EC2 machine where airflow is deployed.
When you use AwsBatchOperator, you set which job definition you want to use. For my case, it is arn:aws:batch:eu-central-1:XXXX:job-definition/my-job-name. This job definition contains the docker image where your command will be executed. See https://docs.aws.amazon.com/en_en/batch/latest/userguide/Batch_GetStarted.html
I was confused as it was the same codebase that was present on EC2 machine and docker image. So instead of updating code on EC2 machine where airflow is deployed, I just have to create a new docker image with the new version of my code and make my AWS batch job uses this new image.


text:
Q: My object works only if instantiated in onCreate() I have an object Model and it is created in first activity and transferred to second activity by Intent . When object is initialized in second activity I can use it only in onCreate(), but when I use it in another method, the app crashes.
1-st Activity creating object and add to Intent:
Intent intent = new Intent(ModelCreatorActivity.this, ModelCreatorBluetooth.class);
Model m = new Model(name);
m.setStreamType(Model.StreamType.valueOf(type));
intent.putExtra("Model_new", new Gson().toJson(m));
ModelCreatorActivity.this.startActivity(intent);

2-nd activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_model_creator_bluetooth);

    String jsonMyObject = null;
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        jsonMyObject = extras.getString("Model_new");
    }
    m = new Gson().fromJson(jsonMyObject, Model.class);
    //here normal work
    Log.d("Models", m.getName() );

}

  public void connectToDevice(String address) {
    if (btt != null) {btt = null;
    }

    btt = new BluetoothThread(address, new Handler() {

        @Override
        public void handleMessage(Message message) {
            Context c = getApplicationContext();
            String s = (String) message.obj;
            s = s.replace("\n", "").replace("\r", "");
            if (s.equalsIgnoreCase("CONNECTED"))
            {
                Toast t = Toast.makeText(c, "CON", Toast.LENGTH_LONG);
                t.show();
                //here are crashing
                Log.d("Models", m.getName() );
            }
            else if (s.equals("DISCONNECTED"))
            {
                Toast t = Toast.makeText(c, "DSC", Toast.LENGTH_LONG);
                t.show();
            }
            else if (s.equals("CONNECTION FAILED"))
            {

                t.show();
                btt = null;
            }
        }
    });
  }

Thanks for help :)


text:
Q: i can't use 'time' word in mysql query? I can't use 'time' word as my column name in mysql query.
This is my query code:(Not Working)
UPDATE ip_p SET deger =  '-1' TIME =  '123' WHERE ip =  '12' AND premium =  '1'

Error is:

#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'time='123' WHERE ip =  '12' AND premium =  '1'' at line 1

But this code is working:
UPDATE ip_p SET deger =  '-1' WHERE ip =  '12' AND premium =  '1'

Will I have to change my column name?

A: 1) You're missing coma (,) after deger =  '-1'
2) You may enclose TIME into backticks (`) to prevent other possible errors
Correct (try it?) query spelling:
UPDATE ip_p SET deger =  '-1', `TIME` =  '123' WHERE ip =  '12' AND premium =  '1'

UPDATE
Responding to comment:
correct query for decreasing deger column by 1 will be:
UPDATE ip_p SET deger =  deger-1, `TIME` =  '123' WHERE ip =  '12' AND premium =  '1'

If you just need to set it to -1 then do:
UPDATE ip_p SET deger = -1, `TIME` =  '123' WHERE ip =  '12' AND premium =  '1'

Also please note that syntax with single quotes (') should be used only with strings (varachar(...) columns etc.); for numbers that is incorrect. If you need to specify the number - just do it without any quotes. I've changed this for deger column (apparently it's numeric if you want to subtract something from it) but not for the others because I don't know their types. If columns TIME, ip and premium are also numbers then you'll need to also remove quotes from their values.

A: You can escape the keyword "time" by using backticks:
UPDATE ip_p SET deger =  '-1', `TIME` =  '123' WHERE ip =  '12' AND premium =  '1'

I believe you also dropped a comma, which may be the cause of the error you are getting here. But in general, if you have a column name which is special to MySQL, escape it.

A: You can, but you must enclose the name in backticks `. As a general rules I always enclose column names in them, as it makes it clear what they are.

A: You're missing a comma before TIME:
UPDATE ip_p SET deger =  '-1', TIME =  '123' WHERE ip =  '12' AND premium =  '1'
                             ^


text:
Q: Closure and Interior of Arithmetic Progression I am trying to figure out and prove what the interior and closure of A where A is all even integers for the topologies on the integers with the following topologies would be.
K must be a nonnegative integer
First: $B(a, k) = \{a + (3^k)m \mid m  \epsilon \mathbb{Z}\}$
Based on intuition, I think  $Int A = \phi$, but I have no idea how to prove this.
I also think $Cl A = \mathbb{Z}$ but have no idea if this is right or how to prove it.
Second: $B(a, k) = \{ a + (2^k)m \mid m  \epsilon \mathbb{Z} \}$
I think $Int A = B(0,1)$ but I do not know how to prove this.
I think $Cl A = B(0,1)$ as well since $B(0,1)$ is open since $\mathbb{Z} - B(0,1) = B(1,1)$ which is open. Is this correct? How do prove $\mathbb{Z} - B(0,1) = B(1,1)$?

A: First case: if $a \in A$, and $B(a,k) \subseteq A$for some $k$, then $B(a,k) \ni a+3^k \in A$ which is a contradiction as $a$ is even and $3^k$ is always odd (also true for $k=0$) so $a+3^k$ is odd, so not in $A$. So no point $a \in A$ is an interior point of $A$ in the topology with these local bases. Hence $\operatorname{int}(A)=\emptyset$.
$\operatorname{cl}(A) = \Bbb Z$ because if $a$ is odd and $B(a,k)$ is any local base set, $a + 3^k \in A \cap B(a,k)$ and so every basic neighbourhood of $a$ intersects $A$.
Second case: If $a$ is even then all numbers of the form $a+m\cdot 2^k$ are also even (sum of even numbers) and if $a$ is odd, so are all $a+m \cdot 2^k$ as well. So both $A$ and $\mathbb{Z}\setminus A$ are open, and so both are closed as well (so $\operatorname{int}(A)=A=\operatorname{cl}(A)$)


text:
Q: IFrame not loading new page with changing src value I am using IFrame to load pages from my main page. Some times first 2-3 pages load normally when I specify source on click of a link using:
var frame = $('#mainFrame')[0];
frame.src='/directory/example.aspx';

I have also tried using jQuery attribute:
$('#mainFrame').attr('src','/directory/example.aspx');

I have tested in  Firebug the src attribute is changed, but when I check following:
frame.content.document.location.href

it show a different location than that specified using src tag.
Please suggest some remedy as this issue is delaying all of my work :(

A: I would create a javascript function that sets an innerHTML property of a div based on an XMLHTTPRequest AJAX style.  Being from IE 5 and Netscape 4.7 days I still have bad memories of Iframes and avoid them at all costs although I hear the issues are now fixed..

A: Folks there I had to struggle with this again today. It seems two things (leading to the same effect) were causing IFrame to missbehave.
1) We are using Telerik ASP.Net AJAX controls. My colleagues were calling a function in main page of application to move it to next or previous pages like:
top.moveNext();
return false;

or
top.movePrevious();
return false;

but they were calling these in RADButton's OnClientClicked event handler. I changed it to be called in OnClientClicking handler and canceled the event like:
function onNextClicking(s,a){
    a.set_cancel(true);//stops event from propogating
    top.moveNext();
}

This made it to behave correctly with pages having RADButtons.
2) On some pages we were using simple button elements. There too they were returning false after calling methods from top window. We have changed those buttons to RADButtons and are handling steps in OnClientClicking handlers. Though it seems strange that a function inside a page already loaded in the IFrame is causing it to stop loading new URL if it returns false.


text:
Q: Inserting script and link tag inside the header tag Is it possible to insert/generate <Script> and <Link> tag inside the <Header> using only Javascript or DOM (not JQuery) when the page load or by just including one <Script> tag inside the <Header> and do it from there? And would still allow us to debug it and avoid duplicates if just in case we already added one similar <Script> or <Link> in the <Header>?
For example:
Before
<Header>
   <script src="Scripts/Generate.js" type="text/javascript"></script>
</Header>

After
<Header>
   <script src="Scripts/Generate.js" type="text/javascript"></script>
   <script src="Scripts/Script1.js" type="text/javascript"></script>
   <script src="Scripts/Script2.js" type="text/javascript"></script>
   <link href="CSS/Css1.css" rel="stylesheet" type="text/css" />
   <link href="CSS/Css2.css" rel="stylesheet" type="text/css" />
</Header>

Any advice or answers would help me.

A: HTML:
<head>
    <script src="Scripts/Generate.js"></script>
</head>

Scripts/Generate.js:
if(!document.getElementById('id1')) {
    var script = document.createElement('script');
    script.id = 'id1';
    script.src = 'Scripts/Script1.js';
    document.head.appendChild(script);
}
if(!document.getElementById('id2')) {
    var link = document.createElement('link');
    link.id = 'id2';
    link.rel = 'stylesheet';
    link.href = 'CSS/Css1.cs';
    document.head.appendChild(link);
}

Afterwards, the HTML is:
 <head>
    <script src="Scripts/Generate.js"></script>
    <script id="id1" src="Scripts/Script1.js"></script>
    <link id="id2" rel="stylesheet" href="CSS/Css1.cs">
</head>

A: I'll presume that "duplicate" means having the same src attribute value. Note that this will only prevent the addition of a duplicate by the script, so it must be run after all other scripts have been added:
function conditionallyAddBySource(tagName, src) {

  tagName = tagName.toLowerCase();
  var elements = document.getElementsByTagName(tagName);
  var propToCheck = {script:'src', link: 'href'}[tagName];

  for (var i=0, iLen=elements.length; i<iLen; i++) {

    // If find a "matching" element, do nothing
    if (elements[i][propToCheck].indexOf(src) != -1) {
      return;
    }
  }

  // Otherwise, add an element of the required type
  var element = document.createElement(tagName);
  element[propToCheck] = src;
  document.getElementsByTagName('head')[0].appendChild(element);
}

conditionallyAddBySource('script', 'myJSLib.js');

The new element doesn't have to be added to the head, could just be written immediately using document.write or attached to the body (or any other element that can have child nodes other than the HTML and document element). Link elements probably should be in the head though.
Edit
Determine whether to check src or href depending on whether tagName is script or link.
Using Paul's suggestion of querySelector, you can use:
function conditionallyAddBySource(tagName, src) {

  tagName = tagName.toLowerCase();
  var propToCheck = {script:'src', link: 'href'}[tagName];
  var element = document.querySelector(tagName + '[' + propToCheck + '$="' + src + '"]');

  if (!element) {
    element = document.createElement(tagName);
    element[propToCheck] = src;
    document.getElementsByTagName('head')[0].appendChild(element);
  }
}

provided querySelector support is avilable (IE 8 in standards mode and higher, dunno about others).

A: The easiest way is like this:
> document.head.innerHTML += '<link rel="stylesheet" type="text/css" href="styles.css" />';


text:
Q: Exact meaning of weights in SOLR ranking I have been trying different weights on SOLR dismax and edismax ranking and got to wonder what these weights mean? For example, you can specify qf parameter something like this:
qf:title^2.0 body^1.0 ...

What do these weights mean? Is it multiplication of each field's text score? Or is it addition?
Also how about pf parameter?
pf:title^2.0 body^0.5

Is it also multiplication or addition?
If someone could shed some light, that will be great.

A: qf -> is for query fields which measures score for individual terms.
boost multiplies the weight to the individual match score for the field
e.g. qf:title^2.0 body^1.0 document with match on the title field will have double the score then a document with a match on boby (given all the other factors are same)
pf -> is for phrase query which measures score for phrase terms
e.g. for query internet banking and Configuration qf:title^2.0 body^1.0 and pf:title^2.0 body^0.5
should result in query :-
title:internet^2 title:banking^2
body:internet^1 body:banking^1
title:"internet banking"^2 body:"internet banking"^0.5


text:
Q: Should I have an updated count as part of user table? Let's imagine I have a databases with two tables, Users and Posts. The first table contains a row for each user, the second table a row for each post that users have written. If I want to display a post count on the users' profiles, which of these two strategies work the best:

*

*Every time a user creates a post I UPDATE the Users table, +1 a field PostCount;

*When someone visits the profile I simply run a select statement to get a count of post, for example SELECT COUNT(post_id) FROM Posts WHERE id_user = 100;

In the first case I have to UPDATE a table very often, which it could be bad as I believe a table gets locked when doing the update; in the second case I have to run a count every time the user visits a profile. Which poison is the less bitter? Is there any other way?

A: I would say that it depends on how many times you will display PostCount, especially for a huge amount of Users. If you are going to display it for 1000+ users on a page that will be called a lot of times, then the first solution should be the best. But you need to do transactions to be sure both tables Posts and Users are updated when adding a new post.
Otherwise, the second solution should be enough, but you should use LEFT OUTER JOIN so that you would get both information from Users and Posts table in only one query. Eg:
SELECT *
FROM Users u
LEFT OUTER JOIN (
    SELECT user_id , COUNT(*) AS posts_count
    FROM Posts
    GROUP BY user_id
) p ON p.user_id = u.id
WHERE u.id = :searched_id

(And anyway you should use a Cache system so that you don't have to do the same SQL query for a same page if shown to several users.)


text:
Q: Local variables in Tail recursion? I have been reading a lot of articles about tail recursion.But i am still unclear about how the tail recursion uses no stack space.
What about the local variables and function arguments? They are also stored in the stack.What will happens to these in case of a tail recursion? How is it different from normal recursion.
"A tail call [tail recursion] is a kind of goto dressed as a call"
What this really means?

A: Local variables are forgotten. The whole point of tail-call recursion is that it is the last thing that will happen in a function, so local variables won't matter after the call. In fact, there not being an "after the call" is what the tail-call optimisation is all about.
EDIT: About the quote:
In a tail-call-optimised scenario, these two are equivalent:
fn(x) {
  ....
  fn(y);
}

and
fn(x) {
  start:
  ....
  x = y;
  goto start;
}


text:
Q: C++ Linux Async HTTP POST (Boost::asio) I have spent the last two days trying to make an async http POST with libcurl and I think I'm giving up on it. curl_multi_fdset is giving me -1 for the number of file descriptors arg and the documentation simply states "it means there's an error with your application". Making a synchronous call was very simply, but that is of course worthless.
Boost::asio seems promising but I can't find any examples of how to do an http POST.
If someone would be kind enough to show me an example of that I could stop pulling my hair out.

A: Here is something I think you may find useful. It is a C++ simple to use HTTP library based on boost.


text:
Q: Changing A Picker to a TextField in SwiftUI I'm a newbie self teaching myself iOS development (100DaysOfSwiftUI by Paul Hudson, Project 1), and currently I came across a problem that I haven't been able to solve yet. Originally, the numberOfPeople section had a picker with below code, which I'm trying to change to a text field. Started by changing its @State property (@State private var numberOfPeople = 2) from 2 to empty string, and tried creating another computed property for people count. when the number of people text field is left empty, 0 doesn't appear as default on the simulator on the amount per person section when I run the project, instead NaN appears as in the screenshot below. (Which makes me wonder if numberOfPeople converted successfully to an Integer through nil coalescing as below). Only time the project functions as it should is when I enter a value in the number of people text field. I'm not 100% sure where I went wrong with this, but any help will be greatly appreciated!!
struct ContentView: View {
    @State private var checkAmount = ""
    @State private var numberOfPeople = ""
    @State private var tipPercentage = 2

    let tipPercentages = [10,15,20,25,0]
    let allPeople = 2...100

    var totalPerPerson: Double {
        let peopleCount = Double(numberOfPeople) ?? 0
        let tipSelection = Double(tipPercentages[tipPercentage])
        let orderAmount = Double(checkAmount) ?? 0

        let tipValue = orderAmount / 100 * tipSelection
        let grandTotal = orderAmount + tipValue
        let amountPerPerson = grandTotal / peopleCount

        return amountPerPerson
    }

    var grandTotal: Double {
        let tipSelection = Double(tipPercentages[tipPercentage])
        let orderAmount = Double(checkAmount) ?? 0

        let tipValue = orderAmount / 100 * tipSelection
        let totalAmount = orderAmount + tipValue

        return totalAmount
    }

    var body: some View {
        NavigationView {
            Form {
                Section {
                    TextField("Amount", text: $checkAmount)
                        .keyboardType(.decimalPad)

                    TextField("Number of people", text: $numberOfPeople)
                        .keyboardType(.numberPad)
                }

                Section(header: Text("How much tip do you want to leave?")) {
                    Picker("Tip percentage", selection: $tipPercentage) {
                        ForEach(0 ..< tipPercentages.count) {
                            Text("\(self.tipPercentages[$0])%")
                        }
                    }
                    .pickerStyle(SegmentedPickerStyle())
                }

                Section (header: Text("Total Amount")){
                    Text("$\(grandTotal, specifier: "%.2f")")
                }

                Section (header: Text("Amount Per Person")){
                    Text("$\(totalPerPerson, specifier: "%.2f")")
                }
            }
            .navigationBarTitle("WeSplit")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

(Original code for picker)
Picker("Number of people", selection: $numberOfPeople) {
        ForEach(2 ..< 100) {
            Text("\($0) people")

(Original code for people count)
let peopleCount = Double(numberOfPeople + 2)

project simulator

A: What you're seeing is a result of trying to divide by zero. You can avoid that calculation by returning 0 from your totalPerPerson function if peopleCount is 0 before doing the division using something like this:
var totalPerPerson: Double {
    let peopleCount = Double(numberOfPeople) ?? 0
    let tipSelection = Double(tipPercentages[tipPercentage])
    let orderAmount = Double(checkAmount) ?? 0

    guard peopleCount > 0 else {
        return 0
    }

    let tipValue = orderAmount / 100 * tipSelection
    let grandTotal = orderAmount + tipValue
    let amountPerPerson = grandTotal / peopleCount

    return amountPerPerson
}

Keep in mind that with your new TextField, as opposed to the picker, even if you specify .decimalPad or .numberPad, there are still ways for the user to enter non-numerical values in those fields, so you'd probably want to put up an error if that happens (or, search here on SO for solutions about fields that only accept numbers).
An example for such a TextField is specified in this solution


text:
Q: How to access json nested objects in node.js I have used xml2js parser to parse the xml file in node.js. It is parsing the xml successfully. But now i want to parse the json or to identify the particular data in json.
My node.js code
var fs = require('fs');
var parseString = require('xml2js').parseString;
var xml = 'C:\\temp\\Masters.xml';
var fileData = fs.readFileSync(xml,'utf8');
parseString(fileData, function (err, result) {
console.log(JSON.stringify(result));
var json = JSON.stringify(result);

var jsonObj = JSON.parse(json);
for (var key in jsonObj) {
console.dir(key + ": " + jsonObj[key].Customer_Name);
}
});

In console output:
'Masters: undefined'

Json data:
'{"Masters":
  {
    "Customer":

  [
  {"Customer_Name":["Kim"],
  "Customer_Code":["c86"],
  "Date":["23-11-15"],
  "Address":["Narhe"],
  "City":["Pune"],
  "State":["Maharashtra"],
  "TIN":["3365670"],
  "PAN_Number":["AAAAA1111a"],
  "Mobile_Number":["8999000090"],
  "Email_ID":["amitshirke@gmail.com"],
  "Contact_Person":["Anish"],
  "Opening_Balance":["0"] },

  {"Customer_Name":["Ankit"],
  "Customer_Code":["c87"],
  "Date":["12-04-15"],
  "Address":["Narhe"],
  "City":["Pune"],
  "State":["Maharashtra"],
  "TIN":["336567"],
  "PAN_Number":["AAAAA1111p"],
  "Mobile_Number":["8900000000"],
  "Email_ID":["amitshirke1@gmail.com"],
  "Contact_Person":["Anuj"],
  "Opening_Balance":["0"] }
  ]
 }
}'

In above data, Masters is root element(Object), Customer is another nested object and there two customers. Then how can I access the customer names or how to use the for loop to access the same?.
Thanks in advance.

A: You can access the Customer array as follows -
var customerArray = Masters.Customer,
    length = customerArray.length;

for(var i = 0; i < length; i++)
{
    // You can access the customers array from here -
    console.log(customerArray[i].Customer_Name[0]); // [0] hardcoded because as you can see all the variables are in array at 0th position
   // similarly you can access other data
   console.log(customerArray[i].City[0]);
}


text:
Q: BxSlider maxslide and minslide So basically, i am using BxSlider with 27 thumbnails, on each is loaded a lightbox so you can check every image.
Thing is, when i load the script with this :
$('ul#items').bxSlider({
          minSlides: 5,
          maxSlides: 5,
          slideWidth: '920px'
        });

I am forced to get 5 thumbnails on everypage of the slider.
So on the last page, my last 3 thumbnails are the first 3 repeated.
I tried using this, instead to fix my problem,
$('ul#items').bxSlider({
          minSlides: 1,
          maxSlides: 5,
          slideWidth: '920px'
        });

But it seems that if you input 1 as minSlides, the script will put only 1 (which gives you 27 pages of 1 thumbnail) slide per page, even if you specefy a maximum of 5 per slide.
Any way to fix this issue ?
thanks alot !

A: If you look at example 3 it describes the issue you are having. Because the slideWidth property is set to be larger than the container it defaults to the minSlide property to allow the slides to scale.

"Here we intentionally set a slideWidth larger than the available space. In this case, the slider defaults to the minSlide value, and scales appropriately." - bxslider example 3 description

To get the desired effect you are looking for you should set the max-width value as the slideWidth property. This way the screen will allow you to switch between minSlide and maxSlide as the viewport allows. You can see this demonstrated in example 4.
I hope this helps, as it took me a while to figure out for myself.
$('ul#items').bxSlider({
    slideWidth: 200,
    minSlides: 1,
    maxSlides: 5,
    slideMargin: 10
});

A: try this
$('ul#items').bxSlider({
          minSlides: 1,
          maxSlides: 5,
          slideWidth: '920px',
          infiniteLoop: false
        });


text:
Q: C++ Boost Property Tree Update Existing Node By Attribute Qualifier Ok, so here's a sample of the XML structure:
<config>
  <Ignored>
    <Ignore name="Test A">
       <Criteria>
          <value>actual value</value>
       </Criteria>
    </Ignore>
    <Ignore name="Test B">
       <Criteria>
          <value>actual value</value>
       </Criteria>
    </Ignore>
  </Ignored>
<config>

I would like to be able to do two things:

*

*Perform a get directly to the Test A element without having to loop all Ignore elements..like a selector on an attribute.

*If nothing else, I need a method of updating either of the Ignore elements and can't seem to figure it out

Do I have to delete the element and recreate it?  I can't seem to figure out a way to perform a put which qualifies an element (where there a many with the same name at the same level) by an attribute (which would be unique at that level).
Something like:
pt.put("config.Ignored.Ignore.<xmlattr>.name='Test A'.Criteria.value",some_var)

Or anything else that can achieve the end goal.  Thank you very much!
Full disclosure: I'm pretty new to C++ and may be missing something blatantly obvious.

A: Boost.property_tree xml parser (RapidXML) doesn't support this.
Consider using something like TinyXPath is you want such functionality out of the box.
Or use explicit loop to find Ignore node with required attribute. Then you can use
someIgnoreNode.put("Criteria.value", some_var);

A: you may use a method like:
auto & pt_child = pt.getchild("config.Ignored");
BOOST_FOREACH(ptree::value_type &v1, pt_child)
{
    if (v1.first == Ignore && v1.second.get<std::string>("<xmlattr>.name") == "Test A")
    {
        ptree & ptGrandChild = v1.second;
        ptGrandChild.put<std::string>("Criteria.value", some_var);
    }
}

boost::property_tree::xml_writer_settings<std::string> settings =
boost::property_tree::xml_writer_make_settings<std::string>('\t', 1);
write_xml(xmlPath, pt, std::locale(), settings);