text:
Q: How to update the result on right side based on user input import React, { Component } from 'react'

    class Arithmetic extends Component {
        constructor(props) {
            super(props)
            this.state = {
               num1: 10,
               num2: 5,
            }
        }
        //the user input
        updateNum1(event) {
          this.setState({
           num1: event.target.value

           });

          }
        updateNum2(event){
            this.setState({
                num2: event.target.value

            });
          }
        render() {

      //calculation of values
            var sub=()=>{
              const {num1, num2} = this.state;
              var subtraction = num1 - num2;
              document.getElementById("output").innerHTML = subtraction;

           }

           var mul=()=>{
             const {num1, num2} = this.state;
             var multiplication = num1 * num2;
             document.getElementById("output").innerHTML= multiplication;

           }
        return (

                            <button type="button" class="btn btn-light active switch" value="sub"
                               name="invest_type" onClick={sub} checked>
                               Sub                         </button>
                             <button type="button" class="btn btn-light switch" value="mul"
                               name="invest_type" onClick={mul}>
                               Mul
                             </button>

                            Num1

                                <button type="button" class="btn btn-light active" value={10}
                                onClick={this.updateNum1.bind(this)} checked>
                               10
                               </button>
                               <button type="button" class="btn btn-light" value={15}  onClick=
                               {this.updateNum1.bind(this)} >
                               15
                               </button>
                               <button type="button" class="btn btn-light" value={20}  onClick=
                               {this.updateNum1.bind(this)} >
                               20
                               </button>
                               <input type="textbox" className="form-control" placeholder="Custom"
                               onChange={this.updateNum1.bind(this)} />

                           Num2

                                 <button type="button" class="btn btn-light active" value={5}  onClick=
                                   {this.updateNum2.bind(this)} checked>
                                   5
                                 </button>
                                 <button type="button" class="btn btn-light " value={10}  onClick=
                                   {this.updateNum2.bind(this)} >
                                   10
                                 </button>
                                 <button type="button" class="btn btn-light " value={15}  onClick=
                                   {this.updateNum2.bind(this)} >
                                   15
                                 </button>

                                 <input type="textbox" className="form-control" placeholder="Custom"
                                  onChange={this.updateNum2.bind(this)} />

RESULT

                           will grow to

            )
        }
    }

    export default Arithmetic

How to display the result for default value without clicking the button.How to change the result of sub and multiplication value on the user input based on button.
The value of the button is not going inside the sub and mul funtion without clicking button.I want to display the default value of the sub when the page is refresh.

A: You need to use value  state inside input i.e
<input
                      type="textbox"
                      className="form-control"
                      placeholder="Custom"
                      value={this.state.num2}
                      onChange={this.updateNum2.bind(this)}
                    />
<input
                    type="textbox"
                    className="form-control"
                    placeholder="Custom"
                    value={this.state.num1}
                    onChange={this.updateNum1.bind(this)}
                  />

Here is full code:

import React from "react";
import "./styles.css";

class Arithmetic extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      num1: 10,
      num2: 5,
      action: "sub",
      value: 0
    };
  }
  componentDidMount() {
    if (this.state.action === "sub") {
      this.updateSub();
    } else {
      this.updateMul();
    }
  }
  //the user input
  updateNum1(event) {
    this.setState(
      {
        num1: event.target.value
      },
      () => {
        if (this.state.action === "sub") {
          this.updateSub();
        } else {
          this.updateMul();
        }
      }
    );
  }
  updateNum2(event) {
    this.setState(
      {
        num2: event.target.value
      },
      () => {
        if (this.state.action === "sub") {
          this.updateSub();
        } else {
          this.updateMul();
        }
      }
    );
  }
  updateAction = (action) => {
    this.setState({ action }, () => {
      if (action === "sub") {
        this.updateSub();
      } else {
        this.updateMul();
      }
    });
  };
  updateSub = () => {
    const { num1, num2 } = this.state;
    var subtraction = num1 - num2;
    this.setState({ value: subtraction });
    // return subtraction;
  };

  updateMul = () => {
    const { num1, num2 } = this.state;
    var multiplication = num1 * num2;
    console.log("multiplication", multiplication);
    // return multiplication;
    this.setState({ value: multiplication });
  };

  render() {
    return (

                <button
                  type="button"
                  class="btn btn-light active switch"
                  value="sub"
                  name="invest_type"
                  onClick={() => this.updateAction("sub")}
                  checked
                >
                  Sub{" "}
                </button>
                <button
                  type="button"
                  class="btn btn-light switch"
                  value="mul"
                  name="invest_type"
                  onClick={() => this.updateAction("multi")}
                >
                  Mul
                </button>

                Num1

                  <button
                    type="button"
                    class="btn btn-light active"
                    value={10}
                    onClick={this.updateNum1.bind(this)}
                    checked
                  >
                    10
                  </button>
                  <button
                    type="button"
                    class="btn btn-light"
                    value={15}
                    onClick={this.updateNum1.bind(this)}
                  >
                    15
                  </button>
                  <button
                    type="button"
                    class="btn btn-light"
                    value={20}
                    onClick={this.updateNum1.bind(this)}
                  >
                    20
                  </button>
                  <input
                    type="textbox"
                    className="form-control"
                    placeholder="Custom"
                    value={this.state.num1}
                    onChange={this.updateNum1.bind(this)}
                  />

                  Num2

                    <button
                      type="button"
                      class="btn btn-light active"
                      value={5}
                      onClick={this.updateNum2.bind(this)}
                      checked
                    >
                      5
                    </button>
                    <button
                      type="button"
                      class="btn btn-light "
                      value={10}
                      onClick={this.updateNum2.bind(this)}
                    >
                      10
                    </button>
                    <button
                      type="button"
                      class="btn btn-light "
                      value={15}
                      onClick={this.updateNum2.bind(this)}
                    >
                      15
                    </button>

                    <input
                      type="textbox"
                      className="form-control"
                      placeholder="Custom"
                      value={this.state.num2}
                      onChange={this.updateNum2.bind(this)}
                    />

RESULT

                  will grow to

                    {" "}
                    {this.state.value}

    );
  }
}

export default function App() {
  return (

      <Arithmetic />

  );
}

Here is the demo: https://codesandbox.io/s/async-butterfly-t802s?file=/src/App.js:0-5662


text:
Q: how does jboss load the lnk like http://localhost:8088/plant/app/? I started a jboss (6.x) locally, and can load the app with the lnk
http://localhost:8088/plant/app/
There is war deployed under standalone/deployments/ as plant.war. So, I know the element of "plant" in the lnk refers to this war deployment. However, there is no sub-folder in the war. So, how is "app" is parsed?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can we simplify this absolute value? I am looking to simplify $f(\alpha,\beta)$ shown below and shading the region it represents in 2D plane.
I have that $$\beta-\alpha>0\tag1$$ $$\alpha-1>0\tag2$$
I am trying to simplify
\begin{align}
f(\alpha,\beta)=\big|1-\beta \big|- 2\big|1-\alpha-\beta \big|-\beta-1\leq0
\end{align}
Does anyone know what $f(\alpha,\beta)$ becomes? In other words given (1) and (2), can I tell whether $1-\beta$ and $1-\alpha-\beta $ are $\geq$ or $\leq$ 0?
Thanks.

A: Combine your inequalities (just pass $1$, respectively $\alpha$, on the other side) to get $1<\alpha<\beta$ and note that $0>1-\beta> 1-\beta-\alpha$.

A: Note that $$\beta-\alpha\gt 0,\ \alpha-1\gt 0\Rightarrow  (\beta-\alpha)+(\alpha-1)\gt 0$$
and that
$$\beta\gt\alpha\gt 1\gt 0,\ \alpha-1\gt0\Rightarrow \beta+(\alpha-1)\gt 0.$$


text:
Q: Is it possible to authenticate snowflake users via AD groups? Is it possible to authenticate snowflake AD SSO users via an AD group? I've already got SSO set up & working, but I dont want to have to create a separate snowflake user for every person. There will be 100s.
I want it to work like SQL Server authentication where I can add 100s of users to the same group and create a single login on SQL Server for the group. To revoke login permissions I just remove the user from the group. To give a new person access I just add them to it.
This is about authentication not authorization (mapping a group to a role), though I may want to do that later.

A: You can configure automatic user provisioning in Snowflake with AD.

*

*https://learn.microsoft.com/en-us/azure/active-directory/saas-apps/snowflake-provisioning-tutorial
Capabilities supported:

*

*Create users in Snowflake

*Remove users in Snowflake when they don't require access anymore

*Keep user attributes synchronized between Azure AD and Snowflake

*Provision groups and group memberships in Snowflake

*Allow single sign-on to Snowflake (recommended)


text:
Q: Labeling diagonal arrows with the diagrams package As far as I can tell, the following code
\usepackage[balance,small]{diagrams}

...

\begin{diagram}
&& X && \\
& \ldTo^\Phi & & \rdTo^\Psi &\\
Y &&&& Z
\end{diagram}

should produce a diagram with diagonal arrows and labels which are horizontal (i.e. not slanted with the arrows), at least that's what happens in Milne's documentation (http://www.jmilne.org/not/Mdiagrams.pdf). However my labels (Phi and Psi) are slanted along the arrow.
How do I make it so the labels are horizontal?

A: Including the option [nohug] will make it so that labels do not slant with the arrow. The top line should be:
\usepackage[balance,small,nohug]{diagrams}


text: Q: Is it possible to add different error in Laravel Passport 9? I'd like to add different error in route "/oauth/token" if User's status is active or not. I check the documentation but I don't find anything. Any suggestion? Thanks!


text:
Q: What Does Coordinate Descent Actually Do? Any Intuition Behind Coordinate Descent? We've done a bunch of theoretical stuff in my optimization class, but basically no time for the actual implementation details. I'm trying to get an understanding of coordinate descent, which if I'm understanding it correctly utilizes the Gauss-Sediel method for solving a set of linear equations.
What I'm not getting is WHICH system of linear equations we're solving.
In the case of $f$ being convex, then $\text{min. } f(x) \Leftrightarrow \nabla f(x) = 0$, which leads to a set of equations, but they're only linear when $f$ is quadratic... It gets even worse if we're relaxing some constraint, in particular a convex, separable but nondifferentiable constraint - here we can't lean on the gradient to produce a set of equations, let alone a linear set of equations.
So where does the linear set of equation solving come into the picture? What are the actual computational steps for coordinate descent?

A: What is the Gradient Descent Method?
Let's generalize it by the Steepest Descent Method.
We'll define the Steepest Descent using the following optimization problem:
$$ \arg \min_{ \left\| d \right\|_{p} \leq 1} \left\{ {\nabla f \left( x \right)}^{T} d \right\} $$
If we chose $ p = 2 $ you will get the known Gradient Descent.
The interesting thing happens when you chose $ p = 1 $.
Then the optimal direction (Easily derived form the KKT) is given by:
$$ {d}_{i} = \begin{cases}
-\operatorname{sign} \left( {\nabla f \left( x \right)}_{i} \right) & \text{ if } \left| {\nabla f \left( x \right)}_{i} \right| = \max_{i} \left\{ \left| {\nabla f \left( x \right)}_{i} \right| \right\} \\
0 & \text{ if } \left| {\nabla f \left( x \right)}_{i} \right| \neq \max_{i} \left\{ \left| {\nabla f \left( x \right)}_{i} \right| \right\}
\end{cases} $$
Namely the Steepest Descent in the $ {L}_{1} $ Norm sense is taking the direction which is aligned to coordinate with the steepest slope.
This is basically Coordinate Descent, solve the problem in a direction aligned with single coordinate.
So you can think of Coordinate Descents something like Steepest Decedent in $ {L}_{1} $ Norm.


text:
Q: WSDL binding with both certificate and username/password I've to make a C# dll to use webservices in some applications (as a com object). The server requires an authentification using both certificate and username/password.
I've tried many solutions but none worked so i'm looking for a solution.
My last try was a custom bindng like this :
// Custom binding
CustomBinding binding = new CustomBinding();
var userNameToken = new UserNameSecurityTokenParameters();
userNameToken.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;

var securityElement = new AsymmetricSecurityBindingElement();
securityElement.IncludeTimestamp = true;
securityElement.RecipientTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.SubjectKeyIdentifier, SecurityTokenInclusionMode.Never);
securityElement.InitiatorTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.SubjectKeyIdentifier, SecurityTokenInclusionMode.AlwaysToRecipient);
securityElement.DefaultAlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256;
securityElement.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
securityElement.SetKeyDerivation(false);
securityElement.EndpointSupportingTokenParameters.SignedEncrypted.Add(userNameToken);
securityElement.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.EncryptBeforeSign;
securityElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
binding.Elements.Add(securityElement);

var encodingElement = new TextMessageEncodingBindingElement();
encodingElement.MessageVersion = MessageVersion.Soap12WSAddressingAugust2004;
binding.Elements.Add(encodingElement);

var httpElement = new HttpsTransportBindingElement();
httpElement.UseDefaultWebProxy = true;
binding.Elements.Add(httpElement);

// Create the endpoint address. Note that the machine name
EndpointAddress ea = new EndpointAddress("https://myURL/userservice");

// Create the client.
UserServiceClient sNext = new UserServiceClient(binding, ea);

// Utilisation du WebService
sNext.ClientCredentials.UserName.UserName = "user";
sNext.ClientCredentials.UserName.Password = "pwd";

sNext.ClientCredentials.ClientCertificate.Certificate = autCertificat;
sNext.ClientCredentials.ServiceCertificate.DefaultCertificate = autCertificat;
sNext.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

sNext.MyService();

Thanks for your help.
Matt
Edit :
My C# project contains a Service Reference generating from a WSDL file on a server.
I compile it to make a dll that can be used in Visual FoxPro clients that used the WebServices of the WSDL.
If i go to the URL of the WebServices in a browser, it ask my first a certificate (that i choose from the list) and second i've to enter a user/password : in the browser it works fine.
Now i've to call this Webservices from my DLL but i don't know how to define the binding and the endpoint to have the same authentification process.
Thx

A: I don't believe you can have 2 competing types of ClientCredentials like this.
If you look at the config for this, you will specify one type, not multiple:
<security>
    <message clientCredentialType="Certificate" />
</security>

Or:
<security>
    <message clientCredentialType="UserName" />
</security>

An alternative route you may want to look into is to use TransportWithMessageCredential, which uses an SSL or Trusted certificate to secure the channel and UserName / Password to secure the individual messages, but without further details of it's difficult to advise further.
Here's a question I answered a while ago that may / may not be helpful:
WCF Client Using Certificate and Username/Password credentials?


text:
Q: Firefox extension: open a dynamic extension-local page In my extension (using the add-on SDK), I want to open an extension-local webpage (say, data/templates/page.html) in a tab. The page should be able to call SDK methods. Namely, I want to manipulate some data saved in the local storage and then display them.
In other words, I want a tab that behaves like a panel.
Can I use the tabs module and attach a contentScript to the page (though it's gonna be a rather long script)?.
The tab will be opened when a button is pressed in the navigation toolbar:
btn.addEventListener("click",
    function(e) {
        //open tab here
    });

How can I open such a page?

A: It's not hard, a lot of extensions are doing that:
const tabs = require('sdk/tabs');
const { data} = require('sdk/self');

tabs.open({
  url: data.url('yourpage.html'),
  onReady: function onReady(tab) {
    tab.attach({
      contentScriptFile: data.url('yourcontentscript.js')
    });
  }
});

You can find all the info you need in the tabs documentation on MDN.


text: Q: Logging to a MLflow Server in a Different User Directory Suppose there is a Linux machine with a few users. If a MLFlow tracking server is set up in a users home directory, is it possible to log to this tracking server by running script in a different users home directory? Are there better ways to set up tracking server in more general manner and allow users of Linux machine to log there?


text:
Q: Core Data not persisting: Using magicalrecord Alright,
I'm using Magicalrecord for core data implementation.  My app downloads a bunch of info the first time it is loaded.  That data is then saved to core data.  This is done in the AppDelegate file.  But, whenever my app goes to the background or is terminated the data is lost.  Here is the didFinishLaunching with options method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

NSLog(@"My app is starting");

[MagicalRecord setupAutoMigratingCoreDataStack];

//NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

if (![[NSUserDefaults standardUserDefaults] objectForKey:@"AGM_DataSetup"]) {

    NSError* jsonError;
    NSArray* json;

    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];

    if (internetStatus == NotReachable) {
        NSLog(@"Offline");
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"static" ofType:@"json"];
        NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
        json = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
    } else {
        NSLog(@"Online");
        NSData* data = [NSData dataWithContentsOfURL:
                        aWaterURL];
        json = [NSJSONSerialization
                JSONObjectWithData:data
                options:kNilOptions
                error:&jsonError];
    }

    if (!jsonError) {

        [MagicalRecord cleanUp];
        NSString* folderPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSError *error = nil;
        for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error])
        {
            [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
            if(error)
            {
                NSLog(@"Delete error: %@", error.description);
            }
        }

        [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:@"Anglers411.sqlite"];

        NSLog(@"Initial Data Load");

        for (id jsonArea in json) {

            // Create an area
            Area *area = [Area MR_createEntity];
            area.name  = [jsonArea objectForKey:@"name"];
            area.bulletDescription  = [jsonArea objectForKey:@"bulletDescription"];
            area.uid  = [jsonArea objectForKey:@"id"];

            NSArray* jsonLocations  = [jsonArea objectForKey:@"locations"];

            for (id jsonLocation in jsonLocations) {

                // create a location
                Location *location = [Location MR_createEntity];
                location.uid = [jsonLocation objectForKey:@"id"];
                location.name = [jsonLocation objectForKey:@"name"];
                location.desc = [jsonLocation objectForKey:@"desc"];
                location.directions = [jsonLocation objectForKey:@"directions"];
                location.bulletDescription = [jsonLocation objectForKey:@"bulletDescription"];
                location.area = area;

                NSArray* jsonBugs  = [jsonLocation objectForKey:@"bugs"];

                for (id jsonBug in jsonBugs) {
                    Bug *bug = [Bug MR_createEntity];
                    bug.name = [jsonBug objectForKey:@"name"];
                    bug.spring = [jsonBug objectForKey:@"spring"];
                    bug.summer = [jsonBug objectForKey:@"summer"];
                    bug.fall = [jsonBug objectForKey:@"fall"];
                    bug.winter = [jsonBug objectForKey:@"winter"];
                    bug.location = location;
                }
            }

        }

        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
            if (success) {
                NSLog(@"You successfully saved your context.");
            } else if (error) {
                NSLog(@"Error saving context: %@", error.description);
            }
        }];

        // Set User Default to prevent another preload of data on startup.
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"AGM_DataSetup"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

}
return YES;
}

Here is the method I use in both applicationDidEnterBackground and ApplicationWillTerminate:
- (void)saveContext {
[MagicalRecord cleanUp];

}

Thanks for any help with this.  I have read over every magicalrecord non-persist question on here and haven't found anything that worked.
Take Care,
Ben

A: Sorry,
After further exploration, I see that it is generally not going to work to set up 2 core data stacks with different names, if you want them to be the same stack...  I have corrected this.


text:
Q: What can cause a 'Could not find the main class' when packaging a jar? I'm participating in an open source project, where I've got my own repo for the modification I'm working on.
I've added new features over the last couple of months while always testing the functionalities from within eclipse. Now that everything is ready, I wanted to make a release, built the windows installer with the ant script which always produced a working installer, but after installation, when launching the application a information window with this message is being displayed right away.
Java Virtual Machine Launcher
Could not find the main class: net.pms.PMS.  Program will exit.
OK
I can't figure out what change has been made to break the packaging.
Some facts:

*

*To build the installer, an ANT script calling two NSIS scipts is being
used. It's the ANT script which is packaging the jar. These scripts haven't changed between the two versions. The manifest for the main method (net.pms.PMS) is being set in the ANT script.

*Quite a big amount of code has changed between the two versions; as the main class not found error is being shown right away when starting the application I tend to think neither the changed code nor changed imports for jars can provoke that!?

*The class files containg the main class are included in the package and I promise PMS.java contains a main method

*It doesn't matter how the application is being started; exe launcher, batch file or command line, the main class not found always shows up.

*I had installed the jdk7. As it might have been conflicting with jdk6, I've uninstalled everyting related to 7 and currently run jdk6_29

*A plugin system is available in the application, where plugins get loaded from a folder dynamically on runtime ExternalFactory. The way this being done has changed quite a bit. Again, as it is during runtime, I can't imagine something in there could provoke the problem.

*I can't find any information either in the windows event log, haven't found any java logs and the application logs obviously aren't initialized at all.

I'm currently clueless what change I've made provokes this main class not found error. I'd be really grateful if someone could point me into the right direction with some clues where I could get some useful information from or what is actually going on.
Thanks, Philippe
[edit] Some additions related to the posted comments:
Contents of MANIFEST.MF:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.2
Created-By: 1.6.0_29-b11 (Sun Microsystems Inc.)
Main-Class: net.pms.PMS
How is the application started:
If launched with the batch: javaw -Xmx768M -Djava.net.preferIPv4Stack=true -Dfile.encoding=UTF-8 -classpath update.jar;pms.jar net.pms.PMS
exe generated with NSIS: -classpath update.jar;pms.jar -Xmx1024M -Dsun.java2d.d3d=false -Djava.net.preferIPv4Stack=true -Dfile.encoding=UTF-8 ${CLASS} $1
When trying to launch it with 'java -cp pms.jar net.pms.PMS' an intersting stack trace shows up
C:\Program Files (x86)\PS3 Media Server MLX>java -cp pms.jar net.pms.PMS
Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for Manifest main attributes
        at sun.security.util.SignatureFileVerifier.processImpl(Unknown Source)
        at sun.security.util.SignatureFileVerifier.process(Unknown Source)
        at java.util.jar.JarVerifier.processEntry(Unknown Source)
        at java.util.jar.JarVerifier.update(Unknown Source)
        at java.util.jar.JarFile.initializeVerifier(Unknown Source)
        at java.util.jar.JarFile.getInputStream(Unknown Source)
        at sun.misc.JarIndex.getJarIndex(Unknown Source)
        at sun.misc.URLClassPath$JarLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.misc.URLClassPath$JarLoader.ensureOpen(Unknown Source)
        at sun.misc.URLClassPath$JarLoader.(Unknown Source)
        at sun.misc.URLClassPath$3.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.misc.URLClassPath.getLoader(Unknown Source)
        at sun.misc.URLClassPath.getLoader(Unknown Source)
        at sun.misc.URLClassPath.getResource(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: net.pms.PMS.  Program will exit.

A: Okay, I will walk you through the process I went through to analyse the issue:

*

*I took you jar and tried to run it via java -jar pms.jar. Indeed, that failed with the above mentioned error messages.

*I created a quick test class in your package that simply prints a message to system.out and put it in the jar file in the folder net.pms.

*I manually changed the Main-Class attribute in the Manifest to call that class (thus: net.pms.Test).

*I re-ran java -jar pms.jar and got the same error messages.

*I deleted all additional folders from the root of the jar and re-ran java -jar pms.jar. It yielded the same error messages.

*I deleted all the additional folders from META-INF and re-ran java -jar pms.jar. It still yielded the same error messages.

*I deleted all additional files from META-INF and re-ran java -jar pms.jar. The application worked fine.

*I started with a fresh copy of the jar, deleted only all additional files from META-INF and re-ran java -jar pms.jar. The application worked fine.

*I started with a fresh copy of the jar and one by one, I deleted the additional files from META-INF, re-running java -jar pms.jar as I went along. This gave me the following results:

If your META-INF directory contains either one of the files NB_IDE.DSA or NB_IDE.SF, the main class of your application cannot be found by Java. It appears that the information in those files somehow influences the location mechanism of the classloader.
I had a look at the files and it seems that it is some Netbeans specific information file. Google did not really give me any results on this, neither did my network of colleagues have any clues on it. At this point, I would usually ask StackOverflow for help, but seeing that the files only concern Netbeans dependency information, I assume that the files are only used in your IDE. Also, since this is information that is needed at build time, but not at runtime, I assume that it is safe to remove the files from your final release jar.
All you have to do now is exclude the files from the final build through your build.xml. I'll leave this up to you, as there is plenty of documentation on Ant on the internet. :)
Now, why did I go through this in so much detail?
Well, this is the typical process that I follow if I am facing a problem like this. First, I exclude all interfering parameters to pinpoint the problem. Then, I analyze the result - potentially using the internet to clarify points that I am not familiar with - to not resolve the symptoms but the cause. Then I eliminate the cause.
Personally, I think that this process is a great tool in every developers toolbox to quickly resolve issues like the one you were facing. I hope that you can re-use it sometime in the future and don't have to wait days and days for my lazy-ass to finally have a look at it. :)
Good luck with your software!

A: Have you ever run the built package before?  On the same machine?  Did you run it from a command line, or try to?
Are you currently running it by a double-click?  I guess we'll assume you're in Windows, since you use WinRAR.
You are focusing on a supposed "change ... made to break the packaging"; how sure are you that your environment is set up properly for running the program?  You don't list details of libraries, directories, etc. that are necessary.
You show us that the class is in the jar file, but you don't show us what path it is on.  And I agree the manifest would be useful.
If we really are looking at an ant problem, you might tag this question for Ant.

A: Well, first of all, I assume that the MANIFEST.MF is located in the META-INF folder - otherwise you would have probably found a solution through google a long time ago. :)
What you say is that you promise that PMS.java contains a main class [sic].
Unless you made a typo there and you actually mean main 'method', I guess that you have an inner class that you would like to serve as the main entry point for your application. The jar structure in your post gives us further evidence to this, since it shows us that there are indeed multiple inner classes in your main class.
I must say that it is a pretty weird construct to start your application through an inner class and quite frankly, I am not sure whether this is even possible or not. I would strongly suggest you move the main method into PMS.java directly.
If you really, really want to use an inner class as the entry point, try something like this as the Main-Class property in your manifest:

Main-Class: net.pms.PMS$1

Where $1 is the class that actually contains the main method.
Again, since I don't know whether your inner classes require an instance of the outer class and whether Java actually supports inner classes as starting point for your application, this might not work at all. My advice still is to move the main method up into PMS.java.
Good luck!

A: Alright, I think I know what might be going on: the commands you are using for running the application do indeed place your jar file on the classpath, but they do not tell Java where to find the main class!

javaw -Xmx768M -Djava.net.preferIPv4Stack=true -Dfile.encoding=UTF-8 -classpath update.jar;pms.jar net.pms.PMS

This tells Java to use pms.jar in the classpath and to go to the folder net/pms in the current structure to run a class PMS.
Try the simple:

java -jar pms.jar

as suggested by AlexR, please and let us know what that shows you...


text:
Q: Issues with Flyway(6.5.7) and Spring Boot 2.5.x? We are using Flyway 6.5.7 and we are trying to upgrade from Spring Boot 2.4.13 to Spring Boot 2.5.x. Application is built with Gradle 7.2.
Before the Spring Boot upgrade everything works fine, but after it bean creation fails with this error when starting the application:
Failed to instantiate [org.flywaydb.core.Flyway]: Factory method 'flyway' threw exception; nested exception is java.lang.IllegalArgumentException: Name must not be null", "level":"WARN","thread":"main","logClass":"o.s.c.s.AbstractApplicationContext","logMethod":"refresh"}

If we disable Flyway the application starts fine with Spring Boot 2.5.x.
And if we switch back to a Spring Boot version earlier than 2.5.x and activate Flyway again it works fine...
So whats up with Flyway and Spring Boot 2.5.x?


text:
Q: Find string in cell array with elements of different types I have a function that takes variadic arguments. These arguments are parameter-value pairs, so varargin is a cell array in which every odd-indexed element is a string (the parameter), but the even-indexed elements can be a string, number, or cell array of strings. I want to find the index of a particular string in varargin. I have a working solution, but it uses arrayfun twice; is there a cleaner/faster/more effective way of find a string in such a cell array? The resulting index will be used to remove that element and the following one from varargin. I would like to minimize creation of new variables.
str_to_find = 'paramX'
finds = arrayfun(@(i) strfind(varargin{i},str_to_find), 1:length(varargin), 'UniformOutput', 0);
finds2 = arrayfun(@(i) ~iscell(finds{i}) && ~isempty(finds{i}), 1:length(finds));
index = find(finds2==1);

varargin(index)=[];
varargin(index)=[];

Given varargin is {'paramA', 'valueA', 'paramB', 9, 'paramX', {'z','x','c'}, then finds is [] [] [] [] [1] {1x3 cell}, finds2 is 0 0 0 0 1 0, and index is 5. So, my solution does what I need, but it just seems ugly. I would just use finds2 (i.e., not create index) to delete that element from varargin, but I also need to remove the one after it.

A: You can use the built-in function strcmp which should be fairly fast:
idx  = strcmp(str_to_find, varargin);

and that will give you an index to all cell elements that are strings matching the target.
Then, for pruning those elements, you can use
varargin( or(idx, [0 idx(1:end-1)]) ) = [];

assuming that idx is a row array.
Finally, you may also want to run some format checks to make sure that the user has not entered argument-pairs in the wrong order (or with an argument name that matches the parameter name) otherwise this kind of code will behave strangely.

A: What about trying this:
index  = find(strcmp(str_to_find, varargin));

This should give the index of 'parameter' and adding one to it will get the index of its 'value'


text:
Q: Always sort NULL as empty string or 0 I am trying to make all queries in our system ORDER BY with NULL and empty strings being equal (only in ORDER BY). I solved this by adding IFNULL(field, "") to all GROUP BY fields.
Now the problem is that if a field type is numeric, then the field is converted to a String which will sort 100 before 20 because its alphabetical, not by number. If I change "" to 0, it casts everything to an int and that makes the sorting by on varchar fields go wrong.
Is there a universal way that I can say "if it is NULL, treat it as an empty string on ORDER BY"? Or maybe, "if the field type is a string, use this function"? In this simple example i could switch the secondary value depending on the field but I am looking for a more global solution.
Example table data:
---------------
|id|person|age|
|1 |Zzz   |100|
|2 |      |0  |
|3 |NULL  |2  |
|4 |      |2  |
---------------

Some examples:
//correct results
SELECT * FROM test ORDER BY IFNULL(`person`, ""), id ASC;
//null and empty strings not sorted properly
SELECT * FROM test ORDER BY IFNULL(`person`, 0), id ASC;

//correct results
SELECT * FROM test ORDER BY IFNULL(`age`, 0), id ASC;
//100 is turned to a string and therefor appears above 2
SELECT * FROM test ORDER BY IFNULL(`age`, ""), id ASC;

A: I'm pretty sure there is no magic option to do what you want.
However, you might consider using DEFAULT values in your CREATE TABLE statements, so avoid NULL values -- just set the default to 0 or '' depending on the data type.

A: Well if anyone happens upon this post, it seams the best way to go about this is to use NULLIF instead of IFNULL to convert all NULL values to empty strings.
This will only work when you are dealing with strings and not NULL numbers though.


text:
Q: Trying to Rails.cache.delete_matched from the runner On redmine 1.2/rails 2.3.11 I'm rendering a repository markdown file as html (as redmine_markdown_extra_viewer does), and now I'am trying to cache the result, which should be updated on each commit.
So I have a git hook that fetch the repo changes, and i'd like it to also clear the corresponding cache entries.
Cache generation (in a RepositoriesController::entry override):
cache_key =['repositories_md', @project.id.to_s, @path.to_s].join('/')
puts cache_key
@content = cache_store.fetch cache_key do
   Kramdown::Document.new(@repository.cat(@path, @rev)).to_html
end
render :action => "entry_markdown"

The hook that should clear the cache, but has no effect:
# This is ok
ruby script/runner "Repository.fetch_changesets"

# This not
ruby script/runner "Rails.cache.delete_matched(/repositories_md\/.*/)"

So it doesn't work and i don't even know if i've taken the right direction to implement that. Any input much appreciated!

A: Which cache backend are you using?
If it's memcached or anything other than the FileStore or the MemoryStore, the delete_matched method is not supported.
You're probably better off letting them expire and just replace their cached contents as they get updated.

A: The problem is when using a Regular Expression as a fragment name, try using a String as a fragment name. Maybe get verbose. I had a similar problem with Dalli(with Memcached), and that was the reason.


text:
Q: Vue md-able not sorting Timestap I am trying to sort a timestamp column and a column that contains an array using Vue.js. Please use the following link to review the: demo code.
I want to sort the columns with the names: pos and Timestamp. Is there a default function that may be called to do this? If not, how is this possible?

A: You can use the object.sort() method to achieve what you want. I have updated your code here: UPDATED SANDBOX
Following changes have been made to your code:
a toggles property in the data method:
toggles: {
    t: false,
    /* you can add all property keys here, which you wish to sort */
},

and toggleSort method:
toggleSort(property) {
  /* get toggle status for the property */
  const alreadyToggled = this.toggles[property];

  /* sort users array accordingly */
  this.users.sort((a, b) =>
    alreadyToggled ? a[property] > b[property] : a[property] < b[property]
  );

  /* update toggle status for the property */
  this.toggles[property] = !alreadyToggled;
}

then on @click you can toggle on the basis of your desired property:
<Button @click="toggleSort('t')">
  Sort Timestamp {{ toggles['t'] ? "Asc" : "Desc" }}
</Button>

For sorting t, you can use @click('t'), for pos property, you can use @click('pos'). So on and so forth. Just make sure, you add all these keys to be sorted in the toggles object as well.


text:
Q: Compiling a C library into a DLL with MinGW I'm trying to use the librsync library in my java program trough the JNA. For this i need to be able to compile the librsync library into a dll. I know how to compile a single c file into a dll using MinGW and for this i have found lots of examples but i'm at a loss on how to do it for a large library like librsync. Is this even possible?
Thanks in advance,
Frank

A: I don't know anything specific about librsync, but you should be able to use ld or gcc --shared as normal. However, when you try to build big libraries with lots of dependencies it is ofen very much simpler if you can use the existing Makefile, and only make small modifications to it.
So your first step would be to see that it builds under MinGW as it is, then go ahead and try to modify the Makefile to make a dll

A: What you can do is

*

*Create your own .def file exporting the various rs* functions you need from librsync: Source

*Run dlltool and then gcc to generate the .dll file you need: Source


text:
Q: Trying to assign a functions return value to a variable I have a script that checks whether the value of a selected element equals the span id. Everything works fine except for the variable assignment.
To be more precise: The function itself works (if i alert object.id it is displayed right) but the variable assignment doesn't. If I try to alert the variable, it says it's undefined. I'm sure it's some minor mistake and it would be very nice if someone could point it out:
var spanId = (function getId(object)
    {
    return object.id;
    //alert(object.id);
    })();

A: Setting the variable will not update that variable when you call it again and again. You need to restructure your code in order to update that variable.
var spanId;
function getId(object) {
    spanId = object.id;
};

now spanId will have the current value.


text:
Q: Traceback (most recent call last): UnboundLocalError: local variable referenced before assignment why am I getting mentioned error? Is there any better way to do this?
def a():
  t = 0
  def b():
    t+=1
    return
  b()
  print(t)
a()

A: You can use the nonlocal statement which will bind access to the t variable from a function.
Though, I wouldn't use that approach unless required.
def a():
    t = 0
    def b():
        nonlocal t
        t += 1
        return
    b()
    print(t)
a()

More information can be found here:
Python nested functions variable scoping


text:
Q: Best way to fix pandas DataFrame with some cell values in wrong columns I have a pandas DataFrame where some cells are in wrong columns. It looks like this:

City
River
Price
Car

NY
Hudzon
Low
VW

LA
Yukon
High
Tesla

LasVegas
Low
Hudzon
VW

Low
NY
Tesla
Yukon

I have enumared lists of all possible values in City, River, Price and Car columns.
What is the best way to fix this dataset and put all values in right columns in pandas ?
Upd:
That is the code, I have created and that worked for me:
x = pd.DataFrame({'name':['andrew', 'karl', 'jhon', 'jack', 'bob', 'high'], 'education': ['high', 'middle', 'lviv', 'high', 'elementary', 'kyiv'], 'city':['lviv', 'kyiv', 'elementary', 'kharkiv', 'kyiv', 'mike']})

ydata = pd.DataFrame(x)

fdict = {}
fdict['name'] = ['andrew', 'karl', 'jhon', 'jack', 'bob', 'mike']
fdict['education'] = ['high', 'middle', 'elementary']
fdict['city'] = ['lviv', 'kyiv', 'kharkiv']

filter = {}
for key in fdict:
    filter[key] = {}

for key1 in fdict:
    regexx = '|'.join(fdict[key1])
    for key2 in fdict:
        filter[key2][key1] = ydata[key2].str.contains(regexx, regex=True, na=False)

indata = {}
for key in fdict:
    indata[key] = {}

for key1 in fdict:
    for key2 in fdict:
        if key1 != key2:
            indata[key1][key2] = ydata.loc[filter[key1][key2], key1]

for key in fdict:
    fn = ~filter[key][key]
    ydata.loc[fn, key] = np.nan

for key1 in fdict:
    for key2 in fdict:
        if key1 != key2:
            ydata.loc[filter[key1][key2], key2] = indata[key1][key2]

A: That is the code, I have created and that worked for me:
x = pd.DataFrame({'name':['andrew', 'karl', 'jhon', 'jack', 'bob', 'high'], 'education': ['high', 'middle', 'lviv', 'high', 'elementary', 'kyiv'], 'city':['lviv', 'kyiv', 'elementary', 'kharkiv', 'kyiv', 'mike']})

ydata = pd.DataFrame(x)

fdict = {}
fdict['name'] = ['andrew', 'karl', 'jhon', 'jack', 'bob', 'mike']
fdict['education'] = ['high', 'middle', 'elementary']
fdict['city'] = ['lviv', 'kyiv', 'kharkiv']

filter = {}
for key in fdict:
    filter[key] = {}

for key1 in fdict:
    regexx = '|'.join(fdict[key1])
    for key2 in fdict:
        filter[key2][key1] = ydata[key2].str.contains(regexx, regex=True, na=False)

indata = {}
for key in fdict:
    indata[key] = {}

for key1 in fdict:
    for key2 in fdict:
        if key1 != key2:
            indata[key1][key2] = ydata.loc[filter[key1][key2], key1]

for key in fdict:
    fn = ~filter[key][key]
    ydata.loc[fn, key] = np.nan

for key1 in fdict:
    for key2 in fdict:
        if key1 != key2:
            ydata.loc[filter[key1][key2], key2] = indata[key1][key2]

A: other solution:
cols_list = []
for col in ydata.columns:
  ydata[col] = ydata[col].apply(lambda x: {key: x for key in fdict.keys() if x in fdict[key]})
ydata_list = ydata.to_dict('split')['data']

# dataset reconstraction
update_ydata_list = []
for y in ydata_list:
  temp_dict = {}
  for d in y:
      temp_dict.update(d)
  update_ydata_list.append(temp_dict.copy())

# final result
pd.DataFrame(update_ydata_list)

you can test it on the full dataset


text:
Q: Custom URL shortcuts in Google Chrome with multiple arguments?
Possible Duplicate:
Multiple parameter keyword searches in firefox (or chrome)

I'm trying to create a shortcut for Google Chrome that will allow me to type "w de foosball" in the Chrome Omnibox, and have it open the URL http://de.wikipedia.org/w/index.php?search=foosball.
What I'd ideally like to do is create a custom web search engine like so:
Name:      My wiki search
Shortcut:  w
URL:       http://%1.wikipedia.org/w/index.php?search=%2

But Chrome only allows one argument for custom search engines ("%s"), so I'm looking for some other way to accomplish this.
This would be really helpful for a couple of internal websites, which are of the form "https://a-b-c.company.com", where "a", "b" and "c" vary across different applications, and the number of possible combinations is in the thousands.
I've looked for Chrome plugins that will do this, tried using OS X app launchers like Spotlight, Quicksilver and Alfred, tried downloading plugins for said app launchers... and found nothing. It seems like I either need to roll my own Chrome Extension, or use javascript via a bookmark somehow. But am I really the first person that's tried to do this?


text:
Q: How to return the results from a summary function? I made a ggplot, I would like to use the results from a function.
How can I return the result of stat_summary_2d?
ggplot(diamonds, aes(carat, depth, z = price))+
  stat_summary_2d(fun =function(x)mean(x))

A: If you are asking how to re-use ggplot2's implementation of the statistics summary function, it is currently not easily feasible with the public API. You can have a look at ggplot2's internals and copy-paste the parts you need. But this should be seen as a non-robust hack which may break after any package upgrade.
The core function of bin2d is accessible in ggplot2::StatBin2d$compute_group. But to call it, you will need some of the plot's components which are not easy to construct by hand.
In another answer, I had listed all the steps done when building a graph in a typical case. Function ggplot2:::ggplot_build.ggplot will show you the details. The relevant line calling the statistics computation is
data <- by_layer(function(l, d) l$compute_statistic(d, layout))

You'll need to execute all previous steps before starting it. On your example, it would finally give:
# A tibble: 238 x 9
    xbin  ybin value     x width     y height PANEL group
   <int> <int> <dbl> <dbl> <dbl> <dbl>  <dbl> <fct> <int>
 1     6     1 4206  1.04  0.160  42.6   1.20 1        -1
 2     6     2 4032  1.04  0.160  43.8   1.20 1        -1
 3     1     8  945  0.240 0.160  51.0   1.2  1        -1
 4     8     8 6727  1.36  0.160  51.0   1.2  1        -1
 5     2     9 1166  0.401 0.160  52.2   1.20 1        -1
 6     3     9 1293  0.561 0.160  52.2   1.20 1        -1
 7     4     9 1895  0.722 0.160  52.2   1.20 1        -1
 8     2    10 1012. 0.401 0.160  53.4   1.2  1        -1
 9     4    10 2164  0.722 0.160  53.4   1.2  1        -1
10     5    10 2815  0.882 0.160  53.4   1.2  1        -1
# ... with 228 more rows

Trick: internal functions of a package can be accessed with triple colon pkg:::fun.

A: Find a solution here:
p<- ggplot(diamonds, aes(carat, depth, z = price))+
       stat_summary_2d(fun =function(x)mean(x))

library('Hmisc')
ggplot_build(p)$data[[1]]

fill   xbin ybin value          x         y  PANEL group   xmin       xmax
#1F4364 6   1   4206.0000   1.0421667   42.6    1   -1  0.9620000   1.1223333
#1F4262 6   2   4032.0000   1.0421667   43.8    1   -1  0.9620000   1.1223333
#142E47 1   8   945.0000    0.2405000   51.0    1   -1  0.1603333   0.3206667
#28557B 8   8   6727.0000   1.3628333   51.0    1   -1  1.2826667   1.4430000
#152F49 2   9   1166.0000   0.4008333   52.2    1   -1  0.3206667   0.4810000
#15304A 3   9   1293.0000   0.5611667   52.2    1   -1  0.4810000   0.6413333
#17344F 4   9   1895.0000   0.7215000   52.2    1   -1  0.6413333   0.8016667
#152E47 2   10  1011.5000   0.4008333   53.4    1   -1  0.3206667   0.4810000
#183651 4   10  2164.0000   0.7215000   53.4    1   -1  0.6413333   0.8016667
#1B3A57 5   10  2815.0000   0.8818333   53.4    1   -1  0.8016667   0.9620000


text:
Q: Using CipherInputStream with Sockets I am encountering an issue when using CipherInputStream over a network connection. I have read a few questions and articles on this and experimented based on their contents but to no avail. I have created a stripped down example of my issue in the hope that someone can point me in the right direction.
My example contains two executable classes:

*

*EchoSocketTest – This is a simple server application that listens on
a port echos back to the sender whatever it receives

*EchoClientTest – This is a simple client. It preforms 3 tests
Test 1. Creates a connection to the echo server, sends a piece of data and displays what it gets back.
Test 2. Creates a connection to the echo server but uses CipherOutputStream to encrypt the data it
sends. It sends a piece of data and displays what it gets back.
Test 3. The same as Test 2 however it tries to use CipherInputStream to decrypt the data.
In my example test 1 and test 2 preform perfectly and give the correct output. However test 3 fails and the message "Error nothing read from socket" is displayed.
I have verified that the encrypt and decrypt parts work by creating another test that uses a FileInputStream and that works as expected. I have a feeling the problem is something to do with padding but I have experimented with various options suggested online.
Code and example output follows:
EchoSocketTest:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoSocketTest {

    public static class Connection extends Thread {
        Socket m_Sock = null;
        PrintWriter m_out = null;
        BufferedReader m_in = null;
        public Connection(Socket p_Sock) throws Exception {
            m_Sock = p_Sock;
            System.out.println("Connection accepted");
            m_out = new PrintWriter(m_Sock.getOutputStream(), true);
            InputStreamReader isr;
            m_in = new BufferedReader(new InputStreamReader(m_Sock.getInputStream(),"UTF-8"));
        }
        @Override
        public void run() {
            try {
                char buf[];
                while (true) {
                    String inputLine = "";
                    while (m_in.ready()) {
                        int i = m_in.read();
                        m_out.write(i);
                        inputLine += (char)i;
                    }
                    if (inputLine.length()>0) {
                        System.out.println(inputLine);
                        m_out.flush();
                        inputLine = "";
                    };
                }
                //System.out.println("Connection closed");
            } catch (Exception e) {
                System.out.println("Connection Exception:");
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println("Echo Socket accepting connections on port 1423");
            ServerSocket sSock = new ServerSocket(1423);
            while (true) {
                Connection c = new Connection(sSock.accept());
                c.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

EchoClientTest:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EchoClientTest {

    public static void main(String[] args) {
        try {
            byte[] keyB = {
                    (byte)0x2C, (byte)0xCF, (byte)0xBC, (byte)0x81, (byte)0x99, (byte)0xB7, (byte)0x37, (byte)0x84,
                    (byte)0xD1, (byte)0x09, (byte)0x44, (byte)0x4F, (byte)0xB6, (byte)0x66, (byte)0x69, (byte)0x1F,
                    (byte)0x17, (byte)0x61, (byte)0xAD, (byte)0xD7, (byte)0x43, (byte)0x0E, (byte)0x80, (byte)0x6C
            };
            byte[] ivB = {
                    (byte)0x7B, (byte)0x9B, (byte)0x5F, (byte)0x36, (byte)0xC9, (byte)0x26, (byte)0xE9, (byte)0x5E
            };

            {
                Socket echoSocket = new Socket("127.0.0.1",1423);
                System.out.println("Connected");

                System.out.println("Setting up - Unencrypted version");
                OutputStream oS = echoSocket.getOutputStream();
                DataOutputStream doS = new DataOutputStream(oS);
                InputStream iS = echoSocket.getInputStream();
                InputStreamReader iSR = new InputStreamReader(iS,"UTF-8");
                BufferedReader bR = new BufferedReader(iSR);

                System.out.println("Writing Unencrypted output");
                doS.write("Test Message\n".getBytes("UTF-8"));
                doS.flush();

                System.out.println("Waiting 1 second");
                Thread.sleep(1000);

                System.out.println("Reading data from socket");

                String inputLine = "";
                while (bR.ready()) {
                    int i = bR.read();
                    inputLine += (char)i;
                }
                if (inputLine.length()==0) {
                    System.out.println("Error nothing read from socket");
                } else {
                    System.out.println("Recieved:" + inputLine);
                    inputLine = "";
                };

                System.out.println("Closing Socket");
                echoSocket.close();
            }
            System.out.println("Repeating but encrypting the data SENT on the socket");
            {
                Socket echoSocket = new Socket("127.0.0.1",1423);
                System.out.println("Connected");

                System.out.println("Setting up Ciphers");
                String Algo = "DESede"; //DES or DESede

                final SecretKey key = new SecretKeySpec(keyB, Algo);
                final IvParameterSpec iv = new IvParameterSpec(ivB);
                final Cipher cipherEncrypt = Cipher.getInstance("DESede/CFB8/NoPadding");
                cipherEncrypt.init(Cipher.ENCRYPT_MODE, key, iv);

                System.out.println("Setting up - Encrypted version");
                OutputStream oS = echoSocket.getOutputStream();
                CipherOutputStream cipherOutputS = new CipherOutputStream(oS,cipherEncrypt);
                DataOutputStream doS = new DataOutputStream(cipherOutputS);
                InputStream iS = echoSocket.getInputStream();
                InputStreamReader iSR = new InputStreamReader(iS,"UTF-8");
                BufferedReader bR = new BufferedReader(iSR);

                System.out.println("Writing Encrypted output");
                doS.write("Test Message\n".getBytes("UTF-8"));
                doS.flush();

                System.out.println("Waiting 1 second");
                Thread.sleep(1000);

                System.out.println("Reading data from socket");

                String inputLine = "";
                while (bR.ready()) {
                    int i = bR.read();
                    inputLine += (char)i;
                }
                if (inputLine.length()==0) {
                    System.out.println("Error nothing read from socket");
                } else {
                    System.out.println("Recieved:" + inputLine);
                    inputLine = "";
                };

                System.out.println("Closing Socket");
                echoSocket.close();
            }
            System.out.println("Repeating but encrypting the data SENT and decrypting RECIEVED on the socket");
            {
                Socket echoSocket = new Socket("127.0.0.1",1423);
                System.out.println("Connected");

                System.out.println("Setting up Ciphers");
                String Algo = "DESede"; //DES or DESede

                final SecretKey key = new SecretKeySpec(keyB, "DESede");
                final IvParameterSpec iv = new IvParameterSpec(ivB);
                final Cipher cipherEncrypt = Cipher.getInstance("DESede/CFB8/NoPadding");
                final Cipher cipherDecrypt = Cipher.getInstance("DESede/CFB8/NoPadding");
                cipherEncrypt.init(Cipher.ENCRYPT_MODE, key, iv);
                cipherDecrypt.init(Cipher.DECRYPT_MODE, key, iv);

                System.out.println("Setting up - Encrypted version");
                OutputStream oS = echoSocket.getOutputStream();
                CipherOutputStream cipherOutputS = new CipherOutputStream(oS,cipherEncrypt);
                DataOutputStream doS = new DataOutputStream(cipherOutputS);
                InputStream iS = echoSocket.getInputStream();
                CipherInputStream cipherInputS =  new CipherInputStream(iS,cipherDecrypt);
                InputStreamReader iSR = new InputStreamReader(cipherInputS,"UTF-8");
                BufferedReader bR = new BufferedReader(iSR);

                System.out.println("Writing Encrypted output");
                doS.write("Test Message\n".getBytes("UTF-8"));
                doS.flush();

                System.out.println("Waiting 1 second");
                Thread.sleep(1000);

                System.out.println("Reading data from socket (and Decrtpying)");

                String inputLine = "";
                while (bR.ready()) {
                    int i = bR.read();
                    inputLine += (char)i;
                }
                if (inputLine.length()==0) {
                    System.out.println("Error nothing read from socket");
                } else {
                    System.out.println("Recieved:" + inputLine);
                    inputLine = "";
                };

                System.out.println("Closing Socket");
                echoSocket.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Example Client Output:
Connected
Setting up - Unencrypted version
Writing Unencrypted output
Waiting 1 second
Reading data from socket
Recieved:Test Message

Closing Socket
Repeating but encrypting the data SENT on the socket
Connected
Setting up Ciphers
Setting up - Encrypted version
Writing Encrypted output
Waiting 1 second
Reading data from socket
Recieved:?Ip?????9?m?
Closing Socket
Repeating but encrypting the data SENT and decrypting RECIEVED on the socket
Connected
Setting up Ciphers
Setting up - Encrypted version
Writing Encrypted output
Waiting 1 second
Reading data from socket (and Decrtpying)
Error nothing read from socket
Closing Socket

Note: I have a situation where TLS and certificates are not applicable. If it were possible I would of course use https rather than this method.


text:
Q: sending updated value to API with useState I have an API that gets count. whenever user clicks on IconButton I must send the count to my server, but it always sends previous value. like if count is 1 it sends 0.
  const { fetchCalculatedService, response } = useCalcService();
  const [count, setCount] = React.useState(0);

 <IconButton
          color="success"
          disabled={!selectInsurance}
          onClick={() => {
            setCount((prev) => prev + 1);
            fetchCalculatedService(
              Date,
              Id,
              filter,
              Time,
              count
            );
          }}
        >
          <ArrowUpward />
 </IconButton>

I logged my response and my count as well. the count is the lastest count and everthing is ok but API response shows 0 in count.
I also looked at server logs. API receives 0
shouldn't it get latest value of count whenever I call it? because value updated before fetchCalculatedService invoke

A: The solution to this is to perform the fetch inside the prev callback of your state update function. Since react states are being updated async, it count is not guaranteed to update immediately after setCount.
By fetching inside that callback you can manually raise your count variable.
<IconButton
  color="success"
  disabled={!selectInsurance}
  onClick={() => {
    setCount((prev) => {
      fetchCalculatedService(Date, Id, filter, Time, prev + 1);
      return prev + 1;
    });
  }}
>
  <ArrowUpward />
</IconButton>

A: I think that's because your count state changed but component is not rerendered yet
you can handle it in this way :
 onClick={() => {
        setCount((prev) => {
          fetchCalculatedService(
            Date,
            Id,
            filter,
            Time,
            prev + 1
          );
          return prev + 1
        });

      }}


text:
Q: How to dump and restore correctly a postgresql db from docker I stuck with this error when trying to backup and restore my database from a docker django app environment :

I first did this command to backup my whole DB
docker exec -t project_final-db-1 pg_dumpall -c -U fred2020 > ./db/dump.sql

And then trying to restory with this command
cat dump.sql | docker exec -i --user fred2020 catsitting-db-1 psql -U fred2020 -d postgres

I have two containers, one for my django app named catsitting-web-1 and one for my postgresql named catsitting-db-1.
I don't understand why it gaves me that error, my db user is the same that I specified on the Dockerfile.
Any clue ?
For purpose help, here is my docker files configuration :
Dockerfile
FROM python:3.9
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
RUN pip install Pillow
COPY . /code/

docker-compose.yml
version: "3.9"

services:
    db:
    image: postgres
    environment:
        - POSTGRES_DB=postgres
        - POSTGRES_USER=fred2020
        - POSTGRES_PASSWORD=p*******DD
    expose:
        - "5432"
    ports:
        - 5432:5432
    web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
        - .:/code
    ports:
        - "8000:8000"
    depends_on:
        - db

requirements.txt
Django>=3.0,<4.0
psycopg2-binary>=2.8
Pillow==8.1.0

And that's my process to migrate from laptop1 to laptop2 :
Installation
Run a command line go into a root directory and run:
git clone https://github.com/XXXXXXXXXXXXXXXX

In the command line go into the root directory:
cd catsitting

In the same command line window, run:
docker-compose build --no-cache

In the command line window you need first to migrate the database for Django, run :
docker-compose run web python manage.py migrate

In the command line window then you need to apply the migrations, run :
docker-compose run web python manage.py makemigrations

In the command line window then you need to import database, run :
cat dump.sql | docker exec -i --user fred2020 catsitting-db-1 psql -U fred2020 -d postgres

(for dumping my DB I used docker exec -t project_final-db-1 pg_dumpall -c -U fred2020 > ./db/dump.sql)
You can now run:
docker-compose up

Is there something I get wrong ?

A: I solved !
It was a problem in misconfiguration in the pg_hba.conf inside my docker postgresql
I changed the value from scram-sha-256 to md5 and it works now I can display my webapp with the current db !!
Do you know how to specifie md5 when I build my docker environnement ? by default it puts scram-sha-256

A: Do you know why when I restore my dump in the new environnement by default in the container the pg_hba.conf set the authentification methode to scram-sha-256 and to do my connection working I need to edit that file and to put the authentification method set to md5 ?
# TYPE  DATABASE        USER        ADDRESS     METHOD
local   all             all                     md5

A: Ok sorry folks I found the solution.
I've put that line in my docker-compose.yml:
environment:
- POSTGRES_HOST_AUTH_METHOD=trust


text:
Q: Reference working on Overleaf but not locally I am using https://www.overleaf.com/latex/templates/university-of-michigan-dissertation-template-unofficial/tpnjzndnrzmf
I downloaded it to my own laptop and compiled it. The citation and reference are not working. But they are fine on Overleaf. I have a vague impression that this has something to do with compilation. I compiled twice using pdfLaTeX (WinEdt 10) but it is still the same. How shall I fix this problem?


text:
Q: Adding icons to navigation bar in xcode I want to add icon to the navigation bar present in my xcode project.Can anyone guide me through any method to do so and also i want to do it programmatically.Any help will be appreciated.
Thanks,
Christy

A: Check below SO post.
how to display an image in the navigation bar of an iPhone application?
adding icon between back button & title of navigation bar
Are there free iPhone navigation bar icon sets available?

A: IBOutlet UIImageView *image;

UIImage *image1=[UIImage imageNamed:@name.jpg"];
image=[[UIImageview alloc]initWithImage:image1];

image.frame=CGRectMake(0,0,320,400);
navigationbar.titleview=image;

EDIT:
image to the right side:
UIButton* fakeButton = (UIButton *) [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage.png"]];
UIBarButtonItem *fakeButtonItem = [[UIBarButtonItem alloc] initWithCustomView:fakeButton];
self.navigationItem.rightBarButtonItem = fakeButtonItem;
[fakeButtonItem release];
[fakeButton release];

source:pevious so questions


text:
Q: why my model does not train over all the data (Tensorflow 2) I have a code here using the tensorflow.keras.datasets.imdb data, after splitting my data for train and validation (line 45-50) so my training data and training labels are ndarray of (15000,).
while training my model I can see that the model is not iterating through the entire dataset and I'm getting an accuracy of 49.8%
I followed this video : TensorFlow 2.0 Tutorial - Training the Model - Text Classification P3 and typed the same program.
this is what I see when I train the model:

the code:
from tensorflow import keras
import numpy as np

# Loading data
data = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = data.load_data(num_words=10000)
# only take 10,000 words that are most frequent
# we get integer encoded words

# Preprocessing
word_index = data.get_word_index()

word_index = {k: (v + 3) for k, v in word_index.items()}
# dict where the keys are words in char form and values are numbers in int form
word_index["<PAD>"] = 0
word_index["<START>"] = 1
word_index["<UNK>"] = 2
word_index["<UNUSED>"] = 3

reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
# now we have a dict with keys as integers and values as words

train_data = keras.preprocessing.sequence.pad_sequences(train_data, value=word_index["<PAD>"],
padding="post",
                                                    maxlen=250)
test_data = keras.preprocessing.sequence.pad_sequences(train_data, value=word_index["<PAD>"],
padding="post",
                                                   maxlen=250)

def decode(text):
    return " ".join([reverse_word_index.get(i, "?") for i in text])

# Model
model = keras.Sequential()
model.add(keras.layers.Embedding(10000, 16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation="relu"))
model.add(keras.layers.Dense(1, activation="sigmoid"))

model.summary()

model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])

# Validation data
x_val = train_labels[:10000]
x_train = train_labels[10000:]

y_val = train_labels[:10000]
y_train = train_labels[10000:]

fitModel = model.fit(x_train, y_train, epochs=40, batch_size=512, validation_data=(x_val, y_val),
verbose=1)
# batch_size is how many reviews are we going to give at once to the model

(note: I don't have an Nvidia GPU, my GPU is RADEON RX)

A: I think your model has been trained on 15,000 examples because the number of iterations for each epoch is 15000 /batch_size ~ 30. According to the logs, it shows 30/30 for each epoch and the training process also completed 40 epochs. The reason you got low accuracy is probably because of the rate between train and dev set which is currently 15000:10000 = 60:40. Therefore, it would be better if you split it to the ratio of 80:20 or 90:10 so that the model can see more examples.

A: with a batch size of 512 your data shows you are training for 30 batches so you are training on   15,360 samples.  Your data shows the model is training well. At the end of 30 epochs you have 100% for training accuracy and 100 % for validation accuracy. I assume you ran model.evaluate on your test set which gave you an accuracy of 49.8%. Since your model is very accurate there is something wrong with your test data. Run model.evaluate on the validation data and you should see 100% accuracy.

A: Every epoch is an iteration over batches of the training set you have specified. In your case, batch size = 512 therefore the model was trained over 512(batch size) * 30(batches) per epoch, which is about 15000ish data points, so your entire set in this case.
You model however is entirely wrong regardless of the above.
Here:
x_val = train_labels[:10000]
x_train = train_labels[10000:]

y_val = train_labels[:10000]
y_train = train_labels[10000:]

You're specifying for both x and y the same object (labels), therefore your model is learning nothing, at least not features!
The .fit() function gives you the option to skip this manual validation split above entirely and do:
fitModel = model.fit(x_train, y_train, epochs=40, batch_size=512, validation_split=0.2, verbose=1)

validation_split inside fit() will handle the validation during training and use 20% of data points in this case as specified, which is a good starting point.
You can then do fitModel.evaluate(x_test, y_test)


text:
Q: What's the most effective way to deal with a big group of sentries? I'm playing Capture the Flag (on Turbine), and the enemy's team has a group of about five level-3 sentries right outside the door to our base. I've tried being a Soldier, Heavy and Demoman, and destroying them, but all five gun me down before I have the chance. The Scout's essentially useless and he'll be destroyed almost instantly, as will the Pyro and Medic. As a Spy, I am either blown up by grenades or sticky bombs before I even get near the sentries, or, if I'm lucky enough to get to them, as soon as I sap them, another Engineer comes along and removes my sapper (and I obvious can't backstab him as other Sentries will quickly shoot at me).
What is the best thing to do in this situation (in order to destroy lots of sentries), where coming into contact with them is inevitable (What is an ideal class to use, and what is the best strategy)?

A: I know this is going to be difficult... but you're going to need a team to do this.
Chances are you'll need at least:

*

*1+ uber Medic.

*1+ stickylauncher DemoMen as the Medics' patient(s).  i.e. one that isn't a DemoKnight or Stickyjumper

*A non-YER, non-DR Spy (this is optional, but may make it easier).  Red-Tape Recorder is recommended.

*Other damage classes (Soldier, DemoMan, Heavy)

*A Bonk Scout can also help to distract the sentries.

Now, the trick here is to use the Uber and get the sentries firing on the DemoMan.  Meanwhile, the Spy (if you have one) should be creating a distraction by some of the farther away sentries.  If possible, the Spy should concentrate on the sentry guns whose Engineers are using Wranglers.
The ubered player should be a DemoMan thanks to the Rescue Ranger... Demo is the only class whose damage can be done in burst so that the shoot to heal effect is useless (although if they pick up the gun to move it, two stickies will kill the Engineer)
The Spy's job (if you have one) is two-fold:

*

*Sap the sentries and supporting buildings.  Especially the Wrangled sentries as you can't wrangle / remotely heal sapped sentries.

*Cause a distraction for the Engies to deal with.

The other damage classes should be assisting to take out the sentries while they are distracted by the Uber.  As long as the Ubered players are closer to the sentries, the sentries will fire upon them instead.  The exception is for wrangled sentries (this is one of the reasons the Wrangler is a bit OP).
Now, the biggest problem with the above scenario is if one of the players is using a Short Circuit.
The Best Solution
Team Scramble.  If teams are unbalanced enough that one team can build 5 sentries out in mid, a scramble is more than warranted.


text:
Q: Reference Excel files getting filename from a cell I want to get values from different excel files (say, File-AAA.xlsx, File-ABC.xlsx, etc). ¿How can I reference said files without inputting manually the "ABC" part of the filename, but getting it from the current sheet instead?

In the example, from our current sheet we want to get the values of A1 and A2, from the File-ABC.xlsx file, and sum them.
For instance, in B2, instead of writing:
    =SUM('\\server\path\[File-ABC.xlsx]Data'!A1:A2)

I would like to be able to write it as
    =SUM('\\server\path\[File-*REFERENCE TO CELL*.xlsx]Data'!A1:A2)

Where *REFERENCE TO CELL* is the sought text string that references the cell that contains "ABC" (A2).

A: You can use the indirect function for this.
Something like this -
=SUM(INDIRECT("'\\server\path\[File-"&A2&".xlsx]Data'!A1"&":"&"A2"))

Edit-1 :
You can use the same syntax to refer to the local directory that you want, just replace \server\path[File- with the path of the new directory. You can copy the path from your file explorer after browsing to the concerned folder.
Eg. Taking the path from your comment (after correction):
=SUM(INDIRECT("'C:\Users\PeteThePanda\Spreadsheets[File-"&A3&".xlsx]Data'!A1"&":"&"A2"))

A: A more straightforward way to do this is set up a conditional statement outside the sum, e.g. if the value of A2 in the current workbook is ABC, then go to this path and bring in the sum.
e.g.
=if(A2="ABC",sum('\\server\path\[File-ABC.xlsx]Data'!A1:A2),if(A2="AAA", sum('\\server\path\[File-AAA.xlsx]Data'!A1:A2),"No File"))
Note, you can add additional nested IFs if there are more files. Just start a new if where I wrote "No File".


text:
Q: imacros work in offline mode I want a command to work offline in imacro for firefox
Is there any way to emaulate manually clicking file->work offline.
even if there is some javascript command or someway to do it by vb code it is ok.
basically what i am trying to achieve is that i open a page which has a form. now i fill the form with some values and click submit and extract results from the next page. again i open the 1st page with the form. now i want to do this opening of the 1st page in offline mode so that it is faster as teh page is already there in cache. next again i need to go online before i click submit.

A: the following Code works for iMacros on Firefox to toggle 'Work Offline' ON/OFF:

EVENT TYPE=KEYPRESS SELECTOR=* Char="f" MODIFIERS="alt"
EVENT TYPE=KEYPRESS SELECTOR=* Char="k" MODIFIERS="alt"


text:
Q: unexpected output value from procedural code I have this piece of javascript that won't work. It is supposed to take the user input and store it into the player input variable. Then, it splits the string that is returned and splits it into an array which is then converted into an object by the function oc(). Finally, the function analyzeUserInput finds keywords in the input object and places text into the paragraph element called text accordingly. In this example if the user types in slash, poke, slice, hack, etc and the word "sword" the paragraph element is supposed to say "you did 4 damage!" but it doesn't. here's the code:
<!DOCTYPE html>

"oh no theres a monster whatchya gonna do?"

        <input id="plyrInput" type="text" />
        <button onclick="analyzeUserInput()">Try it</button>

A:         var plyrInput;
        var plyrInputArray;
        var plyrInputAnalysis;

        function oc() {
            plyrInputArray = plyrInput.split(' ');
            var plyrInputObj = {};
            for (var i = 0; i < plyrInputArray.length; ++i) {
                //storing these values in an object being blank is not really needed at all!
                //plyrInputObj[plyrInputArray[i]] = ' ';
                plyrInputObj[i] = plyrInputArray[i]; //acceptable or use the array itself!
            }
            return plyrInputObj;
        }

        function analyzeUserInput() {
            //plyrInput = document.getElementById("plyrInput").text;//no such property as text
            plyrInput = document.getElementById("plyrInput").value;
            //you ran this function without storing it so we can't use it
            //oc();
            var plyrAction = oc();
            //you call an undefined variable `plyrInputAnalysis`. So what are we going to do with it?
            if (plyrInputAnalysis in oc(['use', 'slash', 'hack', 'wield', 'slice', 'sever', 'dismember', 'poke', 'cripple', 'maim', 'mutilate', 'chop', 'rend']) && plyrInputAnalysis in oc(['sword'])) {
                document.getElementById("text").innerHTML = "You did 4 damage with your sword!";
            }
        }

Now for the fix:
        var plyrInput;
        var plyrInputArray;
        var plyrInputAnalysis;
        //added an acitonList for later usage for yourself
        var actionList = {
          'use':4,
          'slash':4,
          'hack':4,
          'wield':4,
          'slice':4,
          'sever':4,
          'dismember':4,
          'poke':4,
          'cripple':4,
          'maim':4,
          'mutilate':4,
          'chop':4,
          'rend':4
        };
        function oc() {
            plyrInputArray = plyrInput.split(' ');
            var plyrInputObj = {};
            for (var i = 0; i < plyrInputArray.length; ++i) {
                plyrInputObj[i] = plyrInputArray[i];
            }
            return plyrInputObj;
        }

        function analyzeUserInput() {
            plyrInput = document.getElementById("plyrInput").value;
            var plyrAction = oc(); //cached the returned value from oc
           for(var item in plyrAction){ //looping through the plyrActions object
              if(actionList[plyrAction[item]]){ //if there is a plyrAction that matches the actionsList we'll continue.
                  document.getElementById("text").innerHTML = "You did "+actionList[plyrAction[item]]+" damage with your sword!";
              }
           }
        }

Though this could seems more complicated than it needs to be I went off your original methodology, you could create a better instance of this code for an RPG game, though it would be good to look into an IIFE to wrap this in and minimize a lot of the code instead of multiple functions.
For instance
        function analyzeUserInput() {
            plyrInput = document.getElementById("plyrInput").value;
            var plyrAction = plyrInput.split(' ');
            var plyrInputObj = {};
            for (var i = 0; i < plyrAction.length; ++i) {
                plyrInputObj[i] = plyrAction[i];
            }
           for(var item in plyrInputObj ){
              if(actionList[plyrInputObj[item]]){
                  document.getElementById("text").innerHTML = "You did "+actionList[plyrInputObj[item]]+" damage with your sword!";
              }
           }
        }


text:
Q: Positioning social icons on a navigation bar This is what my page currently looks like: Here
I want the social icons to position in line with the rest of the navigation content. At the moment they are beneath the content. I thought float right would fix things. Is it because of my browser size? How can I fix this then? Here is my code:
HTML:

PavSidhu.com

Home

Web Design

Graphic Design

How it Works

Pay

Contact

CSS:
    #Nav {
    position:fixed;
    width:100%;
    background-color:#f26522;
}

#NavContent {
    margin:0 auto;
    width:90%;
}

ul {
    margin:0;
    padding:0;
}

li {
    font-family: Bebas;
    color:#FFF;
    list-style-type:none;
    margin:0;
    padding:0 1%;
    display:inline;
    vertical-align:middle;
    font-size:20px;

}

#Title {
    font-size: 35px;
}

.Social {
    height:35px;
    float:right;
}

Thanks guys :)

A: The
 is a block element, so it wants to be 100% width by default. If you make it an inline element with display: inline; instead, there will be space for the icons to sit next to the rest of the nav bar.
ul {
    margin:0;
    padding:0;
    display: inline;
}

A: You mean you want the social-media-icons higher? Next to the menu-items instead?
Try using
display: inline-block;

for your ul.

A: set ul to display: inline-block

A: As explained earlier, ul is a block element that will take 100% of the width of the parent element, so the floated elements will start on the next line.
To fix this, you can use:
ul {
    margin:0;
    padding:0;
    border: 1px solid blue; /*for demo only */
    display: inline-block;
    width: inherit;
}

See demo at: http://jsfiddle.net/audetwebdesign/tAjW8/
You need to set width: inherit or else the computed width will be narrower than you might expect.


text:
Q: linking error on adding new file/class to ios project I am getting a build failure on link after adding a new .h and .m file dataparsing and i don't quite understand why. I'm newer to objective-c though.  if i remove the include ( then i have to remove the reference to the object from the file that needs dataparsing class) then it wont fail. just removing the object wont cut it and it still fails when i try to include the files. in the error section under linking it says one duplicate symbol for architecture i386
dataparsing.h is:
//
//  dataParsing.h
//  TelnetToICC
//
//  Created by **** on 10/8/12.
//
//

#import <UIKit/UIKit.h>

@interface dataParsing : UIView
{

}
- (void)getData:NSString:id;
-(void) parseLine:id;
-(void) parseDatagram:id;
-(void) reset;

@end

char icc_data[10000];
int data_top=-1;

the idea is just to write some simple functions for processing strings so i am not trying to do anything real special here but i'm newer to objective-c. The include for dataparsing in ViewController.m is:
#import "dataParsing.h"
#import "ViewController.h"
#import <CoreFoundation/CFSocket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

@implementation ViewController

It seems like i got something going on twice for the linker but my experiments havent found it. I noticed both my .h files have
#import <UIKit/UIKit.h>

but i remove one and it doesn't work.
Mike

A: The duplicate symbol is _data_top. And I'm guessing also _icc_data. The problem is that you are declaring a global variable in the dataparsing.h file. So for every file that includes this .h file, a new global variable with the same name is created resulting in the duplicate symbol linker error.
What you need to do is change the lines:
char icc_data[10000];
int data_top=-1;

to:
extern char icc_data[10000];
extern int data_top;

Then in the dataparser.m file you do:
char icc_data[10000];
int data_top = -1;

The extern in the .h file lets the compiler and linker know that there will be one copy of the variable defined somewhere. The lines in the .m file are that one definition.


text:
Q: Access SQL/query has truncated field at 25 characters? I have this query in Access:
SELECT a.title, a.init, a.name, l.User AS CreatedBy,
     IIf(IsNull(l.Time),Null,DateAdd("s",l.Time,#3/1/1980#)) AS CreatedAt
     FROM (Reports AS a LEFT JOIN
     (SELECT id, Min([time]) AS Mintime FROM AuditLog GROUP BY id) AS t
     ON a.id = t.id)
     LEFT JOIN AuditLog AS l ON (t.mintime = l.time) AND (t.id = l.id)
     WHERE (((a.name) Like 'start*') AND ((a.Active)='Y'));

But for some reason a.name is truncated on every result in the query at 25 characters. Why is this? In the table Reports it is correct and shows the full name (25+ characters long).

A: This could be due to the size of the a.name field.  If the field is set to varchar(25), it is going to allow only 25 characters.
-Edit-  Also check any procedures, queries, or outside sources that insert data into that field.  It could be a paramter that has been misconfigured.

A: Please check the field length of name attribute in table a.
It must be more than the name you stored.
I think your name length is larger than field length.

A: I had two similar Name fields, I misread one and it indeed was truncated in the actual table.


text:
Q: Homebrew Yosemite Apache issue I installed a Homebrew Apache setup as explained here.
For me, it doesn't work at the moment.
When running httpd -DFOREGROUND, I'm getting the next error:
httpd: Syntax error on line 117 of /usr/local/etc/apache2/2.2/httpd.conf: Cannot load /usr/local/Cellar/php55/5.5.27_2/libexec/apache2/libphp5.so into server: dlopen(/usr/local/Cellar/php55/5.5.27_2/libexec/apache2/libphp5.so, 10): Symbol not found: _ap_unixd_config\n Referenced from: /usr/local/Cellar/php55/5.5.27_2/libexec/apache2/libphp5.so\n Expected in: /usr/local/bin/httpd\n in /usr/local/Cellar/php55/5.5.27_2/libexec/apache2/libphp5.so.
The file (/usr/local/Cellar/php55/5.5.27_2/libexec/apache2/libphp5.so) does exist though.
Running dnsmasq --keep-in-foreground then, it fails with dnsmasq: failed to create listening socket for 127.0.0.1: Address already in use.
All error logs in troubleshooting are empty.
Important to know is, that I installed another setup earlier, before upgrading to 10.10 that did work for a while, stopped working suddenly. After that, I decided to upgrade my OS and removed everything as explained in the Troubleshooting section. I restarted from the beginning.
Thanks!

A: Try to brew reinstall php55 --homebrew-apxs.
As mentioned here, this should solve this problem.


text:
Q: Reverse order BST Insertion I was wondering if their is a way to insert list items in a BST from right to left. So far I can insert items from left to right.
Code:
-- Type constructor
data Tree a = Empty | Node a (Tree a) (Tree a)
   deriving (Eq, Show)

-- inserts into BST
insert :: (Ord a) => a -> Tree a -> Tree a
insert x Empty = Node x Empty Empty
insert x (Node y l r)
    | y == x = Node y l r
    | y < x = Node y l (insert x r)
    | y > x = Node y (insert x l) r

-- Converts list to a BST
listToTree :: (Ord a) => [a] -> Tree a
listToTree xs = foldl (\acc x -> insert x acc) Empty xs

What I'm currently achieving:
Prelude> listToTree [4,2,6]
Node 4 (Node 2 Empty Empty) (Node 6 Empty Empty)

But I wish the reverse order:
Node 6 (Node 2 Empty (Node 4 Empty Empty)) Empty

I'm not really sure how I can modify foldl to do this. Would a recursive approach be better for this sort of task? Any sort of help would be appreciated.

A: The obvious thing to do is to reverse the list before feeding it to foldl.  The same effect can be achieved by using foldr.
If you are asking how to modify the insert instruction itself, what you want is the last node inserted to be the root and whatever was there already to move down the tree. so:
insert x (Node y l r)  -- Note: x is the new value and y the existing root.
    | y == x = Node y l r -- Don't insert a dup (per original)
    | y > x = Node x l (insert y r) -- make x the new root and y goes in the left tree
    | y < x = Node x (insert y l) r  -- make x the new root and y goes in the right tree


text:
Q: MVP Model RxJava CompositeDisposable where do i clear? I use MVP by http://www.tinmegali.com/en/model-view-presenter-mvp-in-android-part-2/
I use RxJava CompositeDisposable - Observable in MainModel.java
Where do I clear CompositeDisposable in my MainModel.java ?
Can I clear CompositeDisposable in method onComplete of DisposableObserver ?
private CompositeDisposable disposables = new CompositeDisposable();

getObservableNote(note)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(d);

    disposables.add(d);

....
..

private Observable<Note> getObservableNote(Note noteadd) {
    return Observable.just(true).map(aBoolean -> {
        Note noteget = doLongOperationNote(noteadd);
        return noteget;
    });
}

private DisposableObserver<Note> getDisposableObserverNote() {
    return new DisposableObserver<Note>() {

        @Override
        public void onComplete() {

            Log.d("Thread onComplete", Thread.currentThread().getName());
            disposables.clear();
        }

        @Override
        public void onError(Throwable e) {
            Log.d("onError", e.toString());
        }

        @Override
        public void onNext(Note noteget) {
            Log.d("Thread onNext", Thread.currentThread().getName());
            mPresenter.onNoteInsertedNote(noteget);

        }
    };
}


text:
Q: Subject verb agreement in a sentence with and We know that if two or more singular nouns are joined with 'and' they take a plurality verb but if they convey the same idea they take a singular one.
Can you help me out with the following sentence:

The lack of interest and a high price of books ________ equally
  responsible for people running away from serious reading.

What shall we use "is" or "are"? I am in the favour of using "are".

A: In your example, "are" is the correct form of verb.
Moreover, you seem to have absorbed an incorrect version of a rule. Two nouns that have similar meanings and are joined by "and" generally take a plural verb.
Jealousy and envy are similar emotions of no utility and less dignity.
It is when nouns joined by "and" are considered to be constituent parts of a single thing that a singular verb is used.
Meat and potatoes is what I grew up on
is considering that meat was one part of a single meal in   my youth and that potatoes formed another part of that meal. But fish, greens, and fruits were not parts of typical meal.


text:
Q: Using Slick (Scala), is there a way to add a column to a table 'on the fly'? I would like to write my Scala+Slick application so that a user could configure additional columns to a table without having to modify the source code.  Is there a way to do that?
Adam S - Yes, that is what I am thinking of.  The program would come with a default configuration file, and the end user/administrator could optionally add new columns to some of the tables and when the program started it would add those columns.
There are a few other ways I was thinking of going, such as configuring the initial table with spare columns that the user would configure (but that suffers from limiting the number of spares and pre-defining the types).     Another way was to define a second table that had the same primary key(s) as the original, and have it contain only user defined data, and then the program would have to deal with maintaining both tables (each would have the same number of rows), which would allow the original default table to be handled more conventionally.   The two tables might be kept in sync with database functions (which would make it database specific).

A: Yes, this is possible. When you define a column as part of a Table definition, it is done by calling the Table object's 'column' method. You can do the same from the outside, e.g.:
for {
  a <- TableA
  b <- TableB if a.id === b.column[String]("dynamic1")
} yield b.column[Int]("dynamic2")

The type parameter determines the right implicit ColumnType to use for the column. You can also get a ColumnType dynamically and supply that parameter explicitly.
Note that there is no requirement for the * projection of a table to contain all columns. If you want to generate the DDL for dynamically discovered columns, you can include those columns in the Seq returned by create_*.