text:
Q: Not able to instantiate PDF browser control from AcroPDF.dll using COM and .NET interop When I try to instantiate a PDF browser control like this in C#:
AcroPDFLib.AcroPDFClass acrobat = new AcroPDFLib.AcroPDFClass();

I get a COMException with this message:

Creating an instance of the COM component with CLSID {CA8A9780-280D-11CF-A24D-444553540000} from the IClassFactory failed due to the following error: 80004005.

I have made a reference to AcroPDF.dll which has the component name Adobe Acrobat 7.0 Browser Control Type Library 1.0.
When I run Visual C# 2008 Express Edition as administrator I get another error message:

Unable to cast COM object of type 'AcroPDFLib.AcroPDFClass' to interface type 'AcroPDFLib.IAcroAXDocShim'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{3B813CE7-7C10-4F84-AD06-9DF76D97A9AA}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

This happens at the next line when I try to use the object:
acrobat.LoadFile("book.pdf");

I can't figure out what is wrong. Help most appreciated!

A: .net COM interop doesn't route all COM messages directly back to the caller. If you called COM from an STA, it won't understand how you app can handle re-entrance. This means that failure messages that could just be handled with a retry, end up causing exceptions.
Try implementing IMessageFilter interface. This will allow COM to understand how to pass messages back to your app. In particular, implement the RetryRejectedCall and check if the failure flags and possibly return a timeout value (something like 1000ms) to allow COM to retry after a brief pause.
It's a COM type, so this is the code you'll need to define the interface:
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("00000016-0000-0000-C000-000000000046")]
public interface IMessageFilter
{
    [PreserveSig]
    int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);

    [PreserveSig]
    int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);

    [PreserveSig]
    int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
}

And this is an example of how you would implement it:
public class MyMessageFilter : IMessageFilter
{
    int IMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller,int dwTickCount, IntPtr lpInterfaceInfo)
    {
        // 0 means that it's handled.
        return 0;
    }

    int IMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
    {
        // The return value is the delay (in ms) before retrying.
        return 1000;
    }

    int IMessageFilter.MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
    {
        // 1 hear means that the message is still not processed and to just continue waiting.
        return 1;
    }
}

Once you've implemented a message filter you will need to register it using CoRegisterMessageFilter. This is a per-thread registration, so be aware of what thread you are calling it on. The PInvoke signiture is:
[DllImport("ole32.dll")]
static extern int CoRegisterMessageFilter(IMessageFilter lpMessageFilter, out IMessageFilter lplpMessageFilter);

Even if this doesn't work, at the very least, if you log all the messages in the filter you should hopefully get some more information about what is going wrong. Look at the values of the parameters being passed into the message filter. If you look them up they will relate to error/state codes.
[Be aware, the IMessageFilter I'm referring to here is different from the System.Windows.Forms.IMessageFilter, so make sure you don't accidentally use the winforms one.]

A: These are the steps to use the Adobe PDF Reader control:

*

*Create a new Windows Forms Application: File → New Project… → Windows Forms Application → OK

*Add a reference to the Adobe Acrobat 7.0 Browser Control Type Library 1.0: Project → Add Reference… → COM → Adobe Acrobat 7.0 Browser Control Type Library 1.0 → OK

*Add the Adobe PDF Reader control to the Toolbox: Tools → Choose ToolBox Items… → COM Components → Adobe PDF Reader → OK

*Drag an Adobe PDF Reader control from your toolbox into the Form

I'm not sure why but I have to run Microsoft Visual C# 2008 Express Edition with administrative privileges to get this working. With a limited user I get this message in the designer:

Error HRESULT E_FAIL has been returned from a call to a COM component.

Note that after adding the Adobe PDF Reader control to your toolbox a new .NET interop assembly has been created with the name AxInterop.AcroPDFLib.dll. A reference to this new assembly has been added to your project references.
API reference documentation for the Adobe PDF Reader control is located here: http://icio.us/ajukkr
This forum thread provides some more useful information: http://forums.adobe.com/thread/438362


text:
Q: How can I copy a directory that have symlinks in it with CMake during build time when using file(GLOB_RECURSE)? The most straight forward way to copy a directory in CMake during build time is:
add_custom_target(my-copy-dir ALL COMMAND ${CMAKE_COMMAND} -E copy_directory
                                          ${INPUT_DIR} ${OUTPUT_DIR})

However, this approach is not desired because the copy will be executed every single time even when everything is up-to-date, which slow things down. Therefore, the below approach is better
file(
  GLOB_RECURSE FILES
  LIST_DIRECTORIES false
  RELATIVE ${INPUT_DIR}/
  ${INPUT_DIR}/*)
foreach(FILE ${FILES})
  add_custom_command(
    OUTPUT ${OUTPUT_DIR}/${FILE}
    DEPENDS ${INPUT_DIR}/${FILE}
    COMMAND ${CMAKE_COMMAND} -E copy ${INPUT_DIR}/${FILE} ${OUTPUT_DIR}/${FILE})
  list(APPEND ALL_OUTPUT_FILES ${OUTPUT_DIR}/${FILE})
endforeach()
add_custom_target(my-copy-dir ALL DEPENDS ${ALL_OUTPUT_FILES})

The copy will only be executed if there are changes to the files in the input directory. Most of the time this approach works perfectly, however, I recently encountered a situation where there are symlinks in the input folder, and the symlinks are ignored during the file glob, so unfortunately I have to use the first approach to copy this folder in order to preserve the symlink. Is there a way to make the second approach work with a folder that contains symlinks?
For more context, the folder I am copying is a macOS framework. For example, assuming the name of the framework is Foo.framework, Foo.h is inside Foo.framework/Versions/A/Headers, and there's also a symlink to Foo.h in Foo.framework/Headers. If I use the second approach, I can see Foo.h in Foo.framework/Versions/A/Headers but not Foo.framework/Headers, whereas if I use the first approach I can see Foo.h in both, but I would like to make the second approach work in order to avoid copying every single time when everything is up-to-date. How can I achieve this?

A: Just use the FOLLOW_SYMLINKS argument of file(GLOB_RECURSE) :P
Also, note that globbing also always has a tradeoff. See the CONFIGURE_DEPENDS argument. Either you don't get glob match updates at build time, or you do (in which case there's the cost of the glob matching having to run for every build). Take that into account in your statement "Therefore, the below approach is better".
Note also that CMake v3.26-rc3 has a new cmake -E copy_if_different <dir>... <destination> command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS link styling priority I'm using CSS to style some of my link on my website I'm making for school, but I've ran into a problem. One bit is styled with CSS so its can be used as navigation menu. The other links are regular links with some styling.
The navigation menu has to be in the div tag for the regular link styling too, otherwise the background will not cover the whole page.
The problem is, since the div of the nav menu is placed within the styling of the other links, the effect of both styles get applied to the navigation menu.
Is there a way to give the styling of the navigation menu a higher priority than those of the other links, so that only the styling of the navigation menu will be applied?
Here's the CSS of the navigation menu:
    /* styling voor navigation menu */

.nav ul {
    list-style: none;
    background-color: #525252;
    text-align: center;
    padding: 0;
    margin-left: 400;
    margin-right: 400;
    border-radius: 10px;
    border: 1px solid black ;
    color: #fff;
    }

.nav li {
    font-family: 'Oswald', sans-serif;
    font-size: 1.2em;
    line-height: 30px;
    height: 30px;
}

.nav a {
    text-decoration: none;
    color: #fff;
    display: block;
    transition: .3s background-color;
}

.nav a:hover {
    background-color: #404040;
}

.nav a.active {
    background-color: #404040;
    color: #fff;
    cursor: default;
}

.nav li {
    width: 110px;
    height: 40px;
    line-height: 40px;
    font-size: 1.2em;
  }

.nav li {
    display: inline-block;
    margin-right: -4px;
  }

    /* extra class voor meescrollen menubalk */

 .main-nav-scrolled {
    position: fixed;
    top: 0;
    z-index: 9;
    text-align: center;
    width: 41%;
    background: #858585
    }

here's the CSS of the other links:
/* links voor onderste gedeelte pagina */

.bottom a:link {
    text-decoration: none;
    color: inherit;
}

.bottom a:visited {
    text-decoration: none;
    color: inherit;
}

.bottom a {
    color: inherit;
    text-decoration: none;
    border-bottom: 1px solid transparent;
    transition: all 0.3s;
}

.bottom a:hover {
    color: inherit;
    border-color: inherit;
}

And here is the important bit of HTML:

Pokémon

Types

Abilities

Natures

Stats

<?php
echo " " . $type1 . '';
?>

Thanks in advance!
-Gijs

A: if you add styles to .bottom a that are not given to .bottom .nav a like background: green it will become a style to .bottom .nav a also. All styles need to be overwritten if you want custom styles only for .bottom .nav a
because .nav a is a descendant of .bottom , even if you write a very specific path eg .bottom .nav ul li a , it will inherit from .bottom a
the styles that are 'unique'
for example

*

*snippet not good for you ( .nav li a inheriting background: green style from .bottom a because it doesn't have a background style for its self )

.bottom .nav a:hover { color:red;}
.bottom a:hover { color:yellow;background:green}

Pokémon

Types

Abilities

Natures

Stats

*snippet good ( disable background:green from .bottom a by adding background:none or background: anythinghere image or color etc. for .bottom .nav li a )

.bottom .nav a:hover { color:red;background:black}
.bottom a:hover { color:yellow;background:green}

Pokémon

Types

Abilities

Natures

Stats

A: So what you're going to want to do first is add a new class to all the links in your nav, for example:

Types

Then in your css for the nav you will use .nav a.new-class-here instead of .nav a, .nav a.new-class-here:hover instead of .nav a:hover, and so forth.
Then in your css for the other regular links you will want to use .bottom a:not(.new-class-here) instead of .bottom a. What this does is selects all the links in .bottom that do not have that new class we created. So now your nav styles will only apply to your nav links and your regular styles will only apply to the non-nav links.
You can learn more about :not() here if you want: https://developer.mozilla.org/en-US/docs/Web/CSS/:not


text:
Q: Fatal Error: composer.lock was created for PHP version 7.4 or higher but the current PHP version is 7.1.33 At the moment, I'm facing this issue. I've tried everything: deleting composer.lock, then updating composer.json, tried to update PHP version to the highest version, still the same. When I check PHP version in CMD, it shows that my version is 7.4.10, but when I try to open "public" folder on localhost, it shows this "Fatal error: composer.lock was created for PHP version 7.4 or higher but the current PHP version is 7.1.33.".
Thanks in advance

A: Try to delete symfony.lock and composer.lock then deletr vendor folder and launch command composer install


text:
Q: How to initialize nested dictionaries in Python I'm using Python v2.7 dictionaries, nested one inside another like this:
def example(format_str, year, value):
  format_to_year_to_value_dict = {}
  # In the actual code there are many format_str and year values,
  # not just the one inserted here.
  if not format_str in format_to_year_to_value_dict:
    format_to_year_to_value_dict[format_str] = {}
  format_to_year_to_value_dict[format_str][year] = value

It seems a bit clumsy to initialize the first level dictionary with an empty dictionary before inserted into the second level dictionary.  Is there a way to set a value while at the same time creating a dictionary at the first level if there is not one already there?  I imagine something like this to avoid the conditional initializer:
def example(format_str, year, value):
  format_to_year_to_value_dict = {}
  add_dict_value(format_to_year_to_value_dict[format_str], year, value)

Also, what if the inner dict should itself initialize to a list?
def example(format_str, year, value):
  format_to_year_to_value_dict = {}
  # In the actual code there are many format_str and year values,
  # not just the one inserted here.
  if not format_str in format_to_year_to_value_dict:
    format_to_year_to_value_dict[format_str] = {}
  if not year in format_to_year_to_value_dict[format_str]:
    format_to_year_to_value_dict[format_str][year] = []
  format_to_year_to_value_dict[format_str][year].append(value)

A: from collections import defaultdict
format_to_year_to_value_dict = defaultdict(dict)

This will create a dictionary that calls dict() when you access keys that don't exist.

A: Use setdefault:

If key is in the dictionary, return its value. If not, insert key with a value of default and return default.

format_to_year_to_value_dict.setdefault(format_str, {})[year] = value

Or collections.defaultdict:
format_to_year_to_value_dict = defaultdict(dict)
...
format_to_year_to_value_dict[format_str][year] = value

With lists in the inner dict:
def example(format_str, year, value):
  format_to_year_to_value_dict = {}

  format_to_year_to_value_dict.setdefault(format_str, {}).setdefault(year, []).append(value)

or
def example(format_str, year, value):
  format_to_year_to_value_dict = defaultdict(lambda: defaultdict(list))

  format_to_year_to_value_dict[format_str][year].append(value)

For dicts of unknown depth, you can use this little trick:
tree = lambda: defaultdict(tree)

my_tree = tree()
my_tree['a']['b']['c']['d']['e'] = 'whatever'


text:
Q: How to get a weekly interval starting on mondays in sas proc timeseries? The sas proc timeseries is able to compute weekly totals like this:
proc timeseries
        data=work.sorttemptablesorted
        out=work.weeklyagregated
        ;
    id dateusedforstatistics interval=week zeromiss=none ;
    var cases / accumulate=total setmissing=0;
    by subject network;
run;quit;

It's almost perfect, but the only thing is that it agregates weeks starting on sundays
Sun, 25 Feb 2007    2
Sun, 4 Mar 2007 0
Sun, 11 Mar 2007    0
Sun, 18 Mar 2007    1
Sun, 25 Mar 2007    2
Sun, 1 Apr 2007 11

And I cannot find a solution to compute the same with weeks starting on mondays instead.
Is there a option for INTERVAL= that makes weeks start on mondays?
(using SAS9.3)

A: I don't have ETS, so don't know PROC TIMESERIES.  With the INTCK() function, when you specify an interval you can also specify a "shift index", so e.g. week.2 would be weeks starting on Monday rather than the default week.1 which is weeks starting on Sunday. You could try changing to interval=week.2, but I took a look at the docs and didn't look like it was documented.


text:
Q: css :not pseudo not working I have a set of buttons on a wysiwyg textarea that I do not want to apply a .btn class to. I am using Bootstrap 3 and using the :not pseudo selector but the .btn is not getting applied to anything once I add the :not
.btn:not(.wysihtml5-toolbar .btn) {
    padding: 10px 27px 8px;
    font-size: 14px;
    line-height: 1.42857143;
    border-radius: 4px;
    transition: .3s;
}


text:
Q: Storing an array in firebase i want to store an array of components created dynamically with angular into a firebase collection but  i cannot resolve this error
'ERROR FirebaseError: Function CollectionReference.add() requires its first argument to be of type object, but it was: an array'
that's my implementation
  componentscollection: AngularFirestoreCollection;
  componentclass = [];

   constructor(private db: AngularFirestore...){
    this.componentscollection = db.collection('componentclass')
   }

   //that's where am adding the components into the array
     addComponent(componentClass: ComponentFactory<any>, target) {
         let componentRef: ComponentRef<any> = this.container.createComponent(componentClass);
         this.componentclass.push(componentClass)
      }

      //function that will add the array of components into the database
      savemockup(){

       this.componentscollection.add(this.componentclass); }

When calling the method savemockup() this  error occured .


text:
Q: Is there a cache in ansible git module? I am using an ansible-playbook for my deployment and am using git to checkout my source code. The problem I am having is, I keep on getting stale versions of my source. I don't know why this is happening. It was okay before this. Is there a way to disable the cache is there is one ?
- name: Checkout eclaim_revamp source code
  git: repo={{ deployment_url }} dest=/opt/eclaim_revamp force=yes version={{ eclaim_branch }} key_file=~/.ssh/id_travis accept_hostkey=yes
  when: app_version == "eclaim_revamp"

Above is the declaration that I use to checkout my source code from bitbucket. Any help would be appreciated.
More information
I am running this playbook against a docker image I created.

A: Since the ansible git module should force the checkout (when using force=yes), stale files could be the result of a running process keeping an handle on files which should have been updated.
Check if that is the case, or if you see any error message.

From the Travis job (which fails), I can see:
TASK [app_server : Checkout eclaim source code] ********************************

task path: /root/django_deployment/django_app_server_db_server/deployment/roles/app_server/tasks/main.yml:122

skipping: [localhost] => {"changed": false, "skip_reason": "Conditional check failed", "skipped": true}

It might be fixed in issue 14438 (and Ansible 2.1)
But in this case, this is simpler: the Low Kian Seong confirms in the comments:

I am over-writing one of my own files!

So the checkout works fine, but some files get re-written.


text:
Q: Connect to Windows share from Red Hat machine via DNS name We have a Windows share \\server1\share
From a Red Hat machine, we can mount to the share without issue.
We have setup a DNS pointer that points to server1 and is named production.
From the Linux machine, we are able to ping production and we get the corresponding DNS address from server1 but we are unable to mount the share via the name \\production\share.
Anyone ever dealt with this?
Red Hat Enterprise Linux Server release 6.0

A: For future refference, the problem lay on the windows side. You must edit this key to get it to work:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Parameters\
DisableStrictNameChecking[REG_DWORD#32] = 1
Reboot and wahlah.


text:
Q: Export to a file from SQL Developer? I am trying to run the export command in SQL Developer. I get the error message "Unknown Command". Searching the web, I am told by many to run catexp.sql. I don't have that file, and I don't know how to download it. Can anyone help me run this command? How do I find catexp.sql? Using the export functionality is not a feasible option since I must run the code below  about 80 times.
exp username/password direct = y file = C:\mypath\mydata.csv tables = TABLE.TABLENAME query =\"Where rownum\<=5000000\"

Thanks in advance.

A: exp is a commandline program, not a SQL command.
You cannot run that from within any SQL client (including SQL Developer).
Additionally exp is somewhat deprecated anyway and you should use DataPump in order to export your data.
DataPump can be accessed through SQL using the dbms_datapump package and will write the dump file into a directory on the server.
dbms_datapump is documented extensively in the manual
There are also several examples available:

*

*http://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_api.htm

*http://psoug.org/reference/dbms_datapump.html

A: You can just write a query in SQL Developer:
select /*csv*/ * from tableName

Then copy/paste the results to a new file.
This question How to export query result to csv in Oracle SQL Developer? also has several other suggestions.


text:
Q: Scene not changing in SpriteKit I've created a game and now I want to add a start screen in which I want to run a video and after that there will be a screen with start button, I've searched over internet but couldn't find out the way to do it, have tried many things, the latest code is:
#import "FirstScreen.h"
#import "GameScene.h"
#import <MediaPlayer/MediaPlayer.h>

@implementation FirstScreen

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        NSURL *url =[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Intro" ofType:@"mp4"]];
        _player = [[MPMoviePlayerController alloc] initWithContentURL:url];
        _player.view.frame = CGRectMake(0,0, 1024, 768);
        [self.view addSubview:_player.view];

        _player.shouldAutoplay = YES;
        [_player prepareToPlay];

        NSString *nextSceneButton;
        nextSceneButton = @"Start";

        SKLabelNode *myLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];

        myLabel.text = nextSceneButton;
        myLabel.fontSize = 30;
        myLabel.fontColor = [SKColor blackColor];
        myLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
        myLabel.name = @"Start";

        [self addChild:myLabel];
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];

    if ([node.name isEqualToString:@"Start"]) {
        SKTransition *reveal = [SKTransition fadeWithDuration:3];

        GameScene *scene = [GameScene sceneWithSize:self.view.bounds.size];
        scene.scaleMode = SKSceneScaleModeAspectFill;
        [self.view presentScene:scene transition:reveal];
    }
}

@end

App just starts and give the SIGABRT error. Can you tell me how to do it?

A: You should check few things to make sure is everything okay there:

*

*Check if everything is okay with file name, look for spaces or typos etc...

*See what pathForResource returns (println it)

*See what fileURLWithPath returns

*Go to : Target -> Build Phases -> Copy Bundle Resources and add Intro.mp4 file there. If that file is already added , delete it, clean your project Project->Clean, and add it again. Build project and run it.


text:
Q: hive-metastore is not able to start in the cloudera manager installation process We are installing Cloudera CDH4 in Ubuntu 12.04 LTS, In the installation step we are stuck at hive meta-store start. We have configured the meta-store with MySQL as recommended in download documentation.
Its giving us the following error:
/usr/lib/hive/conf$ sudo service hive-metastore status
 * Hive Metastore is dead and pid file exists

In the log file its showing the following error:
ERROR metastore.HiveMetaStore (HiveMetaStore.java:main(4153)) - Metastore Thrift Server threw an exception...
org.apache.thrift.transport.TTransportException: No keytab specified

Following is out hive-site.xml file:
<property>
  <name>javax.jdo.option.ConnectionURL</name>
     <value>jdbc:mysql://my-local-system-ip:3306/metastore?createDatabaseIfNotExist=true</value>
  <description>JDBC connect string for a JDBC metastore</description>
</property>
<property>
  <name>javax.jdo.option.ConnectionDriverName</name>
  <value>org.apache.derby.jdbc.EmbeddedDriver</value>
<value>com.mysql.jdbc.Driver</value>
  <description>Driver class name for a JDBC metastore</description>
</property>
<property>
          <name>javax.jdo.option.ConnectionUserName</name>
          <value>hive</value>
    </property>
    <property>
        <name>javax.jdo.option.ConnectionPassword</name>
        <value>my-password</value>
    </property>
    <property>
  <name>datanucleus.autoCreateSchema</name>
  <value>false</value>
</property>
<property>
  <name>datanucleus.fixedDatastore</name>
  <value>true</value>
</property>

<property>
  <name>datanucleus.autoStartMechanism</name>
  <value>SchemaTable</value>
</property>
<property>
<name>hive.aux.jars.path</name>
  <value>file:///usr/share/java/mysql-connector-java.jar</value>
</property>
<property>
        <name>hive.metastore.uris</name>
        <value>thrift://<FQDN>:9083</value>
    </property>

<property>
  <name>hive.support.concurrency</name>
  <description>Enable Hive's Table Lock Manager Service</description>
  <value>true</value>
</property>
<property>
  <name>hive.metastore.local</name>
  <description>Enable Hive's Table Lock Manager Service</description>
  <value>false</value>
</property>

<property>
  <name>hive.server2.authentication</name>
  <value>KERBEROS</value>
</property>
<property>
  <name>hive.server2.authentication.kerberos.principal</name>
  <value>hive/_HOST@<my-domain-name></value>
</property>
<property>
  <name>hive.server2.thrift.port</name>
  <value>10001</value>
  <description>TCP port number to listen on, default 10000</description>
</property>

<property>
  <name>hive.server2.authentication.kerberos.keytab</name>
  <value>/etc/hive/conf/hive.keytab</value>
</property>

<property>
  <name>hive.zookeeper.quorum</name>
  <description>Zookeeper quorum used by Hive's Table Lock Manager</description>
  <value>FQDN</value>
</property>
<property>
<name>hive.metastore.sasl.enabled</name>
<value>true</value>
</property>
<property>
  <name>hive.zookeeper.client.port</name>
  <value>2181</value>
  <description>
  The port at which the clients will connect.
  </description>
</property>
   <property>
  <name>hive.metastore.schema.verification</name>
  <value>false</value>
</property>
<property>
<name>hive.server2.thrift.sasl.qop</name>
<value>auth</value>
<description>Sasl QOP value; one of 'auth', 'auth-int' and 'auth-conf'</description>
</property>
<property>
<name>hive.metastore.client.socket.timeout</name>
<value>3600</value>
<description>MetaStore Client socket timeout in seconds</description>
</property>

Our main focus is to install impala. If we use default derby. Hive meta-store is working perfectly. But when we start impala-shell. It shows us Not Connected. What can we do rectify this ?
Can anybody help us out to this error.

A: I think the issue is that you're missing the following parameter:
<property>
  <name>hive.metastore.kerberos.keytab.file</name>
  <value>/etc/hive/conf/hive.keytab</value>
  <description>The path to the Kerberos Keytab file containing the metastore thrift server's service principal.</description>
</property>

I see you do have hive.server2.authentication.kerberos.keytab, but it appears this is not enough.

A: replace "my-domain-name" in hive.server2.authentication.kerberos.principal property with your domain name. That is the third part which is missing in hive principal.


text:
Q: Figure next to text
Dear all,
As you can see on the above figure, I would like the text to be higher (like it should start at the top of the image).
My code is :
\begin{figure}[ht]
\centering
\includegraphics[scale=1]{Images/GIS_mapping_Software.jpg}
\caption{test}
\label{GIS_Mapping_Software}
\end{minipage}%
\begin{minipage}[t]{10cm}
As shown on figure ~\ref{GIS_Mapping_Software}, the purpose of the GIS is to display multiple maps on one single map.\\
For example, a single map could regroup sites that produces pollution and sensitive sites to pollution. \\
\end{minipage}
\end{figure}

Is there anyway I can change my code so that the text begins at the top of the image ?

A:
after correcting your code snippet and adding missed part of your document (that your code fragment become complete small document: observe preamble, where is added package which enable above solution).
\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage[export]{adjustbox}

\begin{document}
\begin{figure}[ht]
\begin{minipage}[t]{0.5\linewidth}
\centering
\includegraphics[%scale=1
                 width=0.9\linewidth, valign=t]{Images/GIS_mapping_Software.jpg}
\caption{test}
\label{GIS_Mapping_Software}
\end{minipage}%
\begin{minipage}[t]{0.5\linewidth}
As shown on figure ~\ref{GIS_Mapping_Software}, the purpose of the GIS is to display multiple maps on one single map.\\
For example, a single map could regroup sites that produces pollution and sensitive sites to pollution. \\
\end{minipage}
\end{figure}
\end{document}


text:
Q: How to fix Intent.getAction() error in services on Android In my application i want use one Service for record device screen and this name is RecorderService !
I write below codes, but in some devices when running service show ForceClose error and application has stopped !
My Service codes:
public class RecorderService extends Service {
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    private int WIDTH, HEIGHT, FPS, DENSITY_DPI;
    private int BITRATE;
    private boolean isBound = false;
    private String audioRecSource;
    private String SAVEPATH, videoName;
    private AudioManager mAudioManager;
    private FloatingControlService floatingControlService;

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 0);
        ORIENTATIONS.append(Surface.ROTATION_90, 90);
        ORIENTATIONS.append(Surface.ROTATION_180, 180);
        ORIENTATIONS.append(Surface.ROTATION_270, 270);
    }

    private int screenOrientation;
    private String saveLocation;

    private boolean isRecording;
    private NotificationManager mNotificationManager;
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message message) {
            Toast.makeText(RecorderService.this, "Service stoped", Toast.LENGTH_SHORT).show();
        }
    };

    private Intent data;
    private int result;

    private WindowManager window;
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private MediaProjectionCallback mMediaProjectionCallback;
    private MediaRecorder mMediaRecorder;

    //Service connection to manage the connection state between this service and the bounded service
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //Get the service instance
            FloatingControlService.ServiceBinder binder = (FloatingControlService.ServiceBinder) service;
            floatingControlService = binder.getService();
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            floatingControlService = null;
            isBound = false;
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        videoName = GoodPrefs.getInstance().getString(ConstKeys.TEST_NAME, "Testady");
        //return super.onStartCommand(intent, flags, startId);
        //Find the action to perform from intent
        switch (Objects.requireNonNull(intent.getAction())) {
            case ConstKeys.SCREEN_RECORDING_START:
                if (!isRecording) {
                    screenOrientation = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
                    data = intent.getParcelableExtra(ConstKeys.RECORDER_INTENT_DATA);
                    result = intent.getIntExtra(ConstKeys.RECORDER_INTENT_RESULT, Activity.RESULT_OK);

                    getValues();

                    startRecording();

                    openTestApp();

                } else {
                    Toast.makeText(this, "Service has running", Toast.LENGTH_SHORT).show();
                }
                break;
            case ConstKeys.SCREEN_RECORDING_PAUSE:
                break;
            case ConstKeys.SCREEN_RECORDING_RESUME:
                break;
            case ConstKeys.SCREEN_RECORDING_STOP:
                stopRecording();
                break;
        }

        return START_STICKY;
    }
}

logcat error (get this error from firebase):
Caused by java.lang.NullPointerException
Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
com.app.app.services.RecorderService.onStartCommand (RecorderService.java:126)
android.app.ActivityThread.handleServiceArgs (ActivityThread.java:3028)
android.app.ActivityThread.access$2200 (ActivityThread.java:157)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1454)
android.os.Handler.dispatchMessage (Handler.java:102)
android.os.Looper.loop (Looper.java:148)
android.app.ActivityThread.main (ActivityThread.java:5525)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:730)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:620)

Show me error for this error : switch (Objects.requireNonNull(intent.getAction()))
I start service with this codes:
Intent recorderService = new Intent(this, RecorderService.class);
    recorderService.setAction(ConstKeys.SCREEN_RECORDING_START);
    recorderService.putExtra(ConstKeys.RECORDER_INTENT_DATA, data);
    recorderService.putExtra(ConstKeys.RECORDER_INTENT_RESULT, resultCode);
    startService(recorderService);
    finish();

How can i fix it?


text:
Q: Create-react-app with node-sass doesn't catch/persist @debug/@warn rule in terminal I have used create-react-app and installed node-sass as a depandency. The react version is V16.13.1., and the node-sass version is V4.14.1. Both should be the latest version as then.
My question is if I use @debug $some-variable in my scss file, it doesn't show up in my terminal. However, what is interesting is when I kill the terminal and restart it again, it pops up for a fraction of second and disappear again. The same happens to @warn rule as well.
The workaround is to use @error instead, @error rule always intercepts the terminal and 100% pops up errors, I used it as a work around to debug my scss code.
But I believe the problem is on node-sass side, @debug/@warn should print out something, but just got overwritten on react scripts side, i.e. by "react-scripts start" script. In my opinion, there should be a way to block react side to do that, and persist the stdout info on the terminal. Maybe add a flag into node-sass or modify the start script on react side?
I hope I got the problem addressed properly. Does anyone has experience on this issue? Please advise.
Example code:
In foo.scss file:
   @debug "hello world"  // it does not print anything in terminal
   @warn "this is a warning" // it does not print anything in terminal either
   @error "it definately catch this"  // the error shows up in terminal only


text:
Q: Regarding forward declaration c++ class I have two classes like this:
class B;

class A {
public:
  int a, b;
  B *b;
public:
  int getctxt()
  {
     b->getctxt1();
  }
}

Class B {
public:
  int c,d;
  A *a;
  getctxt1()
  {
      /* something */
  }
}

main()
{
  B *b = new B();
  A *a = new A();
  b->a = a;
  a->b = b;
}

But when I try to compile, it says

invalid use of incomplete type 'struct A'.

Can anyone tell me how to solve this?

A: Inline class member function definitions are parsed as if they appeared right after the class definition. Of course B isn't defined at that point. So move the member function definition for A::getctxt out of the definition of class A:
class B;

class A { int getctxt(); /* ... */ };

class B { /* ... */ };

int A::getctxt()
{
    b->getctxt1();   // at this point, *b has complete type!
    return -35;
}

A: This is the reason why it is recommended to separate your classes in a .h file and a .cpp file. When you write class B;, you are telling the compiler that there is a class called B, but that's it, the compiler does not know what is inside this class. When the compiler reaches the line b->getctxt1();, it knows that b is an instance of B, but it does not know if getctxt1() is a method of B, because that is below. If you are writing all in a single file, you should first write all the declarations, and then all the implementations.

A: didn't anyone notice Class B syntax error? lowercase class is correct.
and those two public members in A with the same name int b and B *b.
once you remove those and finish class definitions with semicolons, add a void type to the void getctxt1() that is missing it in B.
just define functions as they should be defined. not inline without a reason that you know which is!


text:
Q: Doesn't Lua have something comparable to Ruby's method_missing? I seem to recall Lua has something similar to Ruby's method_missing.  Or am I remembering incorrectly?

A: The __index and __newindex of a table's metatable can be used to the same effect as Ruby's method_missing.


text:
Q: A way to get the exact discord message content If you type :a: or :gun:, it sends an emote in discord.
What I'm trying to do, is if someone sends just the string that is in between those : (that is, in this case, I showed, 'a' or 'gun'), my bot would analyze it and check if it can be 'translated' to an emote.
I tried to do:
if (msg.content.length === 1)

But msg.content keeps on being :(string): so it doesn't work.
I am currently searching for other ways and will keep this updated. Any tips will be highly appreciated!
Edit: Went with this api as I found no other way

A: There are a couple caveats with this: 1) There does not appear to be anyway of checking against standard emojis; only guild (i.e. custom) emojis. 2) It may be possible with a 3rd-party plugin.
Regarding #1, this will translate a message into a GUILD emoji:
const emoji = message.guild.emojis.cache.find(e => e.name === message.content);

if (emoji) {
    message.channel.send(`<:${emoji.name}:${emoji.id}>`);
}

Regarding #2, check out emoji-regex. From what I can tell, convert the message to an emoji, and compare it to what emoji-regex tells you. If it matches, then you can send the emoji.


text:
Q: why updating formula, title in large list/library programmatically takes really long time I have to update formula of calculated field. I wrote method for that, it is working fine and is updating formula as well. But it takes really long time to update formula in large library ie library with more than 5000 documents.
    private void changeFormulaForThisField(SPField field, String newFormula)
    {
        if (field.Type == SPFieldType.Calculated)
        {
            SPFieldCalculated calcField = (SPFieldCalculated)field;

            if (calcField.Formula == newFormula)
            {
                writeLogMessage("Column [" + field.Title + "], Old and new formula same");
            }
            else
            {
                calcField.Formula = newFormula;

                if (!TESTMODE)
                {
                    calcField.Update(true);
                }

                writeLogMessage("Column [" + field.Title + "], updating formula...done");
            }
        }
    }

I checked doing same ie updating formula using SharePoint UI. It seems it also depends on number of documents in library. For small library, it is really fast. For large library, it takes also  long time in UI, but not so long as using my code.
Am I doing something wrong or inefficient way in my code ? Does updating formula/title for one spfield also needs to update formula/title for each items or what ?  Have you experienced such behaviour before ?
Any response would be helpful.
Thanks.

A: Calculated columns in SharePoint are precalculated, the assumption being that they are going to be used a lot more than changed.
So when you change the formula SharePoint has to update the calculated value in each item.


text:
Q: Python MVC architecture Temperature Conversion: Why am I getting "NameError: global name 'view' is not defined" This isn't a difficult question, but I can't wrap my head around it when dealing with MVC architecture (passing arguments between the VIEW, MODEL, and CONTROLLER).
Error in question:

Exception in Tkinter callback Traceback (most recent call last):
  File "C:\Python33\lib\tkinter__init__.py", line 1482, in call
      return self.func(*args)   File "C:\Users\Mike\Desktop\code\Assignment 6\glue.py", line 37, in
  buttonPressed
      self.model.convertTempF2C(view.fahrenheitEntrySpace.get) NameError: global name 'view' is not defined

The VIEW (myFrame.py)
"""writing event handlers"""

import tkinter
import glue
class MyFrame(tkinter.Frame): #creates window for controls in an object made
                              #from a class called "tkinter.Frame"
    """
    Class myFrame is a tkinter.Frame...
    It contains two buttons, two entry areas, and four labels:
    one button a converter;
    one button quits the program;
    one entry is for celsius;
    one entry is for fahrenheit;
    and the labels prompt user for input, and label the entry values as needed.
    """

    def __init__(self, controller):
        """
        places the controls on the frame
        """
        tkinter.Frame.__init__(self) #initilizes the superclass
        self.pack()  #required for the buttons to show up properly.
        self.controller = controller #saves ref to controller to call methods on
                                          #contoller object when user generates events

#Fahrenheit Input Prompt
        self.fahrenheitLabel = tkinter.Label(self)
        self.fahrenheitLabel["text"] = ("Enter Fahrenheit Value:")
        self.fahrenheitLabel.pack({"side":"left"})

#Fahrenheit Entry Space
        self.fahrenheitEntrySpace = tkinter.Entry(self)
        self.fahrenheitEntrySpace == self.fahrenheitEntrySpace.insert(1, "0")  #creates starting value of 0
        self.fahrenheitEntrySpace.pack({"side":"left"})

#Fahrenheit Value label (double checked)
        self.fahrenheitLabel = tkinter.Label(self)
        self.fahrenheitLabel["text"] = ("Fahrenheit Degrees")
        self.fahrenheitLabel.pack({"side":"left"})

#Converter button (double checked)
        self.convertButton=tkinter.Button(self)
        self.convertButton["text"]= "Convert"
        self.convertButton["command"]=self.controller.buttonPressed
        # an object that remembers both self and reply when later called
        self.convertButton.pack({"side":"left"})

#Quit button
        self.quitButton = tkinter.Button(self)
        self.quitButton["text"] = "Press\nhere to\n***QUIT***"
        self.quitButton["command"] = self.quit
        #the statement above attaches the event handler
        #self.quit() to the quit button
        self.quitButton.pack({"side":"right"})

#Celsius Value label
        self.celsiusLabel = tkinter.Label(self)
        self.celsiusLabel["text"] = ("Celsius Degrees")
        self.celsiusLabel.pack({"side":"right"})

#Celsius Entry Space
        self.celsiusEntrySpace = tkinter.Entry(self)
        self.celsiusEntrySpace["text"] == self.celsiusEntrySpace.insert(1, "0") #creates starting value of 0
        self.celsiusEntrySpace.pack({"side":"right"})

#Celsius Input Prompt
        self.celsiusLabel = tkinter.Label(self)
        self.celsiusLabel["text"] = ("Enter Celsius Value:")
        self.celsiusLabel.pack({"side":"right"})

#Test program
if __name__=="__main__":
    root = tkinter.Tk()
    view = MyFrame() #puts the frame onto the user's screen.
    view.mainloop()
    root.destroy()

The MODEL (counter.py)
import tkinter
import glue

class Convert: #the MODEL

    '''
    class counter is the MODEL for a simple program that exemplifies
    the MODEL/VIEW/CONTROLLER achitecture.

    It mostly just maintains two formulas that convert Fahrenheit to Celsius
    and Celsius to Fahrenheit each time the f2C() or c2F methods are called.

    in a real MVC app, the MODEL would contain all the business logic.
    Note that the model never contains a reference to the VIEW.
    '''
    def __init__(self):
        self.fahrenheitEntrySpace = 0
        self.celsiusEntrySpace = 0

    def convertTempF2C(self):
        fahrenheit = controller.fahrenheitEntrySpace
        if fahrenheit != 0.0:
            controller.celsius = (fahrenheit - 32) * 5 / 9
        else:
            contoller.celsius = -17.7777778

    def convertTempC2F(self):
        celsius = celsiusEntrySpace.get()
        if celsius != 0.0:
            controller.fahrenheit = (celsius *  9.0/5.0 + 32)
        else:
            controller.fahrenheit = 32

    def __str__(self):
        return str(self.counter)

The Controller (glue.py)
#Event Handler for a button in tkinter is self.yourButton["Command"] = self.yourObject.yourObjectMethod()

import tkinter
import myFrame #the VIEW
import counter #the MODEL

class Controller():

    """
    The CONTROLLER for an app that follows the MODEL/VIEW/CONTROLLER architecture.
    When the user presses a button on the VIEW,
    this controller calls the appropriate methods in the model.
    The controller handles all the communication between the model and the view.
    """

    def __init__(self):

        """
        This starts the TK framework up;
        instantiates the model;
        instantiates the VIEW;
        and states the event loop that waits for the user to press a button on the view
        """
        root = tkinter.Tk() #This starts the TK framework up;
        self.model = counter.Convert() #instantiates the model
        self.view = myFrame.MyFrame(self) #instantiates the VIEW
        self.view.mainloop() # states event loop waits for user to press button on view
        root.destroy() #lets user quit

    def buttonPressed(self):

        """
        Convert F --> C
        """

        self.model.convertTempF2C(view.fahrenheitEntrySpace.get)
        #MODEL creates new celsius temp from(fahrenheit input)

        self.view.celsiusEntrySpace.pop()
        #replaces VIEW's old default celsius value

        self.view.celsiusEntrySpace.insert(self.model.celsius)
        #and insert's MODEL's newly converted (celsius) value

        """
        Convert C --> F
        """

        self.model.convertTempC2F(self.celsiusEntrySpace.get)
        #MODEL creates new fahrenheit temp from  (celsius input)

        self.view.fahrenheitEntrySpace.pop()
        #replaces VIEW's old default 0 fahrenheit value

        self.view.fahrenheitEntrySpace.insert(self.model.fahrenheit)
        #and insert's MODEL's newly converted (fahrenheit) value

if __name__=="__main__":
    c = Controller()

As continued from:
Python Temperature conversion MVC style: why am I getting "TypeError: buttonPressed() missing 1 required positional argument: 'self'"

A: I think NamerError happens, because of wrong folder structure.
You should have for example
app/
|__init__.py
|counter.py
|myFrame.py

and then put all glue.py code to __init__.py, but change imports of  counter.py and myFrame.py. Move imports to the end of __init__.py:
from app import myFrame
from app import counter


text:
Q: problem in getting gps coordinates in android 2.1(Found Answer) I am having a problem in getting GPS coordinates in 2.1.
The code i am using right now is working well in 1.6 but when i test
this same apk in 1.6 device is showing null values
please help me to find a way to work with 2.1 devices also
Here is my code.
public class GpsLocator {

   private static String PROVIDER="gps";
   private LocationManager myLocationManager=null;

   public GpsLocator(Context context) {
      myLocationManager=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
   }

   public void myOnresume() {
      myLocationManager.requestLocationUpdates(PROVIDER, 0,   0, onLocationChange);
   }

   public void myonPause() {
       myLocationManager.removeUpdates(onLocationChange);
   }

   public double getLatitude() {
      Location loc=myLocationManager.getLastKnownLocation(PROVIDER);
      if (loc==null) {
         return(0);
      }
      return(loc.getLatitude());
   }

   public double getLongitude() {
      Location loc=myLocationManager.getLastKnownLocation(PROVIDER);
      if (loc==null) {
         return(0);
      }

      return(loc.getLongitude());
   }

   LocationListener onLocationChange=new LocationListener() {

      public void onLocationChanged(Location location) {
      }

      public void onProviderDisabled(String provider) {
         // required for interface, not used
      }

      public void onProviderEnabled(String provider) {
         // required for interface, not used
      }

      public void onStatusChanged(String provider, int status,Bundle extras) {
         // required for interface, not used
      }
   };
}

in the manifest file i add permission for accessing file they are
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

A:     LocationManager locationManager;
    String context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager)getSystemService(context);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String provider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(provider);

    updateWithNewLocation(location);

    locationManager.requestLocationUpdates(provider, 2000, 10,
                                           locationListener);
  }

  private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      updateWithNewLocation(location);
    }

    public void onProviderDisabled(String provider){
      updateWithNewLocation(null);
    }

    public void onProviderEnabled(String provider){ }
    public void onStatusChanged(String provider, int status,
                                Bundle extras){ }
  };

A: LocationManager.getLastKnownLocation does not guarantee that it will return a valid location. If a GPS fix hasn't been established yet, it will return null. The only reliable way to get an actual location is to use the LocationListener -interface. I see that you have defined a LocationListener, but aren't using it.
You need to modify your code so that it waits for the first call to onLocationChanged before you try to do anything with the location.

A: Hi I am also facing same problem in 2.1  after i resolved like this...
it  will work for you
myManager = ((LocationManager) ApplicationController.getAppContext()
            .getSystemService(Context.LOCATION_SERVICE));

myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            1 * 1000, 0.00001f, this);

Follow location changed asy method in tha u will get lat/and long
don't use bundle object over there it wont work instead of that you can use Gps Satellite class for 2.1..


text:
Q: ASP.Net Calling method from another namespace I have two projects, the first one with a ClassLibraryServer namespace and Output method as following :
   namespace ClassLibraryServer
   {
   public class Output
   {
      public static void Card(tblCard card, int myProperty)
      {
        if (kort.fltNr.Length != 6)
            return;

        using (myDataContext db = new myDataContext(ClassLibrary.Settings.Instance.SqlS))
        {
            tblReader[] readers = (from row in db.tblReader
                                   where !row.fltOffline
                                   select row).ToArray();

            bool blocked = (db.tblCardBlocked.Where(b => b.fltProperty == myProperty && b.fltCard == card.id).FirstOrDefault() != null);

            foreach (tblReader reader in readers)
            {
                Card(card, reader, blocked);
            }
        }
      }
    }
    }

The Card method in foreach loop calls another method (Overloading the first card method) which has three parameters and inserts data to a sql table, I won't share it here as it takes too much space.
Now I want to call above method in another project with namespace ExtControlModule:
          namespace ExtControlModule

          {
            public class TimeModule
            {
             using (ModuleDataContext dbsys = new ModuleDataContext(ClassLibrary.Settings.Instance.SqlS)) {
                var loungee = (from tblLounge in dbsys.tblLounges
                               select tblLounge).ToList();

                 var lasaresFas = 0;
                 foreach (var LoungeRow in loungee)
                 {
                 lasaresFas= Convert.ToInt32(dbsys.tblLasares.FirstOrDefault(f => f.id == LoungeRow.fltCardreader).fltproperty);

                 tblCard cardLoading = dbsys.tblCard.FirstOrDefault(t => t.id == res.fltCardnumber);
                 Output.Card(cardLoading, lasaresFas);
                 }
             }
          }

Now when I want to assign parameters to Output.Card in ExtControlModule I get the following error in cardLoading parameter in Output.Card:
Argument !: cannot convert from 'ExtControlModule.tblCard' to ClassLibrary.db.tblCard'
ClassLibrary is another project in the same Solution which contains a public class Settings with the SqlS property which facilitate connection to SQL database.
Struggling with this for many days as I am new to both ASP.NET and Sql, hope my question is clear enough.

A: call method
ClassLibraryServer.Output.Card(cardLoading, lasaresFas);


text:
Q: How should I make a route for each page in Laravel5.2? Im new to L5 and here, stackoverflow.
I'm making a Blog service based on Repository pattern.
Now I've made some Service class(like ImageService, PostService, CommentService...) and Repositories as data access object.
From now, I will make views. First, "Top page" I would like to.
Need to inject 2 Service class. "ImageService(allUsersImages)", "PostService(allUsersPosts)".
I am stopping here....bothering what the best way.
please let me know if my thought is good, or is there any way?
1.Creating Controller

class IndexController extends Controller
{
    public function top(ImageRepository $image, PostRepository $post)
    {
        $images= $image->allUsersImages();
        $posts= $post->allUsersPosts();

        return view('/index')
                 ->with('images', $images)
                 ->with('posts', $posts);
    }

    public function mypage(ImageRepository $image,
                           PostRepository $post, $id)
    {
        $images= $image->allUsersImagesById($id);
        $posts= $post->allUsersPosts($id);

        return view('/index')
                 ->with('images', $images)
                 ->with('posts', $posts);
    }
                          .
                          .
                          .
                          .
                   prepare methods for each page

    }

2. Creating routing

    Route::get('/top', 'IndexController@top');
    Route::get('/mypage', 'IndexController@mypage');
                    .
                    .
                    .

A: Well i think what you already doing is also pretty good.
class IndexController extends Controller
{
    public function top(ImageRepository $image, PostRepository $post)
    { }
}

When you write something like this, Laravel Dependancy Manager will inject ImageRepository and PostRepository for you  to the function top() {}
Now your question is is there any a better approach then this ?
IMHO:
You don't need to ask the dependancy manager to do this work for you.
Just Use the ImageRepository and PostRepository in the function like this.
    class IndexController extends Controller
    {
        public function top()
        {
              $image_repository = new ImageRepository();
              $post_repository = new PostRepository();
        }
    }

Now what i understand is ImageRepository and PostRepository are your DAL(Data Access Layer) or maybe a wrapper around your ORM (Models), then why using a wrapper around Models, why not using directly models, Since you don't have methods sharing the repository in single page accesss. Just invoke the models directly. These are safe and common practice in laravel.


text:
Q: How to refactor a Java file which has more than 50000 lines? I have a java class which has more than 50,000 lines of codes. I want to refactor it and make multiple small classes.
I have tried making child classes but there are challenges (correct me if I am wrong)
a. we cannot call child method with parent object!
b. Furthermore, we can not call a method which is in child from parent.
public class Parent {

    public void a(){
        System.out.println("Parent :: a");
        b();          //point b
    }
}

public class Child extends Parent{

    public void b(){
        System.out.println("Child :: m");
    }
}

public class Main {

    public static void main(String[] args) {
        Parent p = new Parent();
        p.b();         //point a

        Child c = new Child();
        c.a();
    }
}

Edit: The parent class is a @ManagedBean class ( I am using JSF and Spring ).

A: Point B
You can, it's called the template method pattern. A parent may define

the skeleton of an operation in terms of a number of high-level steps. These steps are themselves implemented by additional helper methods in the same class as the template method.
The helper methods may be either abstract methods, for which case subclasses are required to provide concrete implementations, or hook methods, which have empty bodies in the superclass.

The highlighted part is what I would prefer.
public abstract class Parent {
    public void a(){
        System.out.println("Parent :: a");
        b();
    }
    public abstract void b();  // shouldn't necessarily be public
}

public class Child extends Parent {
    @Override
    public void b(){
        System.out.println("Child :: m");
    }
}

Point A
You can't, it's not a part of parent's interface. Either add the method to the parent or rethink why it's called on a parent reference.

A: A and B can be achieved by the use  of polymorphism
public class Parent {

    public void a(){
        System.out.println("Parent :: a");
        b();          //point b
    }

    public void b() {
         System.out.println("not in use");
    }
}

public class Child extends Parent{

    @Override
    public void b(){
        System.out.println("Child :: m");
    }
}

    public class Main {

    public static void main(String[] args) {
        Parent p = new Child();
        p.b();
        p.a();

    }
}

results:
Child:: m
Parent:: a
Child:: m


text:
Q: Is there a rioxarray version of xarray pad I have a geocoded raster that I'd like to pad with NaNs to 64 x 64 pixels. I've tested rioxarray.DataArray.pad_box(), which does work, but it's a bit complex to calculate new bounding box corners that will give said shape.
Is there a way to simply pad the raster to my desired output shape? Like xarray's DataArray.pad(), but that computes the new spatial coordinates as well, which xarray doesn't do.
Example of xarray's pad:
import xarray as xa
import rioxarray as rioxa

im_xa = xa.DataArray(np.random.randint(0, 255, (37, 33), dtype="uint8"),
          dims=('y', 'x'), coords={'x': np.linspace(447560, 447960, 33),
            'y': np.linspace(6760930, 6761380, 37)})
im_xa = im_xa.rio.write_crs(3006)
xleft = np.ceil((64 - im_xa.shape[1]) / 2).astype('int')
xright = np.floor((64 - im_xa.shape[1]) / 2).astype('int')
yleft = np.ceil((64 - im_xa.shape[0]) / 2).astype('int')
yright = np.floor((64 - im_xa.shape[0]) / 2).astype('int')
im_xa_pad = im_xa.pad({'x': (xleft, xright), 'y': (yleft, yright)})

Windows 10, Python 3.8.2, xarray 0.15.1, rioxarray 0.1.1


text:
Q: How can i get post with multiple dynamic taxonomies I am filtering custom post types using ajax. I am able to filter using single taxonomy but how to filter results with multiple taxonomies.
This is the query i tried:
Code:
$args=array('orderby'=>'date','post_status'=>'publish');

//sort by bank if isset
if(isset($_POST['bank']))
{
    $args['tax_query']=array(
        array(
                'taxonomy'=>'banks',
                'field'=>'id',
                'terms'=>$_POST['bank']
        )
    );
}
if(isset($_POST['card_type']))
{
    $args['tax_query']=array(
        'relation'=>'AND',
        array(
                'taxonomy'=>'cardtype',
                'field'=>'id',
                'terms'=>$_POST['card_type']
        )
    );
}
$query=new WP_Query($args);

But it only shows result with filtering from one taxonomy not both.

A: I think you are working on right track but a small mistake in argument may cause result to be rendered wrong.
Instead of 'relation'=>'AND', use 'relation'=>'OR'
'relation'=>'AND' will fetch result when both taxonomy condition match, while 'relation'=>'OR' condition will compare with any of the taxonomy.
click here to view the WP Query arguments
Actually yout array formation is wrong for tax_query.
Please check updated code below.
If you don't use $args['tax_query']['relation']=   'AND', then also it will work for you.
Please have a try with below code snippet.Update you code with below snippet.
$args = array(
            'orderby'=>'date',
            'post_status'=>'publish'
        );

//sort by bank if isset
if(isset($_POST['bank'])){
    $args['tax_query'][]= array(
                'taxonomy'=>'banks',
                'field'=>'id',
                'terms'=>$_POST['bank']
                );
}
if(isset($_POST['card_type'])){
    $args['tax_query']['relation']=   'AND';//you can remove this

    $args['tax_query'][]=   array(
                            'taxonomy'=>'cardtype',
                            'field'=>'id',
                            'terms'=>$_POST['card_type']
                    );

}
$the_query = new WP_Query( $args );


text:
Q: Is there any algorithm that is O(n) time and necessarily uses O(n) auxiliary space? I have noticed that problems that can be solved in linear time can be tweaked to use no more than O(1) auxiliary space. Take Weighted Indepented Set problem for path graphs. If only total weight is required, it takes O(1) space. But if set is also asked for in solution, then it uses O(n) space, however, auxiliary space used is still O(1). Other problems that admit linear time algorithms are Maximum Subarray Sum problem, rotating a 1D vector by i positions, convert a BST to a sorted doubly linked list, etc...

A: The Z algorithm, linear-time suffix array generation, the Burrows-Wheeler Transform, etc. all need O(n) auxiliary space.
Actually, I think even depth-first search, breadth-first search, etc. require O(n) auxiliary space in their worst cases (linked list for DFS, single-layer tree for BFS).


text:
Q: Prove Wold's theorem from abstract Wold's decomposition I see that Wold's theorem in time series analysis is proven by the abstract Wold's decomposition in operator theory. The abstract theorem states that:

Every isometry is a direct sum of copies of the unilateral shift and a unitary operator.

I want to understand intuitively the connection between the two theorems: so in the time series version $Y_t = \sum_{j=0}^\infty b_j \epsilon_{t-j} + \eta_t$, which are the isometry, the shift and the unitary operator?
PS: I see in some document which states the lag operator is the isometry, then which is the shift operator in the time series version?


text:
Q: Googletest usage I want to use gtest/gmock for TDD for my project, but can't figure out how. I want to split tests for each of the classes into a separate module, but that doesn't work, because the project can only have 1 main() function.
Given:
'lib' project, that produces a lib.
'main' project, that has the main() function of my application, that does the useful stuff.
'test' project, that links to the 'lib' project and I want to have all unit tests in this project.
My problem is that the 'test' project can only have 1 main() function, that runs all tests, but I want to have 1 main() function in each of the modules.
For example, my 'lib' project has classes Foo and Bar, I want to test those classes independently, having tests for Foo in foo_test.cc and tests for Bar in bar_test.cc. As far as I understand, each of the modules {foo_test.cc, bar_test.cc} needs to have a main() that runs its tests, but the project can only have 1 main() function.
Please let me know if any of my assumptions are wrong. I'd be surprised if there was no easy way to test each of the classes independently. As I have ~20 classes, creating 20 test projects is not an option.
Thanks in advance!

A: There must be exactly one main function in a C++ program. So if you
want one gtest test-runner for each class Foo, Bar,... that you want to test then you
must write a separate test-runner program for each of Foo, Bar, ... etc.
The test-runner for class Foo must compile only tests of class Foo, so you must
write these tests in a source file or set of source files distinct from the test sources for
any of the other classes. Similarly the the test-runner for class Bar, etc.
All of these test runners will link to the same library that contains the
implementations of Foo, Bar,... etc. The linkage of each test runner will
not pull in any object files from the library that it does not need.
However there is no need, and it will be pointlessly cumbersome, to write a test-runner for class Foo and another
one for Bar, and so on, to run the Foo tests and the Bar tests independently.
With a single test runner for the whole library, just make use of the the
--gtest_filter=<pattern> commandline option to select the Foo tests, or the
Bar tests, etc. Read Running a Subset of the Tests
in the manual.


text:
Q: How to replace last character in a string with white space in the end I have this kind of scenario in java, the last character : or - in a string should be replaced with "".
Example:
String value = "data - ";

String value2 = "data :";

value.replaceAll("[-:]$","");

value2.replaceAll("[:-]$","");

System.out.println(value);

System.out.println(value2);

Output:
data -

data

I think the whitespace treated as the last character and does not match the regex provide, can someone help me with this scenarion? thank you.

A: private static String strip(String s) {
    if (s.endsWith(":") || s.endsWith("-")){
        s = s.substring(0, s.length()-1);
    }
    return s;
}

A: you can use value.trim() to remove any extra spaces.


text:
Q: Boot randomly leaves eth1 unable to send but can receive On my Ubuntu 14.04 server with dual NICS the NIC connected to the router, eth1, will, just after boot randomly be in a state in which it can listen but not send.  I use Wireshark to monitor the interface.  The router is working.
The card is a PCI Express, Intel PRO/1000 Network Connection.
I have not noticed any differences in DMESG output - it always reports that eth1 is up.  ifconfig eth1 output looks normal as well except that the transmit packages count is always low.
Another anomaly is that DMESG reports that IPv6 is involved with both interfaces but I don't and won't be using IPv6.
eth0 works just fine - it's a direct connection to a device.
I see that I have warnings that ACPI has resource 'conflicts' but no other boot warnings. The computer is essentially a (custom) desktop, not a notebook.
How do I troubleshoot this?  Are there other logs I should examine or troubleshooting commands? Somehow install a different driver?
I'm just a LINUX user trying to learn enough to get a machine working correctly.
EDIT
There is no difference between the outputs of either "route -n" nor "ip route" except that the order of the last two lines output by route-n may reversed. I don't have enough data to know if they are always reversed. 169.254.19.63 is the directly connected device and 192.168.11.0 is the router.
SUCCESS
ip route
default via 192.168.11.1 dev eth1
169.254.19.63 dev eth0  scope link
192.168.11.0/24 dev eth1  proto kernel  scope link  src 192.168.11.219
192.168.11.0/24 dev eth0  proto kernel  scope link  src 192.168.11.211
route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.11.1    0.0.0.0         UG    0      0        0 eth1
169.254.19.63   0.0.0.0         255.255.255.255 UH    0      0        0 eth0
192.168.11.0    0.0.0.0         255.255.255.0   U     0      0        0 eth1
192.168.11.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0

FAILURE
ip route
default via 192.168.11.1 dev eth1
169.254.19.63 dev eth0  scope link
192.168.11.0/24 dev eth0  proto kernel  scope link  src 192.168.11.211
192.168.11.0/24 dev eth1  proto kernel  scope link  src 192.168.11.219
route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.11.1    0.0.0.0         UG    0      0        0 eth1
169.254.19.63   0.0.0.0         255.255.255.255 UH    0      0        0 eth0
192.168.11.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0
192.168.11.0    0.0.0.0         255.255.255.0   U     0      0        0 eth1

EDIT
Changed the IP address of eth0 to 169.254.19.211, the same domain as the device. eth1 still often fails.  Below is the output for route -n and ip route.  I attempted ssh and http connections from a notebook to the computer during the "failed" state this time they worked!  Wireshark shows that nothing is emitted from eth1 if I attempt a ping or load a web page on eth1 but does show the traffic from inbound ssh and web pages.
Identical for eth1 both working and not.
ip route
default via 192.168.11.1 dev eth1
169.254.0.0/16 dev eth0  proto kernel  scope link  src 169.254.19.211
169.254.19.63 dev eth0  scope link
192.168.11.0/24 dev eth1  proto kernel  scope link  src 192.168.11.219
route -n
Kernel IP routing table
Destination    Gateway        Genmask         Flags Metric Ref    Use Iface
0.0.0.0        192.168.11.1   0.0.0.0         UG    0      0        0 eth1
169.254.0.0    0.0.0.0        255.255.0.0     U     0      0        0 eth0
169.254.19.63  0.0.0.0        255.255.255.255 UH    0      0        0 eth0
192.168.11.0   0.0.0.0        255.255.255.0   U     0      0        0 eth1

EDIT
The .../interfaces and .../70-persistent-net.rules are below. Are you suggesting that it would be better if I exchange eth0 for eth1 and vice versa?
I have no idea how to set the route by hand.
/etc/network/interfaces (updated 26 Jan)
# The loopback network interface
auto lo
iface lo inet loopback

# primary network interface left port
auto eth0
iface eth0 inet static
address 192.168.11.219
netmask 255.255.255.0
gateway 192.168.11.1
dns-nameservers 99.99.99.53 8.8.8.8 8.8.4.4

# The camera interface right port
auto eth1
iface eth0 inet static
address 169.254.19.211
pointtopoint 169.254.19.63

############# assign camera to eth0  #############
post-up route add 169.254.19.63 eth0
post-up route add default gw 192.168.11.1 eth1

/etc/udev/rules.d/70-persistent-net.rules (updated 26 Jan)
# PCI device 0x8086:0x1533 (igb)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:01:05:19:7d:59",    ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"

# PCI device 0x8086:0x153a (e1000e)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:01:05:19:7d:58", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"

EDIT
uname -a
Linux fireimager 3.13.0-44-generic #73-Ubuntu SMP Tue Dec 16 00:22:43 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

sudo lspci -v | awk '/Eth/' rs=
00:19.0 Ethernet controller: Intel Corporation Ethernet Connection I217-LM (rev 04)
02:00.0 Ethernet controller: Intel Corporation I210 Gigabit Network Connection (rev 03)

iptables
~$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate     RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:4960
ACCEPT     tcp  --  anywhere             anywhere             tcp dpts:4955:4956
ACCEPT     udp  --  anywhere             anywhere             udp dpt:4958
ACCEPT     udp  --  anywhere             anywhere             udp dpt:domain
ACCEPT     icmp --  anywhere             anywhere             icmp fragmentation-needed
ACCEPT     icmp --  anywhere             anywhere             limit: avg 10/sec burst 5
DROP       all  --  anywhere             anywhere

Chain FORWARD (policy DROP)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain LOGNDROP (0 references)
target     prot opt source               destination
LOG        tcp  --  anywhere             anywhere             limit: avg 5/min  burst 5 LOG level debug prefix "Denied TCP: "
LOG        udp  --  anywhere             anywhere             limit: avg 5/min burst 5 LOG level debug prefix "Denied UDP: "
LOG        icmp --  anywhere             anywhere             limit: avg 5/min burst 5 LOG level debug prefix "Denied ICMP: "
DROP       all  --  anywhere             anywhere

EDIT - it's eth0 with driver igb that is misbehaving.
~$ sudo lspci -v | awk '/Eth/' RS=
00:19.0 Ethernet controller: Intel Corporation Ethernet Connection I218-LM (rev 04)
    Subsystem: Intel Corporation Device 0000
    Flags: bus master, fast devsel, latency 0, IRQ 44
    Memory at f7c00000 (32-bit, non-prefetchable) [size=128K]
    Memory at f7c3d000 (32-bit, non-prefetchable) [size=4K]
    I/O ports at f080 [size=32]
    Capabilities: [c8] Power Management version 2
    Capabilities: [d0] MSI: Enable+ Count=1/1 Maskable- 64bit+
    Capabilities: [e0] PCI Advanced Features
    Kernel driver in use: e1000e
02:00.0 Ethernet controller: Intel Corporation I210 Gigabit Network Connection (rev 03)
    Subsystem: Intel Corporation Device 0000
    Flags: bus master, fast devsel, latency 0, IRQ 19
    Memory at f7b00000 (32-bit, non-prefetchable) [size=128K]
    I/O ports at e000 [size=32]
    Memory at f7b20000 (32-bit, non-prefetchable) [size=16K]
    Capabilities: [40] Power Management version 3
    Capabilities: [50] MSI: Enable- Count=1/1 Maskable+ 64bit+
    Capabilities: [70] MSI-X: Enable+ Count=5 Masked-
    Capabilities: [a0] Express Endpoint, MSI 00
    Capabilities: [100] Advanced Error Reporting
    Capabilities: [140] Device Serial Number 00-01-05-ff-ff-19-7d-59
    Capabilities: [1a0] Transaction Processing Hints
    Kernel driver in use: igb

~$ ifconfig | awk '/eth/' RS=
eth0      Link encap:Ethernet  HWaddr 00:01:05:19:7d:59
          inet addr:192.168.11.219  Bcast:192.168.11.255  Mask:255.255.255.0
          inet6 addr: fe80::201:5ff:fe19:7d59/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:73 errors:0 dropped:0 overruns:0 frame:0
          TX packets:57 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:15740 (15.7 KB)  TX bytes:7496 (7.4 KB)
          Memory:f7b00000-f7b20000
eth1      Link encap:Ethernet  HWaddr 00:01:05:19:7d:58
          inet addr:169.254.19.211  Bcast:169.254.255.255  Mask:255.255.0.0
          inet6 addr: fe80::201:5ff:fe19:7d58/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:37 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:6505 (6.5 KB)
          Interrupt:20 Memory:f7c00000-f7c20000

A: To long for comment, wall of text, sorry =)
Had another look at your ifconfig, and see eth1 or your nic with mac ending on 58 is not receiving any packages. I read that ifconfig will be interface level statistics, before the firewall.  Any particular reason for using the option, pointtopoint in interfaces config? Try remove it and use netmask 255.255.255.0 or 255.255.0.0 instead. If that also fail. I would guess with the rc kernel that it isn't a driver issue. And i would fall back to suspect faulty hardware, cable. For the cable are you using an "Ethernet crossover cable" for the direct connection? it might be that only one of your nics is able to detect and switch rx\tx automatically. Shouldn't have anything to say, but you could also try to flush your firewall; sudo iptables -F
Old, Try the following;
Download and install:
Kernel headers part1
Kernel headers part2
Kernel-image
Use sudo dpkg -i filename.deb to install.


text:
Q: UNION or JOIN 4 tables that have inner join each one I need to know if can I JOIN (FULL or LEFT) or UNION (ALL) these tables I have. The think is I need to show all user with membership in a list, but I have 5 tables of different users in total and each one have INNER JOIN with another tables to show instead of ID the name of that ID.
HERE I show you two tables I need to JOIN or UNION.
$query = "SELECT M.id_med, M.nombres, M.apellidos, M.especialidad, M.subespecialidad, M.foto, M.visto,
                    CM.nombre_categoria, EM.nombre_especialidad
                    FROM MEDICOS M
                    INNER JOIN PAISES P ON M.pais = P.id
                    INNER JOIN DEPARTAMENTOS D ON M.departamento = D.id
                    INNER JOIN MUNICIPIOS N ON M.municipio = N.id
                    INNER JOIN CATEGORIAS_MEDICAS CM ON M.especialidad = CM.id_categoria
                    INNER JOIN ESPECIALIDAD_MED EM ON M.subespecialidad = EM.id_especialidad
                    WHERE CONCAT(',', (pertenece), ',') LIKE CONCAT('%,', 5, ',%') AND foto != '/images/nopic.jpg' AND estado = 'activado'
                    AND status = 'vivo' AND hot != '0' AND imag != '0' ORDER BY RAND() LIMIT 20

                    FULL JOIN // I tried with UNION ALL, LEFT JOIN but without success

                    SELECT o.id_odont, o.nombres, o.apellidos, o.especialidad, o.subespecialidad, o.foto, o.visto,
                    CO.nombre_categoria, EO.nombre_especialidad
                    FROM ODONTOLOGOS O
                    INNER JOIN PAISES P ON O.pais = P.id
                    INNER JOIN DEPARTAMENTOS D ON O.departamento = D.id
                    INNER JOIN MUNICIPIOS N ON O.municipio = N.id
                    INNER JOIN CATEGORIAS_ODONTO CO ON O.especialidad = CO.id_categoria
                    INNER JOIN ESPECIALIDAD_ODONTO EO ON O.subespecialidad = EO.id_especialidad
                    WHERE CONCAT(',', (pertenece), ',') LIKE CONCAT('%,', 5, ',%') AND foto != '/images/nopic.jpg' AND estado = 'activado'
                    AND status = 'vivo' AND hot != '0' AND imag != '0' ORDER BY RAND() LIMIT 20
                    ";

Hope that you can help me with this.
I only show two of 4 tables (MEDICOS, ODONTOLOGOS, NEGOCIOS, PSICOLOGOS) that I need to join or union.


text:
Q: Is it a good practice to nest try-with-resources statement in order to wrap DataOutputStream Instance in it? Here is my question, should I be coding with out a nested try or should I be coding without try-with-resources statement to wrap DataOutputStream ? Or is there a better solution for this? I would really appreciate your help.
I am recently learning to write a java socket client on android with Android Studio.

Inspection told me to initialize a socket with try statement, which I did.

public static String sendSocket(String newText) {
    final int timeout = 5000;
    try (Socket soc = new Socket()){
        final InetSocketAddress address = new InetSocketAddress("10.0.0.3", 6101);
        soc.connect(address, timeout);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "socket done";
}

then I haven't atcually send my "newText", so I decided to add little more thing do it.Here is what I wrote after doing some research.
    public static String sendSocket(String newText) {
    final int timeout = 5000;
    try (Socket soc = new Socket()){
        final InetSocketAddress address = new InetSocketAddress("10.0.0.3", 6101);
        soc.connect(address, timeout);
        if (!newText.isEmpty()) {
            final byte[] buffer = newText.getBytes("UTF-8");
            DataOutputStream dos = new DataOutputStream(soc.getOutputStream());
            dos.write(buffer, 0, buffer.length);
            dos.writeBytes("\n");
            dos.flush();
            dos.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "socket done";
}

But then Inspection told that DataOutputStream should be use with a try-with-resources statement, I did what it asking again, code block end up like this

public static String sendSocket(String newText) {
    final int timeout = 5000;
    try (Socket soc = new Socket()){
        final InetSocketAddress address = new InetSocketAddress("10.0.0.3", 6101);
        soc.connect(address, timeout);
        if (!newText.isEmpty()) {
            final byte[] buffer = newText.getBytes("UTF-8");
            try (DataOutputStream dos = new DataOutputStream(soc.getOutputStream())) {
                dos.write(buffer, 0, buffer.length);
                dos.writeBytes("\n");
                dos.flush();
                dos.close();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "socket done";
}

But then inspection was still not satisfied, telling me that I shouldn't write nested try which may result to be unclear. Then, I am in a dilemma.


text:
Q: How do i detect a WPFDataGrid row Data changed? I have a DataGrid,and need to detect when a user has make changes to a row.I don't want to use CellEditEnding because whenever a row get focus and lost it without any inputs,this event get raised,in the other way i need to bind a bool property to each row that set to true when the row got chgangd.

A: Use following code as an example, so you know the basic idea of how to trace if an item in your ItemSource had been changed (here only compared to the initial value only).
List<myItem> Items=new List<myItem>(); //your ItemSource

    class myItem:ObservableObject //an class implement INotifyPropertyChanged interface
    {
        string _inititemName;
        string _itemName;
        bool itemChanged; //here is your indicator

        myItem(string name)
        {
            _inititemName=itemName=name;
        }

        public string itemName
        {
            get{return _itemName;}
            set
            {
                _itemName=vlaue;
                if (_itemName!=_inititemName)
                   itemChanged=true;
                else
                   itemChanged=false;
                RaisePropertyChanged("itemName"); //or whatever the name of the method is that invoke OnPropertyChanged
            }
        }
    }

A: Make the properties of your item class set a boolean update flag when they are modified
e.g.
public class MyGridItem
{
    public MyGridItem(string Name)
    {
        this.Name = Name;
        Updated = false;
    }

    public bool Updated {get; private set;}

    private string _Name = null;
    public string Name
    {
        get { return _Name; }
        set {
                if (!_Name.Equals( value ))
                {
                    _Name = value;
                    Updated = true
                 }
            }
    }
}


text:
Q: Do two engines with the same specific impulse always perform the same amount of work? As the title say, do engines with different thrusts with the same $I_{sp}$ and the same amount of fuel perform the same amount of work?

A: The answer is no.
A silly counterexample: Consider two rocket engines, one of which delivers 760,000 pounds of thrust at launch, the other, 100,000 pounds. Both have the same specific impulse. The rocket, engine structure, upper stages, and payload have a mass of 100,000 pounds, and the fuel tanks are filled with 500,000 pounds of fuel. (Sorry for the English units. This one of the areas where English units are much easier than metric, unless you use the forbidden kilopond. A lot of European rocket scientists still use the forbidden kilopond.)
The first rocket takes off. The engine does a lot of work, raising the rocket's altitude and increasing it's velocity. The second rocket just sits on the launch pad and never takes off. It does no work. This is a silly example because no one would ever attempt to use that second engine. That math is easy. Thrust needs to exceed total weight or the vehicle won't take off.
Here's a more realistic counterexample: Consider two rockets in a circular orbit. Both rockets have the same mass, the same amount of fuel, and have engines with the same specific impulse but different thrust levels. Both rockets use all the fuel in the most optimal fashion possible to reach the highest possible circular orbit. The rocket that reaches the higher orbit is the winner, and once again it's the rocket with the higher thrust engine that wins.
Low thrust comes at a cost. This is one of the factors that motivated the development of the Variable Specific Impulse Magnetoplasma Rocket (VASIMR) engine. That engine has the ability to vary between low thrust with a high specific impulse and not so low thrust with a not so high specific impulse.


text:
Q: How does calling a method in Objective-C differ from C++?
Possible Duplicate:
Objective C message dispatch mechanism

My question IS NOT about the syntax. I'd like to learn how is calling a method in C++ different from sending a message to an object in Objective-C and how they are performed?

A: This is quite a complicated question, as there is no fix C++ calling convetion unlike C.
Objective-C is just a thin wrapper around C, so it uses the same convention.
Just one additional thing to now, when you send a message like:
[target selector];

It is the same as:
objc_msgSend(target, @selector(selector));

Then it's just the traditional C calling convention, with a first table lookup for the function matching your message. The objc_msgSend is a bit more complicated as it keeps the arguments stack in place and pass it directly to the underlying function.
The C++ calling convention differs from one name-mangling to another, and even from one compiler to another.
From a performance point of view, C++ method call is faster as the link is resolved at compile-time (more exactly at link-time). The method either exists or not, which cause a linker error.
Objective-C method call include a method table lookup at runtime, thus your method may be added later in your code, which gives more flexibility but less performance.

A: Entirely the same and entirely different.  In C++ you'd say
result = myObjectPtr ->myMethod(myParm1, myParm2);

In Objective-C you'd say
result = [myObjectPtr myMethodWithParm1:myParm1 andParm2:myParm2];

In the simple case they'd function the same, from an external appearances standpoint, but lots of differences at the implementation level, since Objective-C calls are dynamic.
It would take several pages to enumerate all the differences in any detail (though for the simplest cases the differences aren't significant).


text:
Q: how to pass dynamic data to custom info window adapter in android? I am trying pass dynamic data(text and images drawables)in custom window adapter,but i am getting same data for all markers,i need different text and diffrent images to my respective markers??how to get??
I tried below code.
CustomInfoWindowAdapter.class

public class CustomInfoWindowAdapter implements InfoWindowAdapter {

    private View v;
    String selectedPath;
    LatLng latLng;
    String addtext;
    Context context;

    CustomInfoWindowAdapter(Context context, String addtext, String selectedPath, LatLng latLng) {
        // TODO Auto-generated constructor stub
        this.selectedPath = selectedPath;
        this.latLng = latLng;
        this.addtext = addtext;
        this.context=context;

    }

    @Override
    public View getInfoContents(Marker marker) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        v = inflater.inflate(R.layout.infowindow,
                null);
        ImageView icon = (ImageView) v.findViewById(R.id.icon);
        // set some bitmap to the imageview
        if (selectedPath != "") {
            Log.d("Selectedpath", "sekectedpath" + selectedPath);
            icon.setImageURI(Uri.parse(selectedPath));
        }
        TextView txt = (TextView) v.findViewById(R.id.textView1);
        txt.setText(addtext);

        return v;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        // TODO Auto-generated method stub
        return null;
    }

}

and i called CustomInfoWindowAdapter to my activity like below
        googleMap.setInfoWindowAdapter(new MyInfoWindowAdapter(addtext, selectedPath, latLng));

A:
Add the markers with the information specific to it. and when you click on particular InfoWindow you will get the particular marker data in   getInfoContents(Marker marker) method.

 public class MainActivity extends AbstractMapActivity implements
 OnMapReadyCallback, OnInfoWindowClickListener {
 private boolean needsInit=false;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 if (readyToGo()) {
  setContentView(R.layout.activity_main);

  MapFragment mapFrag=
      (MapFragment)getFragmentManager().findFragmentById(R.id.map);

  if (savedInstanceState == null) {
    needsInit=true;
  }

  mapFrag.getMapAsync(this);
 }
 }

 @Override
 public void onMapReady(final GoogleMap map) {
 if (needsInit) {
  CameraUpdate center=
      CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
                                               -73.98180484771729));
  CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

  map.moveCamera(center);
  map.animateCamera(zoom);
  }
  map.addMarker(new MarkerOptions()
 .position(new LatLng(37.7750, 122.4183))
 .title("San Francisco")
 .snippet("Population: 776733"));

   map.addMarker(new MarkerOptions()
 .position(new LatLng(37.7750, 122.4183))
 .title("San Francisco")
 .snippet("Population: 776733"));

   map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
   map.setOnInfoWindowClickListener(this);
  }

 @Override
 public void onInfoWindowClick(Marker marker) {
 Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
 }

 private void addMarker(GoogleMap map, double lat, double lon,
                     int title, int snippet) {
 map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
                                 .title(getString(title))
                                 .snippet(getString(snippet)));
 }
 }

Refer this https://github.com/commonsguy/cw-omnibus/tree/master/MapsV2/Popups


text:
Q: What is fileAPI ? How do I use it with angular? I'm creating a function so that I can upload files to my server through the use of AngularJS. While browsing I saw this amazing piece of work on github by daniel farid ( link - https://github.com/danialfarid/ng-file-upload )
But the problem is its too much for me to understand. I'm starting out with more of basic stuff.
I'd be delighted to hear back from you. Thanks

A: Try using this directive in the controller.
app.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function () {
                scope.$apply(function () {
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

Html
 <input type="file" name="file" class="file-input-wrapper btn btn-default btn-primary" file-model="uploadFile" id="control" />

while going back to your controller:
the uploaded file will be available within the $scope.uploadFile


text:
Q: JSON unmarshal array is not working, but the same data works on javascript I try to have some array values into JSON string where I send to the browser and in the browser is working fine to add some input fields dynamically, but when I try to check the data from that new fields on Go I try to unmarshal the same data but is not working because the values are empty.
This is the code:
package main

import "fmt"
import "encoding/json"

type PublicKey struct {
        Name        string   `json:"name"`
        Type        string   `json:"type"`
    Description string   `json:"description"`
    Values      []string `json:"values"`
}

func main() {

keysBody := []byte(`
[
   [
      {
         "name":"fecha_inicio",
         "type":"date",
         "description":"Fecha de Inicio",
         "values":[
            ""
         ]
      }
   ],
   [
      {
         "name":"fecha_final",
         "type":"date",
         "description":"Fecha Final",
         "values":[
            ""
         ]
      }
   ],
   [
      {
         "name":"username",
         "type":"select",
         "description":"Usuario",
         "values":[
            "admin",
            "gus"
         ]
      }
   ]
]
`)

    keys := make([]PublicKey,0)
    json.Unmarshal(keysBody, &keys)
    fmt.Printf("%#v", keys)

}

https://play.golang.org/p/kKT3IN4_8vb
This is the result:
[]main.PublicKey{main.PublicKey{Name:"", Type:"", Description:"", Values:[]string(nil)}, main.PublicKey{Name:"", Type:"", Description:"", Values:[]string(nil)}, main.PublicKey{Name:"", Type:"", Description:"", Values:[]string(nil)}}
This is the same code in javascript working fine:
parameterData contains the same JSON string
        var jsonMenus = JSON.parse(parameterData);
        for (let i = 0; i < jsonMenus.length; i++) {
            let arr = jsonMenus[i];
            for (let j = 0; j < arr.length; j++) {
                //New DIV
                var newDiv = document.createElement("div");
                newDiv.setAttribute("class","w3-quarter");
                //console.log(arr[j].name + ' ' + arr[j].type + ' ' + arr[j].description);
                var label = document.createElement("Label");
                label.innerHTML = arr[j].description;
                label.setAttribute("class","w3-label");
                newDiv.appendChild(label);
                if (arr[j].type != 'select') {
                    var input = document.createElement("input");
                    input.type = arr[j].type;
                    input.name = arr[j].name;
                    input.setAttribute("class","w3-input w3-border w3-round");
                    newDiv.appendChild(input);
                } else {
                    var select = document.createElement("select");
                    select.name = arr[j].name;
                    var values = arr[j].values
                    for (let k = 0; k < values.length; k++) {
                        opt = document.createElement('option');
                        opt.value = values[k];
                        opt.innerHTML = values[k];
                        select.appendChild(opt);
                    }
                    select.setAttribute("class","w3-input w3-border w3-round");
                    newDiv.appendChild(select);
                }
                container.appendChild(newDiv);

Can anyone can help to have the JSON string working in both places?

A: Your json is a 2 dimensional array but you are trying to unmarshal to a single dimension array.
You need to unmarshal to an [][]PublicKey, here is the adjusted playground: https://play.golang.org/p/ykzzqtSPJCU.