Q:

Initializing a class not connected to other classes -- Ruby on Rails

I'm trying to initialize a singular class in my RoR application. This Batch class is not connected to any other class, it is used solely for the Rails API I have set up.
This is the Batch class:
class Batch < ActiveRecord::Base
  before_create :access_bucket

  def access_bucket
    s3 = AWS::S3.new
    bucket = s3.buckets['curateanalytics']
    bucket.objects.each do |obj|
      if obj =~ /swipe batches/i && obj =~ /jpg/i
        self.sort_objs(obj.key)
      end
    end
  end

  def sort_objs(url)
    swipe = url.split("swipe batches/").last
    batch_id = url.split("swipe batches/")[1]
    folder = swipe.split("/")[0]
    self.initialize(batch_id, folder, url)
  end

  def initialize()
    batch = Batch.new
    batch.batch_id = batch_id
    batch.folder = folder
    batch.url = url
    batch.save!
  end
end

I honestly had no idea where to go so I created a before_create :create_batch method in my User class:
class User < ActiveRecord::Base
  has_one :like
  has_one :outfit
  has_one :wardrobe
  before_create :create_batch
  after_create :create_wardrobe, :create_outfit, :create_like
  serialize :preferences

  def self.from_omniauth(auth_hash)
    where(auth_hash.slice(:provider, :uid)).first_or_initialize.tap do |user|
      user.curate_user_id = "curate"+rand(9).to_s+rand(9).to_s+rand(9).to_s+
        rand(9).to_s+rand(9).to_s
      user.provider = auth_hash.provider
      user.uid = auth_hash.uid
      user.name = auth_hash.info.name
      user.email = auth_hash.info.email
      user.image = auth_hash.info.image
      user.oauth_token = auth_hash.credentials.token
      user.oauth_expires_at = Time.at(auth_hash.credentials.expires_at)
      user.preferences = { height: nil, weight: nil, age: nil, waist_size: nil, inseam: nil, preferred_pants_fit: nil, shirt_size: nil, preferred_shirt_fit: nil, shoe_size: nil}
      user.save!
    end
  end

  private
  def create_batch
   @batch = Batch.new
   @batch.save!
  end
end

When I ran the server I received the message that the stack was too deep. Am I wrong in thinking that this path should access the Batch class and the Batch.access_bucket method which would then lead to the initialize method?

A:

Delete initialize method in the Batch class.
When you call new on a Class, it instantiates an object and call initialize on it. So when you call Batch.new in create_batch method of your User class, the initialize method of you Batch class is called. The problem is that Batch#initialize method calls Batch.new inside it, so another Batch#initialize is invoked, which calls Batch.new inside it, which again calls another Batch#initialize, and infinite cycle of Bathc.new and Batch#initialize follows.


Q:

Spring does not use autowired constructor for loading the bean

I have autowired Address bean into the constructor of Employee bean. And expect when getting instance of Employee bean I should get an instance of Address inside it. But Spring container is using no-args constructor of Employee to return the instance. Below is my code
public class Address {
    public void print(){
        System.out.println("inside address");
    }
}

public class Employee {

    private Address address;

    @Autowired
    public Employee(Address address){
        this.address = address;
    }

    public Employee(){}

    public Address getAddress(){
        return address;
    }
}

@Configuration
@ComponentScan(basePackages={"com.spring"})
public class ApplicationConfig {

    @Bean
    public Employee employee(){
        return new Employee();
    }

    @Bean
    public Address address(){
        return new Address();
    }
}

public class Main {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        Employee employee = (Employee)context.getBean("employee");
        // Here add is null !!
        Address add = employee.getAddress();
    }
}

A:

The no-arg constructor is being used because that's the one that you're calling (new Employee()):
@Bean
public Employee employee() {
    return new Employee();
}

Since you're manually creating the Employee instance, rather than having Spring create it for you, you'll also have to pass in the Address yourself:
@Bean
public Employee employee() {
    return new Employee(address());
}

Note that multiple calls to address() will in fact return the same bean, rather than multiple new instances, if that was your concern.
Otherwise, the alternative is to have Employee annotated with @Component, after which Spring will automatically create the bean for you and wire in the Address dependency. You get that for free since you have component scanning turned on (assuming that Employee is in the package that you're scanning). If you go this route, you can remove the employee() bean definition from your config class, otherwise one may end up overriding the other.


Q:

Why the "wc" command called in the following program doesn't output any message in terminal?

I'm trying to get a feeling about how pipe works in Linux. I wrote the following program, compiled it and then run it in terminal. The program exits normally without errors, but it didn't print out any message. Is there anything wrong?
PS: this code snippet is  from MIT's xv6 operating system course.
#include <stdio.h>
#include <unistd.h>

int main() {
    int p[2];
    char *argv[2];
    argv[0] = "wc";
    argv[1] = 0;
    pipe(p);
    if (fork() == 0) {
        close(0);
        dup(p[0]);
        close(p[0]);
        close(p[1]);
        execvp("/bin/wc", argv);
    } else {
        write(p[1], "hello world\n", 12);
        close(p[0]);
        close(p[1]);
    }
}

A:

the following proposed code:

cleanly compiles
performs the desired functionality
passes the name of a local file, rather than some random string AND the file name is terminated with a NUL byte
you will need to modify the passed file name to a file that is in your current directory
notice the length passed to write() includes the trailing NUl byte

and now the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/wait.h>

int main() {
    int p[2];
    char *argv[3];
    argv[0] = "wc";
    argv[1] = "--files0-from=-";
    argv[2] = (char *) NULL;
    if( pipe(p) != 0 )
    {
        perror( "pipe failed" );
        exit( EXIT_FAILURE );
    }
    pid_t pid = fork();
    switch( pid )
    {
        case -1:
        perror( "fork failed" );
        exit( EXIT_FAILURE );
        break;

        case 0:
        close(0);
        if( dup2(p[0], 0) != 0 )
        {
            perror( "dup2 failed" );
            exit( EXIT_FAILURE );
        }
        close(p[0]);
        close(p[1]);
        execvp("/usr/bin/wc", argv);
        perror( "execvp failed" );
        exit( EXIT_FAILURE );
        break;

        default:
        write(p[1], "untitled2.c", 12);
        close(p[0]);
        wait( NULL );
        close(p[1]);
    }
}

Note: the untitled2.c is this source file.
a run of the program results in:
47 101 818 untitled2.c


Q:

Run erlang code from browser and get response?

Hello awesome community!
I've started learning erlang recently. (It's quite mind bending) :)
I can't seem to find an answer anywhere.... but as a way to learn, I'm trying to create a mini shell in my web browser.
For example, I want to enter some actual erlang code into a text box, press enter and return what ever the result is and display it on the web page.
> Awesome = 41 + 41.
> io:format("Awesome = ~p", Awesome).
> 82

I've set up a simple erlang server on my localhost on port 8891 and can easily connect to it.
Is it possible to send it erlang code to run and output the response?
Any help would be appreciated! :)

A:

This can be achieved using erl_scan, erl_parse, erl_eval as mentioned in this link.
The problem is for Variable bindings. Need to know the variable bindings when it is used in an expression (more difficult when it is inside a fun)
1> Expr="Awesome = 41 + 41.".
"Awesome = 41 + 41."
2> {ok, Tokens, _} = erl_scan:string(Expr).
{ok,[{var,1,'Awesome'},
     {'=',1},
     {integer,1,41},
     {'+',1},
     {integer,1,41},
     {dot,1}],
    1}
3> {ok, [Form]} = erl_parse:parse_exprs(Tokens).
{ok,[{match,1,
            {var,1,'Awesome'},
            {op,1,'+',{integer,1,41},{integer,1,41}}}]}
4> {value, Value, Binding} = erl_eval:expr(Form, []).
{value,82,[{'Awesome',82}]}

When the user enters Awesome = 41 + 41. in the browser you can send back the response as 82.
You also need to maintain the state of the Expression. That is the Binding should be maintained can be used as follows
5> FunStr ="io:format(\"Awesome = ~p\", [Awesome]).".
"io:format(\"Awesome = ~p\", [Awesome])."
6> {ok, Tokens1, _} = erl_scan:string(FunStr).
{ok,[{atom,1,io},
     {':',1},
     {atom,1,format},
     {'(',1},
     {string,1,"Awesome = ~p"},
     {',',1},
     {'[',1},
     {var,1,'Awesome'},
     {']',1},
     {')',1},
     {dot,1}],
    1}
7> {ok, [Form1]} = erl_parse:parse_exprs(Tokens1).
{ok,[{call,1,
           {remote,1,{atom,1,io},{atom,1,format}},
           [{string,1,"Awesome = ~p"},
            {cons,1,{var,1,'Awesome'},{nil,1}}]}]}
8> {value, Fun1, _} = erl_eval:expr(Form, Binding).
{value,82,[{'Awesome',82}]}

9> {value, V, _} = erl_eval:expr(Form1, Binding).
Awesome = 82{value,ok,[{'Awesome',82}]}

The Binding list should grow till the end of the session.


Q:

Does Peter Parker have a Chemical Engineering degree?

In Spiderman: Into the Spiderverse during

 the end credits, when we hear Peter Parker singing the song “Spidey Bells”

Peter reveals that he has a degree in Chemical Engineering.
In the Marvel comics, does Peter Parker indeed have a degree in Chemical Engineering?

A:

As indicated in Drifter196's answer, and in the comments above, the 616 version of Spider-Man does not have a degree in Chemical Engineering. As per What was Peter Parker’s college major?:

According to the Official Handbook of the Marvel Universe (Vol. 1 #10) Peter's major in college was Biophysics.

Currently, Parker has taken an indefinite leave of absence from the graduate program in biophysics at Empire State University, and has taken up full-time freelance photograph, primarily for The Daily Bugle,
... the Official Handbook of the Marvel Universe (Vol. 4 #2) indicates that his Doctoral studies are in Biochemistry

EDUCATION: College educated (science major), doctorate studies in biochemistry (incomplete)

In the Marvel-1610 continuity of the Ultimates universe, where Miles comes from, Peter was still a high-school student.
However, there are definite deviations in the Spider-verse film From Marvel-1610, including a blonde Peter Parker who's married Mary Jane, so we cannot really draw any conclusions from either Marvel-1610 or Marvel-616 comic book history. Given that the film's 1610 universe is so different, I think we have to take its statements at face value.
So, long story short, in all likelihood, in the Spider-verse 1610 universe, Peter Parker does have a chemical engineering degree.


Q:

delphi: how to to store TCustomFrames and records in one list

I am using a TObjectList<TCustomFrame> to store TCustomFrames. Now i want to store some more information regarding to the TCustomFrame in the same list. A record would be nice.
Which delphi class would you prefer to store TCustomFrames and records in the same list?
The TCustomFrames and records will be added at runtime.

A:

Create a single record to hold all the information:
type
  TFrameInfo = record
    Frame: TCustomFrame;
    Foo: string;
    Bar: Integer;
  end;

Hold that in a TList<TFrameInfo>.
I note that you were using TObjectList<T> rather than TList<T>. The only good reason for doing that would be if you were setting OwnsObjects to True. But that seems unlikely since I doubt that the list is really in charge of the lifetime of your GUI objects. As a note for the future, if you find yourself  using TObjectList<T> with OwnsObjects set to False then you may as well switch to TList<T>.
Now, in case you do need the list to control the lifetime then you'd be best using a class rather than a record for TFrameInfo.
type
  TFrameInfo = class
  private
    FFrame: TCustomFrame;
    FFoo: string;
    FBar: Integer;
  public
    constructor Create(AFrame: TCustomFrame; AFoo: string; ABar: Integer);
    destructor Destroy; override;
    property Frame: TCustomFrame read FFrame;
    // etc.
  end;

  constructor TFrameInfo.Create(AFrame: TCustomFrame; AFoo: string; ABar: Integer);
  begin
    inherited Create;
    FFrame := AFrame;
    // etc.
  end;

  destructor TFrameInfo.Destroy;
  begin
    FFrame.Free;
    inherited;
  end;

And then hold this in a TObjectList<TFrameInfo> with OwnsObjects set to True.


Q:

Keeping same DateTime format for different locales

Recently I launched support for internalization for my JSF application. Once language is switched from en-US to de-AT, DateTime format is changed as accordingly (default behaviour). Is it any quick solution to keep the same DateTime format for every supported locale?
Should it be DateTimeConverter, or is it a part of the settings (faces-config.xml)?

A:

There are multiple options.
Use f:convertDateTime with a fixed locale attribute
Format your dates using f:convertDateTime with a fixed locale attribute.
<h:outputText value="#{someBean.dateField}" >
    <f:convertDateTime pattern="..."
                       locale="#{applicationScopedBean.fixedLocale}" />
</h:outputText>

From the attribute documentation:

Locale whose predefined styles for dates and times are used during formatting or parsing. If not specified, the Locale returned by FacesContext.getViewRoot().getLocale() will be used. Value must be either a VB expression that evaluates to a java.util.Locale instance, or a String that is valid to pass as the first argument to the constructor java.util.Locale(String language, String country). The empty string is passed as the second argument.

Override the f:convertDateTime converter in the faces-config.xml
You can override converters in the faces-config.xml using <converter>. You can override by ID or class. In this case ID is the way to go. The ID for f:convertDateTime is javax.faces.DateTime, so you could do something like:
<converter>
  <converter-id>javax.faces.DateTime</converter-id>
  <converter-class>org.example.MyDateTimeConverter</converter-class>
</converter>

When you implement your custom converter you should extend javax.faces.convert.DateTimeConverter. If you happen to be using PrimeFaces, extend org.primefaces.convert.DateTimeConverter.
Now simply hardcode the locale (to for example German):
public class MyDateTimeConverter extends DateTimeConverter
{

  public MyDateTimeConverter()
  {
    setLocale(Locale.GERMAN);
  }

}

Now you can use it like (note that the view locale is set to Dutch):
<f:view locale="nl">
  <h:outputText value="#{now}">
    <f:convertDateTime pattern="EEEEE dd MMMMM yyyy"/>
  </h:outputText>
</f:view>

Which will output:

Mittwoch 10 Mai 2017


Q:

How do I stop and start a loop in QT?

I've been trying to figure out how to make the program stop in a for-loop and wait for a button to be clicked and the for-loop continues.
Isn't there any easy way to stop the loop like QSystem.stop() and in the button clicked function QSystem.star() and the loop continues.
In C++ you could use system("pause") or the program stopped when you used a cin<<. But how do i do this in QT?

A:

Since the userinterface needs its code to run, if you halt event loop (which also means that any function that gets called from within the event loop is blocking, waiting for some event), you also halt the user interface, which means clicks into the window won't be processed. That's why in event based programming, which is what all UI kits do, it is essential to return to the main event handler loop as quickly as possible.
What you can do is create a second thread and wait on a condition variable. The GUI thread can signal that condition variable in the button click event slot.

In C++ you could use system("pause") or the program stopped

Exactly: The program is stopped. Which means it won't fetch events from the operating system. However receiving data from stdin is not an event. It's blocking on streamed I/O. Graphical user interfaces are event based though.
Note that conceptually it's not really impossible to think of a user interface to provide streaming I/O channels. However that doesn't work in single threaded programs. You need parallel execution (coroutines, threads, or such) for a concept like this to work.


Q:

How do I properly register a protocol handler on Windows 8?

I have a small project to handle tel: protocol links. It's a desktop application, which I'm developing using Visual Studio 2013 Community Edition.
Previously, I used to register the handler with a simple registry modification:
Microsoft.Win32.Registry.SetValue(registryKey, string.Empty, registryValue, Microsoft.Win32.RegistryValueKind.String);
Microsoft.Win32.Registry.SetValue(registryKey, "URL Protocol", String.Empty, Microsoft.Win32.RegistryValueKind.String);

registryKey = @"HKEY_CLASSES_ROOT\tel\shell\open\command";
registryValue = "\"" + AppDomain.CurrentDomain.BaseDirectory + "TelProtocolHandler.exe\" \"%1\"";
Microsoft.Win32.Registry.SetValue(registryKey, string.Empty, registryValue, Microsoft.Win32.RegistryValueKind.String);

However, this no longer seems to work on Windows 8. While the registry key has the desired value, the links are still handled by a different application. My tool doesn't even appear in the protocol handler selection:

I've looked at Walkthrough: Using Windows 8 Custom Protocol Activation, but I can't relate the mentioned information to my application. The article mentions a .appxmanifest file, which I don't have in my project and am unable to add as a new item.

A:

After asking the question, I stumbled upon Registering a protocol handler in Windows 8
The top voted answer there got me on the right track, although there were other issues. In the end, this is what I ended up with:
// Register as the default handler for the tel: protocol.
const string protocolValue = "TEL:Telephone Invocation";
Registry.SetValue(
    @"HKEY_CLASSES_ROOT\tel",
    string.Empty,
    protocolValue,
    RegistryValueKind.String );
Registry.SetValue(
    @"HKEY_CLASSES_ROOT\tel",
    "URL Protocol",
    String.Empty,
    RegistryValueKind.String );

const string binaryName = "tel.exe";
string command = string.Format( "\"{0}{1}\" \"%1\"", AppDomain.CurrentDomain.BaseDirectory, binaryName );
Registry.SetValue( @"HKEY_CLASSES_ROOT\tel\shell\open\command", string.Empty, command, RegistryValueKind.String );

// For Windows 8+, register as a choosable protocol handler.

// Version detection from https://stackoverflow.com/a/17796139/259953
Version win8Version = new Version( 6, 2, 9200, 0 );
if( Environment.OSVersion.Platform == PlatformID.Win32NT &&
    Environment.OSVersion.Version >= win8Version ) {
    Registry.SetValue(
        @"HKEY_LOCAL_MACHINE\SOFTWARE\Classes\TelProtocolHandler",
        string.Empty,
        protocolValue,
        RegistryValueKind.String );
    Registry.SetValue(
        @"HKEY_LOCAL_MACHINE\SOFTWARE\Classes\TelProtocolHandler\shell\open\command",
        string.Empty,
        command,
        RegistryValueKind.String );

    Registry.SetValue(
        @"HKEY_LOCAL_MACHINE\SOFTWARE\TelProtocolHandler\Capabilities\URLAssociations",
        "tel",
        "TelProtocolHandler",
        RegistryValueKind.String );
    Registry.SetValue(
        @"HKEY_LOCAL_MACHINE\SOFTWARE\RegisteredApplications",
        "TelProtocolHandler",
        @"SOFTWARE\TelProtocolHandler\Capabilities",
        RegistryValueKind.String );
}

TelProtocolHandler is the name of my application and should be replaced by whatever the name of your handler is.
The accepted answer in the other question also has ApplicationDescription in the registry. I didn't see the same key for any of the other registered handlers that I've checked, so I left it out and couldn't detect any problems.
Another key issue was that all of this wouldn't work if my application that sets up the handler was 32bit. When the entries are made in the Wow6432Node, I wasn't able to select the handler as the default for the given protocol. It took me a while to figure this out, because my application was compiled as AnyCPU. What I first missed was this little flag in the project properties:


Q:

Rendering a specific stylesheet for a view or set of views

Inside of my views directory I have two folders with files inside. Those folders are titled main and off-brand-main. I have similar but differing CSS files that need to be used with each, respectively. Those CSS are titled main.css and off-brand-main.css.
I'm stumped as to how to call the respective stylesheets, and where to make the calls. Should I do it in the controller in def new?
Any help would be very appreciated. Thanks!

A:

In the  section of your template file (often 'application.html.erb'), you can use a conditional to set the stylesheets to use based on something...
<Head>
  <% if ... %>
    <%= stylesheet_link_tag "main" %>
  <% else %>
    <%= stylesheet_link_tag "off-brand-main" %>

The conditional could be a controller (controller_name == 'something') and/or action (action_name == 'something').


Q:

Map in Hibernate a table to MEMORY (HEAP) in XML

This question is not about caching.
I need this in-memory table for many small updates and complicated queries.
I must have it on a server shared between several nodes.
MySQL have MEMORY (HEAP) Storage Engine which is exactly what I need.
Can I tell Hibernate to create such a table, when defining a <class> or a '` in the XML?
Is there another solution?
Thanks!

A:

No, you cannot generate those tables via Hibernate. Hibernate chooses storage engine based to dialect, and for MySQL 5 available dialects are MySQL5InnoDBDialect and MySQL5Dialect.
If it is really important to generate database structure via Hibernate, then you can of course go and create dialect yourself. As you see from the source of MySQL5InnoDBDialect, it boils down to "ENGINE = MEMORY".


Q:

Entity Framework Code First : Setting up One-To-One foreign key association using Annotations

I have following two Entities that I am trying to relate (one to one) using foreign key associations.
public class StandardRack {
    public int Id {get;set}
    public StandardRelay StandardRelay {get;set}
}

public class StandardRelay {
    public int Id {get;set}

    public int StandardRack_Id {get;set;}
    [Required][ForeignKey("StandardRack_Id")]
    public StandardRack StandardRack { get; set; }
}

This throws ModelValidationException. Any ideas why such a seemingly simple one-to-one bidirectional relationship cannot be configured.
Edit:
Here is the Exception:

System.Data.Entity.ModelConfiguration.ModelValidationException was caught
        Message=One or more validation errors were detected during model generation:
System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'StandardRelay_StandardRack_Source' in relationship 'StandardRelay_StandardRack'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be �*�.
Source=EntityFramework
        StackTrace:
             at System.Data.Entity.ModelConfiguration.Edm.EdmModelExtensions.ValidateAndSerializeCsdl(EdmModel model, XmlWriter writer)
             at System.Data.Entity.ModelConfiguration.Edm.EdmModelExtensions.ValidateCsdl(EdmModel model)
             at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
             at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
             at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
             at System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input)
             at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
             at System.Data.Entity.Internal.InternalContext.Initialize()
             at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
             at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()
             at System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator()
             at System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable.GetEnumerator()
             at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
             at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
             at TestApplication.MainWindow.Window_Loaded(Object sender, RoutedEventArgs e) in D:\RailwayProjects\RelayAnalysis\TestApplication\MainWindow.xaml.cs:line 33
        InnerException:

A:

One-to-one foreign key associations are not supported by Entitiy Framework. You must remove the foreign key and use shared primary keys (primary key of the dependent is its foreign key to the principal at the same time):
public class StandardRack {
    public int Id {get;set}
    public StandardRelay StandardRelay {get;set}
}

public class StandardRelay {
    public int Id {get;set}
    public StandardRack StandardRack { get; set; }
}

Mapping in Fluent API:
modelBuilder.Entity<StandardRack>()
    .HasOptional(rack => rack.StandardRelay)
    .WithRequired(relay => relay.StandardRack);

(I'm assuing here that a StandardRack has an optional Relay.)

A:

I think the foreignKey should be Id, not StandardRack_id.
Also, you should use virtual, in order to be able to use lazy loading.
This works for me
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace Racks
{

    public class StandardRack
    {
        public int Id { get; set; }
        public virtual StandardRelay StandardRelay { get; set; }
    }

    public class StandardRelay
    {
        public int Id { get; set; }

        public int StandardRack_Id { get; set; }

        [ForeignKey("Id")]
        [Required]
        public virtual StandardRack StandardRack { get; set; }
    }

    public class Context : DbContext
    {
        static Context()
        {
            Database.SetInitializer<Context>(null);
        }

        public DbSet<StandardRack> StandardRacks { get; set; }
        public DbSet<StandardRelay> StandardRelays { get; set; }

    }

    class Program
    {
        static void Main(string[] args)
        {
            var context = new Context();
            context.Database.Delete();
            context.Database.Create();

            var standardRack = new StandardRack();
            standardRack.StandardRelay = new StandardRelay();

            context.StandardRacks.Add(standardRack);
            context.SaveChanges();
        }
    }
}

A:

Here is how you can specify one-to-one relationship with FK using fluent api.
Note that FK is not explicitly defined in Enitity, but it's defined using fluent api.
public class StandardRack {
    public int Id {get;set}
    public StandardRelay StandardRelay {get;set}
}

public class StandardRelay {
    public int Id {get;set}
    public StandardRack StandardRack { get; set; }
}

modelBuilder.Entity<StandardRack>()
            .HasOptional(x => x.StandardRelay)
            .WithOptionalPrincipal(y => y.StandardRack)
            .Map(configurationAction: new Action<ForeignKeyAssociationMappingConfiguration>(x => x.MapKey("StandardRack_Id")));

fluent api will add column StandardRack_Id in StandardRelay.
Note that method name WithOptionalPrincipal() is quite ironic. msdn documentation of WithOptionalDependent shall make it clear.


Q:

Set a camera to free fall like a Rigid Body?

I want to capture freely falling objects from their reference frame. i.e. to have the camera freely falling due to gravity in the exact same manner.  Is there a simple way to make a camera free fall just like a Rigid Body?

A:

No python needed.
Simply add a Copy Location constraint to the camera. Set the Target to an object with an active rigid body. (I simply duplicated one of my colorful cubes and moved it back from the rest of the bunch. Remember to turn the visibility off). That will get the camera to fall down with gravity.
To get the nice camera shake when it hits the ground we need two more constraints. A Copy Rotation constraint and a Track To constraint.
The Copy Rotation is copying the rotation of the same cube the camera is glued to, that gets the real shake from the impact with the ground. (I have the Influence of that set to 0.5 just to tone it down a bit.)
The Track To is to keep all my cube in frame. (you can see how much the cubes tumble, and without this constraint the camera would do that too.)
These are my constraints on the camera. Do note the object "Cube.001" is the cube I moved off screen for the camera, and the "Cube" is simply one in the middle of the pack.

A:

You can do this even easier. Just Parent Camera to one of the Cubes faces.

Select Cubes face.
Place Cursor on it - Shift+S > Cursor to Selected.
Select Camera and place it on Cursor position - Shift+S > Selection to Cursor.
Select Camera first then Cube with Shift and Ctrl+P > Object.
Done.

Note: Based on the initial Camera position/face selected you will need
  to set Camera rotation accordingly.


Q:

Client doesn't get new IP when switching between subnets/locations

So here is our setup.
We have 14 locations each with its own subnet and router. The routers at these locations have DHCP relay enabled that points back to our central server that is running DHCP.
This DHCP server (Windows 2008 R2) has a Superscope and then our 14 other scopes inside of it. So far everything has been working and all the locations have been getting the appropriate IP addresses.
However, when a user goes between locations they never receive a new IP address. Their machine holds on to the same IP from the previous subnet and the DHCP does not hand them a new one. It won't even work if we do a release/renew.
I have to go into the DHCP Server and physically delete their IP entry in order for them to get a new IP at the new location.
Any Ideas?

A:

You don't want a superscope for this set up. The goal of a superscope is multiple networks on a shared physical segment. The DHCP server thinks these IPs are valid for anywhere inside the superscope.


Q:

Conditional import to switch implementations

I have node.js application written in TypeScript and I need to switch between two interface implementations based on the config file. Currently I have this code which seems to be working.
"use strict";

import { config } from "../config";

let Something;
if (config.useFakeSomething) {
    Something = require("./FakeSomething").FakeSomething;
} else {
    Something = require("./RealSomething").RealSomething;
}
...
let s = new Something();
s.DoStuff();
...

But I have bad gut feeling about that (mainly because of the mixing require and import for loading modules). Is there some other way how to achieve implementation switching based on config file without importing both modules?

A:

I can see nothing wrong with your approach. In fact lines like
import { config } from "../config";

When targeting commonjs will be compiled to the following javascript (ES6):
const config = require('../config');

So they are effectively identical and you are not mixing different module loading techniques.

A:

If you want to keep the client-code for your Something class clean, you can move the conditional importing to a single file. You can have the following directory structure for your Something module:
/Something
    RealSomething.ts
    FakeSomething.ts
    index.ts

And in your index.ts, you can have the following:
import { config } from '../config';

const Something = config.useFakeSomething ?
    require('./FakeSomething').FakeSomething :
    require('./RealSomething').RealSomething;

export default Something;

And in your client code, you can just import Something:
import Something from './Something/index';


Q:

Why are my photos taken at f/11 less sharp than those taken at a wider aperture?

I am new to photography. I have Fujifilm FinePix HS10 camera. Lately I was trying my hands on landscape photography.
I learnt from different tutorials that setting high aperture value gets most of the scene in focus. Hence proceeding with this notion I set my aperture value to f-11 which is the highest on my camera.
But what I observed is that, f-11 images were very soft and I don't see that background elements well focused.
On the contrary, images taken in range f-4 to f-5.6 were better looking in terms of sharpness of background elements. I have attached sample images for your reference.
Can you please shed some light on this?
Image taken with f-4

Image taken with f-11

A:

Images with your camera will start showing signs of diffraction around f/4 to f/5.6 due to the size of the sensor.  Shooting at a significantly smaller aperture (like f/11) will only increase the diffraction problems.  You'll lose resolution.
Here's a good tutorial on diffraction:
http://www.cambridgeincolour.com/tutorials/diffraction-photography.htm

A:

It is correct that a smaller aperture (higher f number) results in greater front-to-back focus, whilst larger apertures (smaller f numbers) result in more selective focus.
There is, however, a tradeoff.  With the smaller apertures, less light is let into the camera body and in order to compensate for this, the camera must do one of two things.  a) slow the shutter speed, in order to collect more light, or b) increase the ISO to make the sensor more sensitive to the light it does receive.  Possibly, your camera will do both.
You do not say whether your sample images above were taken on a tripod, though since they are framed ever so slightly differently, I'm guessing not.  The lack of sharpness in the second photograph may be caused by camera shake, where the shutter was open longer than for the photo with the larger aperture.  The longer shutter time would also accentuate and capture movement in the water, as opposed to the first shot which, with a faster shutter speed, 'froze' the water.
With all things being equal however, the photos should result with the same 'brightness'.  Your second photo is clearly slightly overexposed, compared to the first.  So I am wondering if in the first photo, your camera metered off the water, and the second metered off the trees.
Unfortunately it's difficult to identify the exact issues based on the two photos provided.  Can you perhaps supply not only the f stop used, but also the shutter speed and ISO values? (This will be stored as metadata (called EXIF) in the photo file.  Windows or Mac should display this when the file is selected in Explorer/Finder).

A:

Camera shake and diffraction have already been mentioned.
Another factor that can be common (especially for quite a bit of the subject matter in the pictures you posted) is that even a fairly light breeze can move the subjects (especially leaves) around during the exposure. This can result in (at least parts of) a picture looking unsharp, even when/if you do everything else right (e.g., using a tripod to prevent camera shake).


Q:

How do I improve breaking substitution ciphers programmatically?

I have written (am writting) a program to analyze encrypted text and attempt to analyze and break it using frequency analysis.
The encrypted text takes the form of each letter being substituted for some other letter ie. a->m, b->z, c->t etc etc. all spaces and non alpha chars are removed and upper case letters made lowercase.
An example would be :

Orginal input - thisisasamplemessageitonlycontainslowercaseletters
  Encrypted output - ziololqlqdhstdtllqutozgfsnegfzqoflsgvtkeqltstzztkl
  Attempt at cracking - omieieaeanuhtnteeawtiorshylrsoaisehrctdlaethtootde

Here it has only got I, A and Y correctly.
Currently my program cracks it by analysing the frequency of each individual character, and mapping it to the character that appears in the same frequency rank in a non encrypted text.
I am looking for methods and ways to improve the accuracy of my program as at the moment I don't get too many characters right. For example when attempting to crack X amount of characters from Pride and Prejudice, I get:

1600 - 10 letters correct
  800 - 7 letters correct
  400 - 2 letters correct
  200 - 3 letters correct
  100 - 3 letters correct.

I am using Romeo and Juliet as a base to get the frequency data.
It has been suggested to me to look at and use the frequency of character pairs, but I am unsure how to use this because unless I am using very large encrypted texts I can imagine a similar approach to how I am doing single characters would be even more inaccurate and cause more errors than successes. I am hoping also to make my encryption cracker more accurate for shorter 'inputs'.

A:

I'm not sure how constrained this problem is, i.e. how many of the decisions you made are yours to change, but here are some comments:
1) Frequency mapping is not enough to solve a puzzle like this, many frequencies are very close to each other and if you aren't using the same text for frequency source and plaintext, you are almost guaranteed to have a few letters off no matter how long the text. Different materials will have different use patterns.
2) Don't strip the spaces if you can help it. This will allow you to validate your potential solution by checking that some percentage of the words exist in a dictionary you have access to.
3) Look into natural language processing if you really want to get into the language side of this. This book has all you could ever want to know about it.
Edit:
I would look into bigraphs and trigraphs first. If you're fairly confident of one or two letters, they can help predict likely candidates for the letters that follow. They're basically probability tables where AB would be the probability of an A being followed by a B. So assuming you have a given letter solved, that can be used to solve the letters next to it, rather than just guessing. For example, if you've got the word "y_u", it's obvious to you that the word is you, but not to the computer. If you've got the letters N, C, and O left, bigraphs will tell you that YN and YC are very uncommon where as YO is much more likely, so even if your text has unusual letter frequencies (which is easy when it's short) you still have a fairly accurate system for solving for unknowns. You can hunt around for a compiled dataset, or do your own analysis, but make sure to use a lot of varied text, a lot of Shakespeare is not the same as half of Shakespeare and half journal articles.


Q:

Page redirect within the same domain

I have moved my old website from static html pages to drupal. Now I want to redirect old pages that I now get 404 errors upon request, to new drupal nodes.
What is the best approach to do this and how? Can it be done using .htaccess directives?

A:

If you don't know what the address was, making a catch-all url would be a good way but that may cause some problems to drupal's working parts.
If you know the url of the old pages you can create a simple map or just simple rules with the .htaccess would be the safer route.
An example of catch-all would be:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/index.php$
RewriteRule . index.php

The above rules would redirect anything that is not a existent file or folder within your domain and not index.php and redirect it do index.php.
The other way would be knowing the urls and doing something like this:
RewriteEngine on
# screenshot's page
RewriteRule ^(screenshot.html)$ index.php?section=screenshot [R=301,L]

There might be other ways too but these 2 were what i could thing right away.


Q:

How to get random string items from an array randomly and put each character of the string word into li tags randomly

I am trying to prepare a vocabulary practice exercise. In this exercise the letters of a word are seperated in li tags and below that there is a an answer button to show the correct order of the letters. Here you can see how a "rabbit" word asked.

A

I

R

B

B

T

RABBIT

       <button class="bttnStyle" id="show4">▼ Answer</button>

well every thing is ok by the help of ready codes found on internet and a user can drag the letters into the correct order and see the answer. BUT the words are the same all the time. how can I get random words from an array and put each letter of the words into the li tags randomly. So that the user can practice different words on each page load. I've found the shuffle word code below but I cant figure out how to put letters in to the li tags. I am not good at javascript.

A:

Ok, first of all I added JQuery which helps with DOM manipulation a lot (It's that $ sign stuff).
After that i get the ul element $("#items4"); with this and save into a variable.
You already had your shuffled array with words. So I made the first Word in the list into an array (var word = callwords[0].split("");) and called that shuffle function again to mesh up the characters: var shuffledWord = getRandomSubarray(word, word.length);.
And changing the solution to word, $("#p4").html(word)
After this its quite easy you empty your unordered list ul.empty(); and then append all the li's with one char in it one by one. shuffledWord.forEach(function(char){ ul.append('
'+ char +'
') }); by iterating over the shuffled word.

function getRandomSubarray(arr, size)
{
   var shuffled = arr.slice(0), i = arr.length, temp, index;
   while (i--)
   {
      index = Math.floor(parseInt((i + 1) * Math.random()));
      temp = shuffled[index];
      shuffled[index] = shuffled[i];shuffled[i] = temp;
   }
   return shuffled.slice(0, size);
}

var mywordsList = ["class","classroom","book","bookcase","brush","calendar","clock","crayon"];
callwords = getRandomSubarray(mywordsList, mywordsList.length);

var word = callwords[0].split("");
$("#p4").html(word)
var shuffledWord = getRandomSubarray(word, word.length);

var ul = $("#items4");
ul.empty();
shuffledWord.forEach(function(char){
   ul.append('
'+ char +'
')
});

A

I

R

B

B

T

RABBIT

       <button class="bttnStyle" id="show4">▼ Answer</button>

And as a side note for the future if you see this in your code callwords = getRandomSubarray(mywordsList, 7), don't do this because if you change your mywordsList e.g by adding one more word you always have to change the function call by counting up the value. I corrected this in my example.
Just do callwords = getRandomSubarray(mywordsList, mywordsList.length) and you never have to think about it again:).


Q:

Disable XML Entity resolving in JDOM / DOM

I am writing a Java application for the postprocessing of XML files.
These xml files come from an RDF-Export of a Semantic Mediawiki, so they have rdf/xml syntax.
My problem is the following:
When I read the xml file, all the entities in the file get resolved to their value which is specified in the Doctype. For example in the Doctype I have
<!DOCTYPE rdf:RDF[
<!ENTITY wiki 'http://example.org/smartgrid/index.php/Special:URIResolver/'>
..
]>

and in the root element
<rdf:RDF
xmlns:wiki="&wiki;"
..
>

This means
<swivt:Subject rdf:about="&wiki;Main_Page">

becomes
<swivt:Subject rdf:about="http://example.org/smartgrid/index.php/Special:URIResolver/Main_Page">

I have tried using JDOM and the standard Java DOM.
The code I think is relevant here is for standard DOM:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setExpandEntityReferences(false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

and for JDOM
SAXBuilder builder = new SAXBuilder();
    builder.setExpandEntities(false); //Retain Entities
    builder.setValidation(false);
    builder.setFeature("http://xml.org/sax/features/resolve-dtd-uris", false);

But the Entities are resolved throughout the whole xml document none the less.
Am I missing something? Hours of search has only led me to the 'ExpandEntities' commands, but they don't seem to work.
Any hint is highly appreciated :)

A:

I recommend the JDOM FAQ:
[http://www.jdom.org/docs/faq.html#a0350]
How do I keep the DTD from loading? Even when I turn off validation the parser tries to load the DTD file.
Even when validation is turned off, an XML parser will by default load the external DTD file in order to parse the DTD for external entity declarations. Xerces has a feature to turn off this behavior named "http://apache.org/xml/features/nonvalidating/load-external-dtd" and if you know you're using Xerces you can set this feature on the builder.
builder.setFeature(
  "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

If you're using another parser like Crimson, your best bet is to set up an EntityResolver that resolves the DTD without actually reading the separate file.
import org.xml.sax.*;
import java.io.*;

public class NoOpEntityResolver implements EntityResolver {
  public InputSource resolveEntity(String publicId, String systemId) {
    return new InputSource(new StringBufferInputStream(""));
  }
}

Then in the builder...
builder.setEntityResolver(new NoOpEntityResolver());

There is a downside to this approach. Any entities in the document will be resolved to the empty string, and will effectively disappear. If your document has entities, you need to setExpandEntities(false) code and ensure the EntityResolver only suppresses the DocType.


Q:

Exporting a database to a different schema

I am creating an web application which is replacing the outdated one I currently use. The database is also outdated and horribly structured. For testing purposes I would like to export the old database and load it into the new one to have test data for the new web application. However, because of the schema changes to the database I need to manually change:

Table names
Column names

Example:
Old Database Table: part
id | date | user

New Database Table: apx_parts
id | date_created | user_id

Is there a MySQL tool or something to automate this? Would it have to be self-written in a scripting language?
Edit
Just to clarify, the reason I want it automated is because I want to use the most recent data that the old application is collecting.

A:

You're probably thinking about using mysqldump to copy the schema and data over.  Instead, think about exporting the data by itself.
Create the new database and tables as you normally would.
Export the data from the old database using SELECT...INTO.  Column names don't matter here.  If there are new columns in the new database, you can compute their values in this SELECT or just ignore them.
Import the data into the new database using LOAD DATA
Good luck.


Q:

tikz, minipage and positioning problem

I am using tikz and minipage to create a note box inside a description list. The problem I am facing is that I practically do not have any control over the positioning of the minipage and the corresponding note text. I would want to position the note text in such a manner in which the surrounding text is not wrapped around it (by which I mean no inline embedding), and I could position the note box in accordance with the layout of the page (say take it left, or right, or position it around the center, et al.). Can anyone suggest a method to achieve both of the above? The MWE follows.
TIA
\documentclass[11pt]{report}
\usepackage{tikz}
\usetikzlibrary{shapes,snakes}
\begin{document}
 \begin{description}
\item[\emph{Point:}] texttexttexttexttexttexttexttexttext...
 % copied from http://www.texample.net/tikz/examples/boxes-with-text-and-math/
\vspace{3mm}
\begin{tikzpicture}
\node [mybox] (box){%
    \begin{minipage}{0.9\textwidth}
Note text.
    \end{minipage}
};
\node[fancytitle, right=10pt] at (box.north west) {NOTE};
\node[fancytitle, rounded corners] at (box.east) {$\clubsuit$};
\end{tikzpicture}
texttexttexttexttexttexttexttexttext...
\end{description}
\end{document}

A:

First your example:
\documentclass[11pt]{report}
\usepackage{tikz,showframe}
\usetikzlibrary{shapes,positioning}
\tikzset{mybox/.style = {draw=red, fill=blue!20, line width=1pt,
                          rectangle, rounded corners, inner sep=10pt, inner ysep=20pt},
         fancytitle/.style ={fill=red, text=white}
         }
\begin{document}
 \begin{description}
    \item[\emph{Point:}] texttexttexttexttexttexttexttexttext...

    % copied from http://www.texample.net/tikz/examples/boxes-with-text-and-math/
      \vspace{3mm}
       \begin{tikzpicture}
        \node [mybox] (box){%
           \begin{minipage}{\dimexpr\textwidth-\leftmargin-22pt\relax}
             Note text.
           \end{minipage}
          };
        \node[fancytitle, right=10pt] at (box.north west) {NOTE};
        \node[fancytitle, rounded corners,overlay] at (box.east) {$\clubsuit$};
       \end{tikzpicture}

      texttexttexttexttexttexttexttextt
  \end{description}
\end{document}

Now with tcolorbox
\documentclass[11pt]{report}
\usepackage[many]{tcolorbox}
\tikzset{fancytitle/.style ={fill=red, text=white}}
\newtcolorbox{mybox}[2][]{
  enhanced jigsaw,
  width=0.5\textwidth,  %% change
  colback=blue!20,
  colframe=red,
  title=#2,
  boxrule=1pt,
  left=10pt,right=10pt,top=20pt,bottom=20pt,
  attach boxed title to top left= {xshift=10pt,yshift*=-\tcboxedtitleheight/2},
  boxed title style={size=small,colback=red,colframe=green!75!black,arc=0ex},
  before=\par\vspace{3mm},
  after=\par,
  overlay unbroken and first ={
    \node[fancytitle, rounded corners] at (frame.east) {$\clubsuit$};
    },
  #1
}

\begin{document}
 \begin{description}
    \item[\emph{Point:}] texttexttexttexttexttexttexttexttext...
       \begin{mybox}{NOTE}
          Note text.
       \end{mybox}
      texttexttexttexttexttexttexttextt
  \end{description}
\end{document}

And an example from manual:
\documentclass[11pt]{report}
\usepackage[many]{tcolorbox}
\usepackage{lipsum}
\usepackage{varwidth}
\newtcolorbox{mybox}[2][]{enhanced,
attach boxed title to top left={xshift=1cm,yshift=-2mm},
fonttitle=\bfseries,varwidth boxed title=0.7\linewidth,
colbacktitle=green!45!white,coltitle=green!10!black,colframe=green!50!black,
interior style={top color=yellow!10!white,bottom color=green!10!white},
boxed title style={enhanced,boxrule=0.75mm,colframe=white,
borderline={0.1mm}{0mm}{green!50!black},
borderline={0.1mm}{0.75mm}{green!50!black},
interior style={top color=green!10!white,bottom color=green!10!white,
middle color=green!50!white},
drop fuzzy shadow},
overlay unbroken and first ={
    \node[fill=red, text=white, rounded corners] at (frame.east) {$\clubsuit$};
    },
title={#2},#1}

\begin{document}
 \begin{description}
    \item[\emph{Point:}] texttexttexttexttexttexttexttexttext...
       \begin{mybox}{My title}
         \lipsum[2]
       \end{mybox}
      texttexttexttexttexttexttexttextt
  \end{description}
\end{document}


Q:

Image in djangocms-teaser

I've got a question about functionality of djangocms-teaser. Is there a way to import a scaliable picture in the teaser? To make it more fancy.
For example, I've got pic 300*300 on my PC, but when I load it into teaser, it automatically (or manually) re-sizes to 50*50.
Maybe you got some ideas about how to implement that.
Thanks in advance.

A:

Kek, I've found a solution for my question.
In teaser.html (can be found in site-packages-->djangocms-teaser) added width="***".  That made images shown in teasers smaller.


Q:

GRUB is still beta after upgrade to 14.04

After I upgraded to 14.04 the GRUB still says beta.

A:

Ubuntu 14.04 shipped with a beta version of Grub2. To be specific "2.02~beta2-9".
Sources:
http://packages.ubuntu.com/trusty/grub2
Will Ubuntu 14.04 Have Improved UEFI Support Or Will We Be Using Boot-repair For The Next 5 Years?


Q:

Como podria emitir un sonido en una app de WPF de Visual Studio mediante un controlador?

muy buenas, estoy intentando realizar un controlador , concretamente un botón que al pulsar, la interfaz WPF de Visual Studio me emita un sonido simple (como si es formato wav o mp3), sin embargo todo lo que he visto para hacerlo lo realizan en Windows Forms y nadie lo ha hecho en una WPF, no es posible hacerlo o simplemente la gente prefiere hacerlo en el otro. Alguien tiene idea de como se podría hacer en WPF?

A:

Agrégalo directamente como un trigger en el etiquetado XAML, algo así:
<Button Content ="Play">
   <Button.Style>
    <Style>
     <Style.Triggers>
      <EventTrigger RoutedEvent="Button.Click">
       <EventTrigger.Actions>
        <SoundPlayerAction Source="02 Best I Ever Had.wav"></SoundPlayerAction>
       </EventTrigger.Actions>
      </EventTrigger>
     </Style.Triggers>
    </Style>
   </Button.Style>
  </Button>

Necesitarás referenciar el namespace System.Media.SoundPlayer


Q:

How do I convert Twips to Pixels in .NET?

I'm working on a migration project in which a database actually stores display sizes in twips.
Since I can't use twips to assign sizes to WPF or Winforms controls, I was wondering if .NET has a conversion method usable at runtime?

A:

It turns out that the migration tool has something, but it wouldn't do any good at runtime.  Here's what I did (if the hard-coded value in the extension method were changed to the value for points per inch it would work as a point converter too):
1 Twip = 1/1440th of an inch.
The .NET Graphics object has a method DpiX and DpiY which can be used to determine how many pixels are in an inch.
Using those measurements I created the following extension methods for Graphics:
using System.Drawing;

static class Extensions
{
    /// <summary>
    /// Converts an integer value in twips to the corresponding integer value
    /// in pixels on the x-axis.
    /// </summary>
    /// <param name="source">The Graphics context to use</param>
    /// <param name="inTwips">The number of twips to be converted</param>
    /// <returns>The number of pixels in that many twips</returns>
    public static int ConvertTwipsToXPixels(this Graphics source, int twips)
    {
        return (int)(((double)twips) * (1.0 / 1440.0) * source.DpiX);
    }

    /// <summary>
    /// Converts an integer value in twips to the corresponding integer value
    /// in pixels on the y-axis.
    /// </summary>
    /// <param name="source">The Graphics context to use</param>
    /// <param name="inTwips">The number of twips to be converted</param>
    /// <returns>The number of pixels in that many twips</returns>
    public static int ConvertTwipsToYPixels(this Graphics source, int twips)
    {
        return (int)(((double)twips) * (1.0 / 1440.0) * source.DpiY);
    }
}

To use these methods one simply has to do the following (assuming you're in a context where CreateGraphics returns a Drawing.Graphics object (here this is a Form, so CreateGraphics is inherited from Form's super-class Control):
using( Graphics g = CreateGraphics() )
{
    Width = g.ConvertTwipsToXPixels(sizeInTwips);
    Height = g.ConvertTwipsToYPixels(sizeInTwips);
}

See the "Remarks" section in the Graphics Class documentation for a list of ways to obtain a graphics object.  More complete documentation is available in the tutorial How to: Create Graphics Objects.
Brief summary of easiest ways:

Control.CreateGraphics
a Paint event's PaintEventArgs has a Graphics available in its Graphics property.
Hand Graphics.FromImage an image and it will return a Graphics object that can draw on that image. (NOTE: It is unlikely that you'll want to use twips for an actual image)

A:

For migration projects we can use built in converstion support functions
microsoft.visualbasic.compatibility.vb6.twipsperpixelx
microsoft.visualbasic.compatibility.vb6.twipsperpixely

A:

For reference, another C# version, using the Win32 API instead of requiring a Graphics objects:
using System.Runtime.InteropServices;

static class SomeUtils {

  public static int ConvertTwipsToPixels(int twips, MeasureDirection direction) {
    return (int)(((double)twips)*((double)GetPixperinch(direction))/1440.0);
  }

  public static int ConvertPixelsToTwips(int pixels, MeasureDirection direction) {
    return (int)((((double)pixels)*1440.0)/((double)GetPixperinch(direction)));
  }

  public static int GetPPI(MeasureDirection direction) {
    int ppi;
    IntPtr dc = GetDC(IntPtr.Zero);

    if (direction == MeasureDirection.Horizontal)
      ppi = GetDeviceCaps(dc, 88); //DEVICECAP LOGPIXELSX
    else
      ppi = GetDeviceCaps(dc, 90); //DEVICECAP LOGPIXELSY

    ReleaseDC(IntPtr.Zero, dc);
    return ppi;
  }

  [DllImport("user32.dll")]
  static extern IntPtr GetDC(IntPtr hWnd);

  [DllImport("user32.dll")]
  static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);

  [DllImport("gdi32.dll")]
  static extern int GetDeviceCaps(IntPtr hdc, int devCap);
}

public enum MeasureDirection {
  Horizontal,
  Vertical
}

The MeasureDirection is supposed to be specified as there is no guarantee that pixels are always square (according to the kb).
Reference: kb210590: ACC2000: How to Convert Twips to Pixels


Q:

Are these two functions equal?

If $f(x) = \frac{x^2 − 4}{x − 2}$ and $g(x) = x + 2$, then we can say the functions
$f = g$
I think this is false but I cannot prove it.

A:

Some teachers might tell you these functions are the same. Other teachers will tell you that they are not. Both viewpoints have merit. However, usually those espousing equality are just being sloppy.
$$f(x) = \dfrac{x^2-4}{x-2} = \dfrac{(x-2)(x+2)}{x-2} = x+2=g(x)$$
The above statement is true everywhere it is defined (i.e. as long as $x \not= 2$).
In a loose sense $f$ and $g$ are the "same".
However, strictly speaking the function $f$ and the function $g$ are equal on the domain of $f$. Yet they are different functions since $g$ is defined at $x=2$ while $f$ is not (they have different domains).
Now for many purposes these two functions can be treated as equal (which is why some textbooks/teachers will say they are the "same"). For example:
$$ \lim\limits_{x \to 2} f(x) = \lim\limits_{x \to 2} \dfrac{x^2-4}{x-2} = \lim\limits_{x \to 2} \dfrac{(x-2)(x+2)}{x-2} = \lim\limits_{x \to 2} x+2 = \lim\limits_{x \to 2} g(x) = g(2) = 2+2=4$$
The reason we can do this with the limit is that the limit concerns points "close to" $x=2$. However, $x$ is never allowed to be exactly equal to $2$ (in the limit). Since we aren't actually working at $x=2$, $f(x)=g(x)$ everywhere we are limiting. :)


Q:

PHP - Deleting content of div doesn't work in specific file

I wrote a function which opens a HTML file, deletes the content of divs with a certain class and saves the file. I created 3 testfiles in three different locations. My function works great on site.html and site3.html, but not on site2.html
The folder structure is as the following:
/testing/script.php // contains my function

/testing/site.html
/testing/folder1/site2.html // script doesn't work in this file
folder2/site3.html

The HTML of the files is identical
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Content of site2.html

not here

foo

This is my script.php
<?php

    $urls = array(
            "site.html",
            "/folder1/site2.html",
            "../folder2/site3.html"
        ); // get the urls of the files

    function DeleteContent () {

        global $urls;

        echo "DeleteContent is running";

        if (is_array($urls) || is_object($urls)) {
            foreach($urls as $url) {

                $dom = new DOMDocument;
                $dom->loadHTMLFile($url);
                $xpath = new DOMXPath($dom);
                $pDivs = $xpath->query(".//div[@class='string']");

                foreach ( $pDivs as $div ) {
                    $div->removeChild($div->firstChild);
                }

                $dom->saveHTMLFile($url);

            }
        }
    }

    DeleteContent();

?>

I get this error
Catchable fatal error: Argument 1 passed to DOMNode::removeChild() must be an instance of DOMNode, null given, called in /testing/script.php on line 57 and defined in /testing/script.php on line 29
// line 29 in original file (adjusted it for the question)
foreach ( $pDivs as $div ) {
    $div->removeChild($div->firstChild); // line 29
}

A:

All I can suggest is testing for firstChild before removing it, because your code otherwise seems fine.
foreach ( $pDivs as $div )
{
    if( $div->firstChild )
    {
      $div->removeChild( $div->firstChild );
    }
}


Q:

Bootstrap tabs not changing the content when clicked more than once

I have been trying to implement tab into one of my pages. The code is as follows.

Vehicles

Battery

Charging

What I have done is, I have created two columns, one containing the links and the other containing the region where the data should be shown according to the link clicked. When run, the code actually works for once, i.e. the when the links are clicked for the first time, it shows the respective content on the right. But when I try to access another link, it does not work. It sort of works one time only. What should I do to make them work no matter how many times I want to toggle between data?

A:

You didn't add the 'nav nav-tabs' list container for your nav-tabs. Right now your all links are working as an independent internal link. Hence it works for just one click.
Here is update code

Vehicles

Battery

Charging

Let me know if it meets your requirements.


Q:

Is it true that if $X$ is connected, then for every nonempty proper subset $A$ of $X$, we have $\mathbf{Bd} \ne \emptyset$

Is it true that if $X$ is connected, then for every nonempty proper subset $A$ of $X$, we have $\mathbf{Bd} \ne \emptyset$? Does the converse hold?
I start by trying to understand what $\mathbf{Bd}$ means in "formal terms" (i.e. $\bar{A} \cap \overline{X-A}$ is the 'boundary' of $A \in X$)?
This means I'm supposed to figure out if the boundary of subset of a connected space is empty or not, right? I think that if a set is connected then it contains no partition into two sets, so there would exist points that are both in $A$ and in the complement of $A$ in $X$. This would be an informal definition of a boundary. (A boundary contains points in a set $A$ and points outside of it, right?)
What I mean is, if $X$ is connected, and $A \subset X$ is connected, then $A$ could have a boundary which means that technically, $X$ cannot be partitioned into $A$ and $A$-complement without making the boundary of $A$ an empty set.
Right?

A:

Be careful: any set with more than one element can be partitioned into two non-empty sets; a connected set cannot be partitioned into two non-empty relatively open sets. And in your last paragraph it’s the closures of $A$ and $X\setminus A$ whose disjointness makes the boundary of $A$ empty.
The easiest way to prove the result is to prove the contrapositive. Suppose that $A$ is a non-empty proper subset of a space $X$, and suppose further that $\operatorname{bdry}A=\varnothing$. As you say, $\operatorname{bdry}A=(\operatorname{cl}A)\cap\operatorname{cl}(X\setminus A)$, so $\operatorname{cl}A$ and $\operatorname{cl}(X\setminus A)$ are disjoint closed sets whose union is $X$. Each of them is therefore the complement of a closed set, so each is open. Moreover, $\operatorname{cl}A\supseteq A\ne\varnothing$ and $\operatorname{cl}(X\setminus A)\supseteq X\setminus A\ne\varnothing$, so $\{\operatorname{cl}A,\operatorname{cl}(X\setminus A)\}$ is a partition of $X$ into non-empty open sets, and $X$ therefore is not connected.


Q:

What is the Biblical basis against being able to predict the date of the end of the world?

Recently, there have been a few people (e.g. Harold Camping) who have predicted the end of the world.  Historically, the Jehovah's Witnesses (Watchtower Bible & Tract Society) have also predicted the end of the world several times.
What is the Biblical basis for the claim that no one can predict the date that the world will end?

A:

Jesus taught that we might be able to read the signs that it was near, but that no one would be able to know what day the end would come:

"From the fig tree learn its lesson: as soon as its branch becomes tender and puts forth its leaves, you know that summer is near. So also, when you see these things taking place, you know that he is near, at the very gates. Truly I tell you, this generation will not pass away until all these things have taken place. Heaven and earth will pass away, but my words will not pass away. But about that day or hour no one knows, neither the angels in heaven, nor the Son, but only the Father. Beware, keep alert; for you do not know when the time will come. It is like a man going on a journey, when he leaves home and puts his slaves in charge, each with his work, and commands the doorkeeper to be on the watch. Therefore, keep awake—for you do not know when the master of the house will come, in the evening, or at midnight, or at cockcrow, or at dawn, or else he may find you asleep when he comes suddenly. And what I say to you I say to all: Keep awake." —Mark 13:28-37

A:

What is the Biblical basis against being able to predict the date of the end of the world?
Here are a couple of more verses.

Acts 1:6-7  When they therefore were come together, they asked of him,
  saying, Lord, wilt thou at this time restore again the kingdom to
  Israel?   And he said unto them, It is not for you to know the times
  or the seasons, which the Father hath put in his own power.
1 Thessalonians 5:2-3  For yourselves know perfectly that the day of
  the Lord so cometh as a thief in the night.   For when they shall say,
  Peace and safety; then sudden destruction cometh upon them, as travail
  upon a woman with child; and they shall not escape.


Q:

How to re-populate form with old data if a validation error occurs?

The problem here is that the country field is not being re-populated whenever I submit the form. What I expect is for the user to submit the form and have the server validate it and redirect back with the errors and keep the data that the user input before submitting.
For some unknown reason, the country field is not getting the old input but the state field is getting the old input perfectly.
<select  id="country" name ="country" class="form-control rounded input-lg text-center no-border"  required autofocus  <option> </option>
</select> </br>
<select name ="state" id ="state" class="form-control rounded input-lg text-center no-border" required autofocus
 <option>{{ Request::old('state') }}</option>
</select> </br>

A:

You can use just old() helper for that:
<input type="text" name="username" value="{{ old('username') }}">

Another way to do that is to use Laravel Collective form model binding:
{!! Form::model($user, ['route' => ['user.update', $user->id]]) !!}

In this case all form data will be re-populated automatically.


Q:

Show only children of current page in submenu

I have checked the official documentation and also these pages:
How do you only show children of "active" parent in a Structure section's nav?
How to output a structure sub-navigation of current page
I still can't get this to work though. I have tried various code and currently have this (from official docs):

{% set pages = craft.entries.section('pages').level('>1') %}
{% nav entry in pages %}

    {{ entry.title }}
        {% ifchildren %}

               {% children %}

         {% endifchildren %}

{% endnav %}

This outputs all the children whenever I'm on any top level page. My structure is a little different though, like so (shortened for brevity):
Home
About (structure: 'pages', entry type: 'aboutPage')
  - Aims (structure: 'pages', entry type: 'aboutPage')
  - Governance (structure: 'pages', entry type: 'aboutPage')
Services (structure: 'pages', entry type: 'servicesPage')
  - Residential (structure: 'pages', entry type: 'servicesPage')
  - Homecare (structure: 'pages', entry type: 'servicesPage')
Resources (structure: 'pages', entry type: 'resourcePage')
  - Health (structure: 'pages', entry type: 'resourcePage')
  - External (structure: 'pages', entry type: 'resourcePage')

You can see I have a tree which uses a single 'pages' structure to keep everything obvious in the admin section. I then just create an entry, choose the parent and choose the entry type to add content.
I use a structure 'mainMenu' to add links manually to the main menu using a related entry field. So I have:
Home - About - Services - Resources
As top level pages. When I'm on a top level page, I want to show children of this current page and to hide the unordered list element when there are no children of the current page, and I'm stuck.
Can anyone point me in the right direction? Thanks in advance.

A:

Ran into the same issues you had. Pulled this from a working site I recently built.
Basically you have to get the topmost page. I found entry.getAncestors().level(1).first() works for that no matter what level you're in.
From there, you just get everything that's underneath it. But first check to see if there's actually any children using {% if topLevel.hasDescendants %}
       <! -- local navigation -->

        {% set topLevel = (entry.level == 1) ? entry : entry.getAncestors().level(1).first()  %}

        {# don't show the tree if nothing's under it #}

        {% if topLevel.hasDescendants %}

{{topLevel}}

            {% set subnav =  topLevel.getDescendants()  %}

            {% nav page in subnav  %}
            {% if page.id != entry.id %}
{{ page.getLink() }}
{%else%}
{{page}}
{%endif%}

                {% ifchildren %}

                            {% children %}

                {% endifchildren %}

            {% endnav %}

       {% endif %}


Q:

Joining Keywords in a list NYT

For each article that a keyword list is returned for. We want to join all the words using the key --> values into a list, as shown below. I would like to strip out the ‘u’ from the list, before I do the append. Then we want to compare how many common words in both list and return the result.
Example lists returned from dic['keywords']:
Article one returns:
    [
  {
    u'value': u'Dunford, Joseph F Jr',
    u'name': u'persons',
    u'rank': u'1'
  },
  {
    u'value': u'Afghanistan',
    u'name': u'glocations',
    u'rank': u'1'
  },
  {
    u'value': u'Afghan National Police',
    u'name': u'organizations',
    u'rank': u'1'
  },
  {
    u'value': u'Afghanistan War (2001- )',
    u'name': u'subject',
    u'rank': u'1'
  },
  {
    u'value': u'Defense and Military Forces',
    u'name': u'subject',
    u'rank': u'2'
  }
]

Article two returns:
[
  {
    u'value': u'Gall, Carlotta',
    u'name': u'persons',
    u'rank': u'1'
  },
  {
    u'value': u'Gannon, Kathy',
    u'name': u'persons',
    u'rank': u'2'
  },
  {
    u'value': u'Niedringhaus, Anja (1965-2014)',
    u'name': u'persons',
    u'rank': u'3'
  },
  {
    u'value': u'Kabul (Afghanistan)',
    u'name': u'glocations',
    u'rank': u'2'
  },
  {
    u'value': u'Afghanistan',
    u'name': u'glocations',
    u'rank': u'1'
  },
  {
    u'value': u'Afghan National Police',
    u'name': u'organizations',
    u'rank': u'1'
  },
  {
    u'value': u'Afghanistan War (2001- )',
    u'name': u'subject',
    u'rank': u'1'
  }
]

Desired Output:
List1 = ['Dunford, Joseph F Jr',’ Afghanistan’, ‘Afghan National Police’, ‘: Afghanistan War (2001- )’, ‘Defense and Military Forces’]
List2 = [‘Gall, Carlotta'’,’ u'Gannon, Kathy',’ Niedringhaus, Anja (1965-2014)’,’Afghanistan’]

Keywords in common: 2
My Code is as follows:
  from flask import Flask, render_template, request, session, g, redirect, url_for
  from nytimesarticle import articleAPI

  api = articleAPI('X')

articles = api.search( q = 'Afghan War',
 fq = {'headline':'', 'source':['Reuters','AP', 'The New York Times']},
 begin_date = 20111231 )

def parse_articles(articles):
'''
This function takes in a response to the NYT api and parses
the articles into a list of dictionaries
'''
news = []
for i in articles['response']['docs']:
    dic = {}
    dic['id'] = i['_id']
    if i['abstract'] is not None:
        dic['abstract'] = i['abstract'].encode("utf8")
    dic['headline'] = i['headline']['main'].encode("utf8")
    dic['desk'] = i['news_desk']
    dic['date'] = i['pub_date'][0:10] # cutting time of day.
    dic['section'] = i['section_name']
    dic['keywords'] = i['keywords']
    print dic['keywords']
    if i['snippet'] is not None:
        dic['snippet'] = i['snippet'].encode("utf8")
    dic['source'] = i['source']
    dic['type'] = i['type_of_material']
    dic['url'] = i['web_url']
    dic['word_count'] = i['word_count']
    # locations
    locations = []
    for x in range(0,len(i['keywords'])):
        if 'glocations' in i['keywords'][x]['name']:
            locations.append(i['keywords'][x]['value'])
    dic['locations'] = locations
    # subject
    subjects = []
    for x in range(0,len(i['keywords'])):
        if 'subject' in i['keywords'][x]['name']:
            subjects.append(i['keywords'][x]['value'])
    dic['subjects'] = subjects
    news.append(dic)
return(news)

print(parse_articles(articles))

A:

You can use list comprehension to build lists from the given dict.
d = [{u'value': u'Dunford, Joseph F Jr', u'name': u'persons', u'rank': u'1'}, {u'value': u'Afghanistan', u'name': u'glocations', u'rank': u'1'}, {u'value': u'Afghan National Police', u'name': u'organizations', u'rank': u'1'}, {u'value': u'Afghanistan War (2001- )', u'name': u'subject', u'rank': u'1'}, {u'value': u'Defense and Military Forces', u'name': u'subject', u'rank': u'2'}]
print [v['value'] for v in d] # prints [u'Dunford, Joseph F Jr', u'Afghanistan', u'Afghan National Police', u'Afghanistan War (2001- )', u'Defense and Military Forces']


Q:

Bada's AppLog mangles my reported strings strangely

I'm adapting the example of Forms Management here and found AppLog to mangle my reported strings strangely.
void
MyFormsApp::OnUserEventReceivedN (RequestId requestId, IList *pArgs)
{
    AppLog("OnUEveRxdNb, beginning");
    if(!pArgs) {
        AppLog("OnUserEventReceivedN, null List");
        return;
    }

    if(requestId==TabsForm::TABS_SWITCH_CALL)
    {
        Integer * tabindex = static_cast<Integer *>(pArgs->GetAt(0));
        MyLog(L"OnUEveRxdN, formID : ", formID->ToInt());
        //MyLog(L"OnUserEventReceivedN, formID : ", formID->ToInt());
        if(tabindex)
        {
            switch(tabindex->ToInt())
            {
            case TabsForm::SEARCH_TAB:
                frame_->SetCurrentForm(*search_form_);
                search_form_->RequestRedraw(true);
                break;
            case TabsForm::RESULTS_TAB:
                frame_->SetCurrentForm(*results_form_);
                results_form_->RequestRedraw(true);
                break;
            case TabsForm::CONTENTS_TAB:
                frame_->SetCurrentForm(*contents_form_);
                contents_form_->RequestRedraw(true);
                break;
            }
        }
    }
    pArgs->RemoveAll(true);
    delete pArgs;
} //closebracket

MyLog is
void MyLog(const String &badaStr) {
    char *natStr = new char[badaStr.GetLength()];
    for (int i = 0; i < badaStr.GetLength(); ++i)
        natStr[i] = badaStr[i];
    AppLog(natStr);
    delete[] natStr;
}

void MyLog(const mchar *pValue, const int int_param) {
    String str(pValue);
    result r = str.Append(int_param);
    MyLog(str);
}

void MyLog(const char *pValue, const int int_param) {
    String str(pValue);
    result r = str.Append(int_param);
    MyLog(str);
}

If you see where I've got the two calls to it the second was commented out because it appends garbage to the end of my string. I call these functions from various other places in my application without trouble but here the string must be truncated. It's not a total char count per function either because replacing the first AppLog with AppLog("BadaReader::OnUserEventReceivedN, beginning"); makes no difference.
Can anyone spot my mistake or is Bada 2.0.2 known for this kind of random glitch?

A:

Why do you need separate logging functions?
bada has three AppLog Macros.Yoc can use them.
Also, if you need to print String do,
AppLog("Log Statement %s",string_name->GetPointer());

string_name->GetPointer() returns const char*.


Q:

Why don't we allow a linear programming problem to have strictly '<' or '>' constraints?

I am new to linear programming and I have been asked this question
"Why don't we allow a linear programming problem to have strictly '<' or '>' constraints?"
But unable to answer it.
Kindly provide me an explanation on this.

A:

Consider the linear program on $\mathbb R$ consisting of one constraint: $x < 1$, with the function to be optimized being $f(x) = x$. What's the optimum? At what point is it achieved?
Answer: There's no optimum. Normally, it'd be at $x = 1$, but that just barely fails to meet the constraint. But for any $x$ less than $1$, there's a better solution, namely $(1+x)/2$.


Q:

Navigation in ReactNative

I want to navigation between two screen . I am try lot of code but not successul yet Here i am try this get undefined is not an object(RNGestureHandlerModule.State). Please help i am new in react native please check any help would be appreciated. If their any tuturial to proper guide please help let me know
My App.Js Look Like
 import React, {Component} from 'react';
    import {Platform, StyleSheet, Text, View} from 'react-native';
    import AppNavigator from './AppNavigator';

    type Props = {};
    export default class App extends Component<Props> {
      render() {
        return (

         <AppNavigator/>

        );
      }
    }

My appnavigation look like

    import { createStackNavigator } from 'react-navigation';
    import Home from './Home';
    import Friends from './Friends';

        const AppNavigator = createStackNavigator({
            Home: { screen: Home },
           Friends: { screen: Friends},
        });

        export default AppNavigator;

My Friend.js look Like
import React, {Component} from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

type Props = {};
export default class Friends extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
          <Button
           title="Back to home"
          onPress={() =>
            this.props.navigation.navigate('Home')
          }
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
My HOme.js

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';

type Props = {};
export default class Home extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
          <Button
          title="Back to home"
          onPress={() =>
            this.props.navigation.navigate('Home')
          }
        />

      </View>
    );
  }
}

A:

It is not linked to Navigation library. The issue is linked to 'RNGestureHandlerModule'. I assume you are using another library, probably 'react-native-gesture-handler'. Try removing and linking it using react-native link.
Found this related post here

A:

You are using the latest reactnavigation library. It requires to install react-native-gesture-handler. But if you are using Expo, you don't need to install this library since its already included in the sdk.
After by installing the react-native-gesture-handler library, run the react-native link command to link all the native dependencies.


Q:

Codeigniter, timezone_menu and date_default_timezone_set

I make use of Codeigniters timezone_menu which gives a drop down box of time timezones and I am wondering how are we supposed to make use of these timezones with PHPs date_default_timezone_set?
An example of codeigniters timezone is UP1. However, you can't use that with PHPs date_default_timezone_set as the string it takes in should be something like Europe/Berlin
The question is, is there a way to convert a codeigniter timezone string to a PHP one that can be accepted by the date_default_timezone_set?

A:

The following works for me:
// Example - timezones is part of the date helper function
// You obviously wouldn't echo it out, you would pass it in to
// set default timezone function in PHP based on the posted data from
// the dropdown
echo timezone_by_offset(timezones('UM5')); // ouputs 'America/Porto_Acre' which is (-5)

// And the function
function timezone_by_offset($offset) {
    $offset = ($offset+1) * 60 * 60;
    $abbrarray = timezone_abbreviations_list();

    foreach ($abbrarray as $abbr) {
        foreach ($abbr as $city) {
            if ($city['offset'] == $offset) {
                echo($city['timezone_id']);
                return true;
            }
        }
    }
    echo "UTC";
    return false;
}

EDIT
The original function didn't exclude DST offsets. timezone_abbreviations_list() lists 2x for a timezone that has DST marked as true, for example Tasmania appears under +11 and +10. So if DST == TRUE, ignore it as part of the return listing.
//-- Function -------------------------------------------------------------------
function timezone_by_offset($offset) {
    $abbrarray = timezone_abbreviations_list();
    $offset = $offset * 60 * 60;

    foreach ($abbrarray as $abbr) {
        foreach ($abbr as $city) {
            if ($city['offset'] == $offset && $city['dst'] == FALSE) {
                return $city['timezone_id'];
            }
        }
    }
    return 'UTC'; // any default value you wish
}

Some examples:
//-- Test Cases -------------------------------------------------------------------
echo timezone_by_offset(-12) . '
';
echo (date_default_timezone_set(timezone_by_offset(-12)) == TRUE ? 'Valid' : 'Not Valid'). '
';
// Etc/GMT+12
// Valid

echo timezone_by_offset(-10) . '
';
echo (date_default_timezone_set(timezone_by_offset(-10)) == TRUE ? 'Valid' : 'Not Valid'). '
';
// America/Anchorage
// Valid

echo timezone_by_offset(-8) . '
';
echo (date_default_timezone_set(timezone_by_offset(-8)) == TRUE ? 'Valid' : 'Not Valid'). '
';
// Etc/GMT+8
// Valid

echo timezone_by_offset(6) . '
';
echo (date_default_timezone_set(timezone_by_offset(6)) == TRUE ? 'Valid' : 'Not Valid'). '
';
// Asia/Aqtobe
// Valid

echo timezone_by_offset(7) . '
';
echo (date_default_timezone_set(timezone_by_offset(7)) == TRUE ? 'Valid' : 'Not Valid'). '
';
// Indian/Christmas
// Valid


Q:

HTML5 mobile game development vs. native game apps

What is the current state of game engines, frameworks, libraries and conversions related to the HTML5 set of technologies (including CSS3 and JavaScript libraries such as RaphaelJS, Impact, gameQuery); and how does the best of that compare with developing a native app (especially for iOS and Android)?
Especially in terms of performance, visuals and getting that "native feel".
Thoughts on solutions such as Appcelerator and Corona SDK are also appreciated.
In regards to Unity3D, is it possible to develop in it and still have the game be playable on a browser (such as current releases of Chrome or Firefox, at least) without any dependencies or having the user install anything (no unity web player).
What I'm looking for is how to develop in web standards as to reach the maximum number of platforms (including outside mobile) while still retaining a native experience for mobile without having to implement the game anew for iOS and Android.

A:

The HTML5 libraries are surprisingly good especially considering its young age. There are solid 2D/3D engines that support particle effects, physics, and the like. However, there is nothing comparable to established and mature game engines such as Unity or the Unreal Engine.
Also HTML5 libs in my experience like to be event driven. For example sprites will have an onclick events and there will not really be a traditional game loop.
For performance native apps are much, much quicker than anything having to do with the HTML 5 canvas. That is the extent of my experience though, I have no idea about Appcelerator or Corona SDK.
However if your goal is more the "maximum number of platforms" than the "web standards" part, I suggest a solution such as Unity which works on almost everything and thanks to its built in editor is a very productive engine.

A:

Tom here from Scirra, we make Construct 2 the HTML5 game maker.
We recently blogged about this, comparing HTML5 Canvas/WebGl/C++ DX performance.  You can read about it here:
http://www.scirra.com/blog/58/html5-2d-gaming-performance-analysis
And here's the graph:

I know it's not a performance in comparison to native mobile formats, but it is a comparison to desktop native apps which should give some indication of the performance gap.

A:

First and foremost, Corona SDK is lovely to work with. Lua's a great language, Corona's a very thorough framework, and the documentation's been great thus far.
In my opinion HTML5 game development isn't worth it yet. Both on desktop and mobile browsers. If your goal is to make an awesome game to run on desktops and mobile devices, then don't bother. If your goal is to make an HTML5 game, then go make it and use one of the frameworks people have mentioned (also look at Crafty or Gee for more of a drawing-type interface).
The primary reason is that when I make a game, I want to make a complete and polished game. Part of making a complete and polished game is good audio. Although the <audio> tag is supported on major browsers (assuming you provide enough different formats), managing your soundtrack programmatically with createElement is kind of a pain. SoundManager 2 is a band-aid, not a solution. In many cases it will just fall back on using a Flash object for desktops. At which point I ask, why not just make the darn thing in Flash?
On iOS, unless you use a hack like in Zynga's Jukebox library, you're actually limited to only playing sounds in response to user input. It's ridiculous.
Also, unless you're packaging your HTML5 game up as an app, people need a connection to play. The time I spend playing mobile games most is on the subway--no signal. And if you do package your game up, won't it be weird to not have sound? If I'm downloading a game I expect a certain level of responsiveness and polish. Read: a native app.
Until HTML5's further developed and mobile browsers are faster and HTML5 audio stops sucking, I will have fun playing with Javascript and <canvas> and all that, but I will not go so far as to produce a polished game with it. It boils down to what your goals are. Very few I know who play games and are not developers even have mobile HTML5 games on their radar. Again, if you want to make awesome HTML5 games, make HTML5 games. If you want to make and sell awesome games, make the quality of your players' experience a priority.


Q:

How to Ignore certain Errors in Development Tools?

On a test system I have a lot of 404 errors that are not important to me right now. Still they are cluttering the console in Chromium's Developer Tools, making it pretty much useless.
Is it possible to ignore errors of a certain type? In this case, I want all 404-errors to not be shown.

A:

If you need to filter errors for a particular domain, you can now do this directly using Chrome Developer Tools. Simply right click on the error you want to hide and then click Filter => Hide messages from...


Q:

Does iOS provide a function to get a device-specific suffix string?

On iOS there is this nice feature that an app developer can specify device-specific resources or keys in Info.plist by tacking on a device-specific suffix to the base name of the resource or key. Currently we have ~ipad and ~iphone.
I would like to use the same system for some of my app's registration domain user defaults that should have different values on the various devices. Do you know of a function or method in iOS that I can call to get the current device suffix? Although it is simple to code this myself, I prefer to use the system API whenever that is possible.
I don't really care whether the system gives me ~ipad and ~iphone, the strings just need to be unique for each device. I also prefer something that is human readable, which is why I am not enthusiastic about using UIDevice.userInterfaceIdiom (that's just a number). I also looked at UIDevice.model but I am unsure if this would be suitable.

A:

Just in case there is no positive answer, this is how my implementation of the desired function looks:
// NSStringAdditions.h
@interface NSString(NSStringAdditions)
- (NSString*) stringByAppendingDeviceSuffix;
@end

// NSStringAdditions.m
- (NSString*) stringByAppendingDeviceSuffix
{
  static NSString* deviceSuffix = nil;
  if (! deviceSuffix)
  {
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
      deviceSuffix = @"~iphone";
    else
      deviceSuffix = @"~ipad";
  }
  return [self stringByAppendingString:deviceSuffix];
}


Q:

JSON-formatted extract-document-data options node throws "unbalanced pairs" error when using multiple extract-paths

MarkLogic REST Client API's default search endpoint results in server error when using a query options node that contains more than one extract-path even though the request is successful when either extract-path is used individually within extract-document-data:
{"errorResponse":{"statusCode":500, "status":"Internal Server Error", "messageCode":"RESTAPI-INTERNALERROR", "message":"RESTAPI-INTERNALERROR: (err:FOER0000) Internal error:  JSON build, unbalanced pairs: "}}

The offending paths:
<extract-path xmlns:tei="http://www.tei-c.org/ns/1.0" xmlns:FO="http://founders.archives.gov/">/tei:text/FO:metadata/FO:ProjectCode</extract-path>

<extract-path xmlns:tei="http://www.tei-c.org/ns/1.0" xmlns:FO="http://founders.archives.gov/">/tei:text/FO:metadata/FO:ShortProjectTitle</extract-path>

Only occurs when the format is JSON--XML format behaves as expected. This error can be reproduced across disparate datasets.
The entire options node:
<options xmlns="http://marklogic.com/appservices/search">
  <search-option>unfiltered</search-option>
  <quality-weight>0</quality-weight>
  <page-length>10</page-length>
  <extract-document-data selected="include">
    <extract-path xmlns:tei="http://www.tei-c.org/ns/1.0" xmlns:FO="http://founders.archives.gov/">/tei:text/FO:metadata/FO:ProjectCode</extract-path>
    <extract-path xmlns:tei="http://www.tei-c.org/ns/1.0" xmlns:FO="http://founders.archives.gov/">/tei:text/FO:metadata/FO:ShortProjectTitle</extract-path>
  </extract-document-data>
</options>

I would simply extract the parent element FO:metadata; however, that returns a string, indicating a dependency on a parsing library (does it not?) which I would rather avoid if possible.
Any suggested workarounds are appreciated. Thanks.

A:

There is a known bug with the inline response that should be fixed in 8.0-3.
In the interim, it should work to get the extracted fragments either as XML or as a multiplepart/mixed response (which, if the source documents are XML would also be XML).


Q:

how to apply multiple count in hive query

i have table of 2 columns act,dst in hive:
  act      dst
  success  Info
  success  High
  failure  medium
  Blank    low
  failure  Info

I want to count of every field of act columns like
    act     count
    success  2
    failue   2
    Blank    1

Also if it is possible to find for both columns its good.

A:

Use group by and aggregation as count(*) in your select query
Try with this query:
select act,count(*) from <table_name> group by act;


Q:

Is it possible to create a Windows 7 virtual machine on Ubuntu Server without GUI?

I have a Ubuntu Server 12.04 server without GUI. Would it be possible to install Windows 7 (with GUI) as a virtual machine on the server? I want to use Windows 7 with remote desktop on my phone.

A:

You have to install this VM somewhere else or if you already have it, that's great. Otherwise will be difficult to install it without GUI.
And you can install and use Xvfb server for your VM (which is X virtual framebuffer). It works like X window, but without GUI. In case of some issues with your Windows, you could also make some screenshots from your Xvfb and save into file and see them somewhere else.


Q:

Subscribe to an observable within a loop in Angular

I'm having a use case where I need to subscribe to an Observable then looping the response in order to subscribe to another Observable using a data from the first Observable.
  getTasks(taskType: Observable<any>): void {
    taskType // Subscribing to the first Observable
      .subscribe(
        (tasks: any) => {
          let row: InboxTasks;
          for (const task of tasks) { // Looping through the result
            if (task.assigned_id) { // I need to extract that data in order to use it as an argument of the second Observable below
              this.auth.getUserById(task.assigned_id).subscribe((user) => this.username = `${user.firstname} ${user.lastname}`);
            }
            row = {
              assigned: this.username ? this.username : '', // Here I use my newly created property
              task: task.displayName
            };
            this.rowData = [
              ...this.rowData,
              row
            ];
          }
        }
      );
  }

Using that method the loop while be executed before the second Observable can be complete.
How can I manage to use this second Observable in that scenario?
Thanks

A:

You can first gather all inner Observables based on the response from the first Observable and wait until all of them complete with forkJoin:
taskType
  .pipe(
    concatMap(tasks => {
      const observables = [];
      for (const task of tasks) {
        observables.push(this.auth.getUserById(task.assigned_id));
      }
      return forkJoin(...observables).pipe(
        map(innerResults => ({
          innerResults,
          tasks
        }))
      );
    })
  )
  .subscribe(({ innerResults, tasks }) => ...);


Q:

str_replace is replacing string on wrong place

I am redesigning template mechanism of my one of the wordpress plugin. So the users can customized design as per their need. For this purpose. i am asking a template format string with some options which i can replace later.
Sample Template String :
$template = '';

Code:
$temp .= $template;
$temp = str_replace("%POST_TITLE%", $ptitle, $temp);
$temp = str_replace("%POST_URL%", the_permalink(), $temp);
$temp = str_replace("%POST_THUMB%", lead_img_thumb_post($width ,$height ,$imagepath ,$icontype ), $temp);

Output:
%POST_URL%%POST_URL%%POST_URL%

Why %POST_URL% is moving ahead

A:

You need to use get_the_permalink() instead. the_permalink() outputs the link to the browser direction. Using the get_whatever() instead will cause WP to return the data, instead of outputting it.


Q:

GET operations cannot have a body error while Android calling WCF web service

My android application is calling WCF web services yet I can't send my get request :
This my WCF contract
[OperationContract]
    [WebGet(UriTemplate = "ValidateLogin/{userId}/{password}",
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped)]
    LoginValidation ValidateLogin(string userId, string password);

and I'm calling this on my Android app
public String ValidateLogin(ArrayList<NameValuePair> httgetArgs){

    String result = "";

    String url = "http://10.0.2.2/WSCom.svc/ValidateLogin";
    InputStream is = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        setparameters(url , new UrlEncodedFormEntity(httgetArgs));

        HttpGet httget = new HttpGet(url);

        httget.setHeader("Accept", "application/json");
        httget.setHeader("Content-Type", "application/json");

        HttpResponse response = httpclient.execute(httget);

        HttpEntity entity = response.getEntity();

        is = entity.getContent();

    }
        catch (Exception e) {
        result = e.toString();
    }

    try {
        result = readStream(is);

        is.close();
    }
    catch (Exception e) {

        result = e.toString();
    }
    return (result);
    }

But I got the error as

Operation 'ValidateLogin' in contract 'IWSCom' uses GET, but also has body parameter 'userId'. GET operations cannot have a body. Either make the parameter 'userId' a UriTemplate parameter, or switch from WebGetAttribute to WebInvokeAttribute

A:

String user = "";
String pass = "";
String url = "http://10.0.2.2/WSCom.svc/ValidateLogin/" + user + "/" + pass;


Q:

What is the colloquial Cantonese translation for "还真是"?

A says: 他自从遇到车祸以后就不开车了。
B says: 还真是，我以为他不喜欢开车呢。

A:

'还真是' here is similar to  "It is actually true" in English (agree/affirm to A's statement)
In Cantonese, we would say "噉又係喎"
噉(this) | 又(also) | 係(true) | 喎(final particle: indicate 'agree/affirm')
Mandarin:

A: 他自从遇到车祸以后就不开车了。
B: 还真是，我以为他不喜欢开车呢。

Cantonese:

A: 佢自从遇到车祸之后就冇再楂車嘞。
B: 噉又係喎，我仲以为佢唔鐘意楂車㖭。