Q:

Can I disable AutoMapper reference cache?

I believe AutoMapper is using a cache when it is mapping lists of objects from one type to another.  Take a look at the following code:
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Mapper.CreateMap<Source, Destination>()
                       .ForMember(dest => dest.SomeOtherNumber, opt => opt.Ignore());

            Mapper.AssertConfigurationIsValid();

            var sourceList = new List<Source>();

            var s1 = new Source {SomeNumber = 10};
            var s2 = new Source {SomeNumber = 69};

            sourceList.Add(s1);
            sourceList.Add(s1);
            sourceList.Add(s1);
            sourceList.Add(s2);

            var destList = Mapper.Map<List<Source>, List<Destination>>(sourceList);

            destList[0].SomeOtherNumber = 100;

            destList.ForEach(x => Console.WriteLine("SomeNumber: {0}, SomeOtherNumber: {1}", x.SomeNumber, x.SomeOtherNumber));
            Console.ReadLine();
        }
    }

    public class Source
    {
        public int SomeNumber { get; set; }
    }

    public class Destination
    {
        public int SomeNumber { get; set; }
        public int SomeOtherNumber { get; set; }
    }

}

The output of the code shows that even though I set only the SomeOtherNumber of the first object in the destList list, the first three items have the same property value because they are referencing the same object reference.  I would like to know if I can disable this behavior, so even if I have duplicate references in the source list, I will not have duplicate references in the destination list.  Does this make sense?
Here's the ouput:
SomeNumber: 10, SomeOtherNumber: 100
SomeNumber: 10, SomeOtherNumber: 100
SomeNumber: 10, SomeOtherNumber: 100
SomeNumber: 69, SomeOtherNumber: 0

A:

I would say this is cannot be done with AutoMapper as the time being. The instance caching is built in pretty deep and currently it can't be turned off easily. Altough your use case is very strange... having the same source object multiple times in a list but you still want different destination objects is quite unusual in my point of view.
But it can be worked around with a pretty bad hack, because it will turn off instance caching globally and relies on the implementation details of AutoMapper so use it carefully. And if you still want to try it out the below mentioned solution is not working with Automapper 2.2.0 because of a bug which is only fixed in the development branch so you need to build AutoMapper from source or wait for the next release.
But nevertheless here are the details
The instance caching is handled by the TypeMapObjectMapperRegistry.CacheMappingStrategy [source] which like all the other ITypeMapObjectMapper implementation is a private class.
However the TypeMapObjectMapperRegistry.AllMappers field which should return all the ITypeMapObjectMapper is a public Func which can be overridden:
So add this code before the first usage of the Mapper class:
var baseMappers = TypeMapObjectMapperRegistry.AllMappers();
TypeMapObjectMapperRegistry.AllMappers = () =>
    baseMappers.Where(m => m.GetType().Name != "CacheMappingStrategy").ToArray();

Mapper.CreateMap<Source, Destination>();


Q:

How rigid is the max size of a VARCHAR in SQL Server?

i.e. if I create a VARCHAR(50) field, what happens if I try to assign it a value that's 100 characters long?
Will SQL Server let me do this? Is it somehow less efficient?

A:

If you try forcing a large string into a smaller-size variable, the incoming string will be simply chopped off at the appropriate size.
declare @Variable varchar (50)
set @Variable = replace (SPACE (100), ' ' , '.')
print @Variable

the output is 50 characters long
..................................................

If you try to force a large string into a small sized Field in a Table, an Error will be raised
declare @MyTable Table
(
    TestVariable varchar (50)
)
insert into @MyTable (TestVariable) select replace (SPACE (100), ' ' , '.')
select * from @MyTable

the output is
Msg 8152, Level 16, State 14, Line 6
String or binary data would be truncated.
The statement has been terminated.
TestVariable
------------------------------------------------

A:

It will throw an error saying that the value would be truncated.  It won't write more than the 50 characters you've specified, otherwise you wouldn't be able to prevent the row size from growing out of control

A:

Will SQL Server let me do this? Is it somehow less efficient?

It will emit an error, saying that the string or binary data would be truncated.


Q:

Javascript regex match for certain websites only

I'm not really good with regular expressions, so I'm hoping someone could help come up with something that would fit what I'm trying to do, which is:
I want it to match in the following cases (only for youtube links):
http://www.youtube.com/watch?v=oHg5SJYRHA0
www.youtube.com/watch?v=oHg5SJYRHA0
youtube.com/watch?v=oHg5SJYRHA0
http://youtu.be/oHg5SJYRHA0
www.youtu.be/oHg5SJYRHA0
youtu.be/oHg5SJYRHA0
also in the first three examples, it should match any domain ending, so not just .com
While I'm asking this, I will also need to be able to get the video ID alone as well.

A:

You could do the following:
function getYoutubeId(str) {
    var check;
    check = /youtu.be\/(\w+)/.exec(str);
    if(check) return check[1];
    check = /youtube\.com\/.*v=(\w+)/.exec(str);
    if(check) return check[1];
    return null;
}

getYoutubeId("http://www.youtube.com/watch?v=oHg5SJYRHA0"); // oHg5SJYRHA0
getYoutubeId("www.youtube.com/watch?v=oHg5SJYRHA0"); // oHg5SJYRHA0
getYoutubeId("youtube.com/watch?v=oHg5SJYRHA0"); // oHg5SJYRHA0
getYoutubeId("http://youtu.be/oHg5SJYRHA0"); // oHg5SJYRHA0
getYoutubeId("www.youtu.be/oHg5SJYRHA0"); // oHg5SJYRHA0
getYoutubeId("youtu.be/oHg5SJYRHA0"); // oHg5SJYRHA0

getYoutubeId(""); // null
getYoutubeId("google.com"); // null
getYoutubeId("youtu.be/"); // null
getYoutubeId("youtube.com/?other=something"); // null


Q:

Change primary key (id) of a row in a table and shift the others downwards

I have a MySQL table that looks like this:

I wanted to change such that the entry with id 15 (women, dress) now has a primary key of 8 and then the others are shifted by one, so for example Kids Tops now will be 9, etc. Is there an easy way to do this via phpmyadmin or a SQL query? Also because id 15 is already being used as a foreign key somewhere else, I wanted this change to be reflected all over the place in other tables.

A:

One should not change the primary key - ever. Moreover, it may be beneficial to think about PKs as non-numeric values. Imagine that you use autogenerated GUIDs for your primary keys.
If you want to renumber your items, then the column that you want to change should be a separate numeric column, which you treat explicitly as a sequence number of sorts. Then you can do what you want with three UPDATE statements:
update mytable set sequence = -sequence where sequence = 15 -- hide the original 15
update mytable set sequence = sequence+1 where sequence >= 8
update mytable set sequence = 8 where sequence = -15

A:

You cannot change a "primary key", and for good reason.  The primary key is likely to be used by other tables to reference a particular row.  So, a change would not be local in the table, it would have to be in every referencing table.
If you want to change the values in the column, then you have to first drop the primary key constraint.
If you really have to do such a thing, here are some considerations:

To change the value of the primary key, you have to drop the primary key constraint first.
Drop all foreign key references to the table.  Otherwise, you will either get unexpected errors or unexpected deletes when you change values (on delete cascade).
Create a mapping table that has the old value and the new value.
Update the values in the main table.
Update the "foreign key" references.
Re-apply the foreign key constraints on the remote tables
Re-apply the primary key constraint on the original table

(I must admit that I might have missed something, because this is not something that I would ever do.)
Changing a primary key, especially one used in foreign key relationships, should not be taken lightly.  The purpose of such keys is to maintain relational integrity.  You should not be bothered by gaps in the key or lack of sequentiality.  If you want a sequential number, you can add that into another column.

A:

Perhaps you should alter your child table FK with an ON UPDATE CASCADE operation so that changes on the parent table get reflected on the child table.
See the MySQL reference for FK's: http://dev.mysql.com/doc/refman/5.1/en/create-table-foreign-keys.html
Later you can execute the following:
UPDATE table SET id = -15 WHERE id = 15;
UPDATE table SET id = id + 1 WHERE id >=8;
UPDATE table SET id = 8 WHERE id = -15;


Q:

Angular ternary operator with html output

Is it possible to render the output from a ternary operator as html?
{{ boolA ? 'Some text' : '<i class=\"fa fa-check\"></i>' }}

Also tried to modify a inline if/else directive from a previous question but can't get this to work either.
.filter('iif', ['$sce', function ($sce) {
    return function (input, trueValue, falseValue) {
        return $sce.trustAs('html', input ? trueValue : falseValue);
    }
}])

A:

Yes, Use ng-bind-html like this :

Replace values according to your requirements.


Q:

creating vagrant public network on windows PC

I am trying to setup public network for the vagrant box am setting up and i use Windows 10. If i do not put the interface name, vagrant asks for the interface name and without putting what vagrant wants it won't work.
So my question is how do i get the exact interface name from my windows 10 PC to use for vagrant?
OR
How can i let vagrant asks me to choose from list of interface names it can detect?
I have searched and search for how to achieve this but just can't.
config.vm.network "public_network", bridge: "???"
Window's ipconfig doesn't help
Thanks

A:

you can use the VBoxManage tool to find out what are your interfaces.
so you can run - if VBoxManage is not in your PATH, you need to run this from your VBoxManage directory
VBoxManage.exe list bridgedifs

Name:            en0: Wi-Fi (AirPort)
GUID:            00306e65-0000-4000-8000-b8f6b1126bcf
DHCP:            Disabled
IPAddress:       192.168.1.33
NetworkMask:     255.255.255.0
IPV6Address:
IPV6NetworkMaskPrefixLength: 0
HardwareAddress: b8:f6:b1:12:6b:cf
MediumType:      Ethernet
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-en0

Name:            en1: 1 Thunderbolt
GUID:            00316e65-0000-4000-8000-3200139bff20
DHCP:            Disabled
IPAddress:       0.0.0.0
NetworkMask:     0.0.0.0
IPV6Address:
IPV6NetworkMaskPrefixLength: 0
HardwareAddress: 32:00:13:9b:ff:20
MediumType:      Ethernet
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-en1

Name:            en2: 2 Thunderbolt
GUID:            00326e65-0000-4000-8000-3200139bff21
DHCP:            Disabled
IPAddress:       0.0.0.0
NetworkMask:     0.0.0.0
IPV6Address:
IPV6NetworkMaskPrefixLength: 0
HardwareAddress: 32:00:13:9b:ff:21
MediumType:      Ethernet
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-en2

etc etc

if you have cygwin or something you can even run VBoxManage list bridgedifs | grep -e "^Name:*" and you'll get the exact name to use in your Vagrantfile.
on windows box with VirtualBox 5.0.6 running
C:\Program Files\Oracle\VirtualBox>vboxmanage list
Oracle VM VirtualBox Command Line Management Interface Version 5.0.6
(C) 2005-2015 Oracle Corporation
All rights reserved.

Usage:

VBoxManage list [--long|-l] vms|runningvms|ostypes|hostdvds|hostfloppies|
                            intnets|bridgedifs|hostonlyifs|natnets|dhcpservers|
                            hostinfo|hostcpuids|hddbackends|hdds|dvds|floppies|
                            usbhost|usbfilters|systemproperties|extpacks|
                            groups|webcams|screenshotformats

C:\Program Files\Oracle\VirtualBox>vboxmanage list bridgedifs
Name:            Intel(R) PRO/1000 MT Network Connection
GUID:            754f0866-bd85-43bc-b403-3c85945b3226
DHCP:            Enabled
IPAddress:       172.16.42.165
NetworkMask:     255.255.255.0
IPV6Address:     fe80:0000:0000:0000:64b8:b1cf:962f:7aa1
IPV6NetworkMaskPrefixLength: 64
HardwareAddress: 00:0c:29:64:09:f3
MediumType:      Ethernet
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-Intel(R) PRO/1000 MT Network Connection

Name:            Juniper Network Connect Virtual Adapter
GUID:            ed9c3519-e796-42ce-b782-14ec6819b743
DHCP:            Enabled
IPAddress:       169.254.251.149
NetworkMask:     15.0.0.0
IPV6Address:     fe80:0000:0000:0000:5525:2e65:10a8:fb95
IPV6NetworkMaskPrefixLength: 64
HardwareAddress: 00:ff:10:e0:06:1a
MediumType:      Ethernet
Status:          Down
VBoxNetworkName: HostInterfaceNetworking-Juniper Network Connect Virtual Adapter


Q:

Computing taylor series of multivariate function with sympy

I am trying to compute with SymPy the taylor series of a function which depends on the trigonomertic function sinc  (here), to simplify my problem, we can assume the function I need the Taylor series of is :
f(x1, x2) = sinc(x1) * sinc(x2)

My problem is that when importing sympy.mpmath I often get the error :

cannot create mpf from ...

I have tried to use the taylor-series approximation or this other solution (number 1.), but they all seem to fail. For example for the later alternative the line :
(sinc(x)*sinc(y)).series(x,0,3).removeO().series(y,0,3).removeO()

returns :

cannot create mpf from x

I also have tried of defining the function as an expression and as a lambda function. But nothing seems to work.
Any help will be much appreciated.

A:

You can't use mpmath functions with symbolic SymPy objects. You need to define sinc symbolically.
One way is to just define it as a Python function that returns the equivalent (here sin is sympy.sin):
def sinc(x):
    return sin(x)/x

Or, you could write your own SymPy class for it.
class sinc(Function):
    @classmethod
    def eval(cls, x):
        if x == 0:
            return 1
        # Should also include oo and -oo here
        sx = sin(x)
        # Return only if sin simplifies
        if not isinstance(sx, sin):
            return sx/x

    # You'd also need to define fdiff or _eval_derivative here so that it knows what the derivative is

The latter lets you write sinc(x) and it will be printed like that, and you can also define custom behavior with it like what the derivative looks like, how the series works, and so on. This would also let you define the correct values at 0, oo, and so on.
But for the purposes of taking series, just using sin(x)/x (i.e., the first solution) works fine, because your final answer won't have sinc in it anyway, and the series methods take the limit correctly when evaluating at points like 0.


Q:

Fragments Failed to inflate

I'm a little shakey on this so bear with me.  I'm trying to teach myself and I'm currently working out of the WROX Android 4 Application Development for Beginners book. I'm currently on the section "Communication between fragments" and I feel like I'm getting it, but when I run the code taken right out of the book, I get "failed to inflate" in the logcat.  Here's the XMLs followed by the .java files, then the error.  I can't figure out what's killing this:
main.xml:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    >
    <fragment
        android:name="com.example.Fragments.Fragment1"
        android:id="@+id/fragment1"
        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent"
        />
    <fragment
        android:name="com.example.Fragments.Fragment2"
        android:id="@+id/fragment2"
        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent"
        />
</LinearLayout>

fragment1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00FF00"
    >
    <TextView
        android:id="@+id/lblFragment1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is fragment #1"
        android:textColor="#000000"
        android:textSize="25sp"
        />
</LinearLayout>

fragment2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFE00"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is fragment #2"
        android:textColor="#000000"
        android:textSize="25sp"
        />
    <Button
        android:id="@+id/btnGetText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get text in Fragment #1"
        android:textColor="#000000"
        android:onClick="onClick"
        />
</LinearLayout>

FragmentsActivity.java:
package com.example.fragments;

import android.app.Activity;
import android.os.Bundle;

public class FragmentsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Fragment1.java:
package com.example.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // ---Inflate the layout for this fragment---
        return inflater.inflate(R.layout.fragment1, container, false);
    }

}

Fragment2.java:
package com.example.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Fragment2 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        //---Inflate the layout for this fragment---
        return inflater.inflate(
                R.layout.fragment2, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        //---Button View---
        Button btnGetText = (Button)
                getActivity().findViewById(R.id.btnGetText);
        btnGetText.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                TextView lbl = (TextView)
                        getActivity().findViewById(R.id.lblFragment1);
                Toast.makeText(getActivity(), lbl.getText(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

logcat:
04-20 15:09:55.759: E/ActivityThread(9523): Failed to inflate
04-20 15:09:55.759: E/ActivityThread(9523): android.view.InflateException: Binary XML file line #7: Error inflating class fragment
04-20 15:09:55.759: E/ActivityThread(9523):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
04-20 15:09:55.759: E/ActivityThread(9523):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:282)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.Activity.setContentView(Activity.java:1881)
04-20 15:09:55.759: E/ActivityThread(9523):     at com.example.fragments.FragmentsActivity.onCreate(FragmentsActivity.java:15)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.Activity.performCreate(Activity.java:5104)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2260)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2356)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.ActivityThread.access$600(ActivityThread.java:150)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.os.Looper.loop(Looper.java:137)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.ActivityThread.main(ActivityThread.java:5195)
04-20 15:09:55.759: E/ActivityThread(9523):     at java.lang.reflect.Method.invokeNative(Native Method)
04-20 15:09:55.759: E/ActivityThread(9523):     at java.lang.reflect.Method.invoke(Method.java:511)
04-20 15:09:55.759: E/ActivityThread(9523):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
04-20 15:09:55.759: E/ActivityThread(9523):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
04-20 15:09:55.759: E/ActivityThread(9523):     at dalvik.system.NativeStart.main(Native Method)
04-20 15:09:55.759: E/ActivityThread(9523): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.Fragments.Fragment1: make sure class name exists, is public, and has an empty constructor that is public
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.Fragment.instantiate(Fragment.java:592)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.Fragment.instantiate(Fragment.java:560)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.Activity.onCreateView(Activity.java:4709)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
04-20 15:09:55.759: E/ActivityThread(9523):     ... 21 more
04-20 15:09:55.759: E/ActivityThread(9523): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.Fragments.Fragment1" on path: /data/app/com.example.fragments-2.apk
04-20 15:09:55.759: E/ActivityThread(9523):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
04-20 15:09:55.759: E/ActivityThread(9523):     at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
04-20 15:09:55.759: E/ActivityThread(9523):     at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
04-20 15:09:55.759: E/ActivityThread(9523):     at android.app.Fragment.instantiate(Fragment.java:582)
04-20 15:09:55.759: E/ActivityThread(9523):     ... 24 more

A:

the Layout definition is wrong android:name="com.example.Fragments.Fragment1". It should be
android:name="com.example.fragments.Fragment1"

the same for Fragment2


Q:

Get Locale Date Format Information

Using Swift 4, is there a way to get a string representation of a locale's date format?  Based on an iPhone's locale settings, I would like to find out if the format is yyyy/mm/dd or mm/dd/yyyy.
I've found all of the ways for changing a date format or getting the date from the locale's format but have not been able to work out how to get the actual format.

A:

Use DateFormatter dateFormat(fromTemplate:options:locale:).
let userFormat = DateFormatter.dateFormat(fromTemplate: "yyyyMMdd", options: 0, locale: Locale.current)

In the US this returns MM/dd/yyyy. In Germany this gives dd.MM.yyyy.
If you ever need to get the appropriate time format which also takes into account the user's chosen 12/24-hour time format, use a template of jms. The j is a special format specifier, only used with templates, that returns either h or H for the hour depending on what's appropriate.

Another possible option is to create a DateFormatter, set the desired dateStyle and timeStyle, then read the dateFormat property:
var mydf = DateFormatter()
mydf.dateStyle = .long // set as desired
mydf.timeStyle = .full // set as desired
print(mydf.dateFormat)

For the US this gives:

MMMM d, y 'at' h:mm:ss a zzzz

For Germany this gives:

d. MMMM y 'um' HH:mm:ss zzzz


Q:

C# How to save image from an OLE Object stored in a Database

It seems that header bytes are stored along with an image when it is embedded into an access database as a OLE Object and they are preventing me from writing the bytes stored to disc as it raises an exception 'A generic error occurred in GDI+.'
How do you extract only the image bytes from a OLE Object stored in an access database and then save to disk?
photo = ((rs.Fields["photo"].Value == System.DBNull.Value) ?
    null : (byte[])rs.Fields["photo"].Value)

...

if (photo != null)
{
    MemoryStream stream = new MemoryStream(photo);
    Image image = new Bitmap(stream);
    stream.Close();

    image.Save(@"C:\Temp\images\test", ImageFormat.Jpeg);
 }

A:

using (MemoryStream stream = new MemoryStream(photo))
using (Image image = Image.FromStream(stream))
{
    image.Save(@"C:\Temp\images\test.jpg", ImageFormat.Jpeg);
}


Q:

is there a way i can use Asterix(*) in tesseract?

am trying to extract to use all my box file to extract characters and when i try this line
unicharset_extractor *.box

it gives me an error that it cannot find *.box instead of loading all box files.

A:

I finally made my own tool for that .
[link]http://code.google.com/p/serak-tesseract-trainer/


Q:

Why does exporting withAlert(Alerts) causes error but withAlert()(Alerts) works?

In Brad's tutorial the Alerts component is exported using:
export default withAlert(Alerts)

This was causes the errors:
The above error occurred in one of your React components:
    in Unknown (created by App)
    in Provider (created by App)
    in Provider (created by App)
    in App

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb me/react-error-boundaries to learn more about error boundaries. react-dom.development.js:21810:13
Error: Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead.
    in Unknown (created by App)
    in Provider (created by App)
    in Provider (created by App)
    in App 2 main.js line 753 > eval:14729:15

After reading react-alerts documentation the export was changed to the below and it works:
export default withAlert()(Alerts)

In essence:

Was this change correct?
What did that change do?
Why was it necessary?

A:

Yes. It's correct.
Since the api of react-alerts change, you should update the code. The changing information is described in this link https://github.com/schiehll/react-alert/commit/9decd399fccc42c623bfdd44cd6fc381d75c3116
to follow the published api, since you used their code :). I guess they added some arguments inside the bracket to customize the alert. But the important is the guide in youtube used the older version than current.


Q:

How to traverse PHP Array from HTML TextArea Input?

Whenever I receive input such as from a HTML Textarea box:
 joeschmo@gmail.com:25wfsfrs
 johnbrown@yahoo.com:324dasd
 janedoe@yahoo.com:3dsadasd

I want to use the PHP function explode() on the colon and print out a list such as:
Usernames:
1st Email
2nd Email
3rd Email

Passwords:
1st Pass
2nd pass
3rd Pass

Code so far:
<html>
<head>
<title>
Usernames AND Passwords!
</title>
</head>
<body>

<?php
/*Print contents of textarea for testing purposes.*/

$data = explode("\n", $_POST['uandp']);
foreach($data as $value){
    echo $value;
}

/*Split username and password*/
$string = $_POST['uandp'];
list($string1,$string2) = explode(":",$string);
/*$string1 = username, $string2 = password*/
$new_string = $string1;
$new_string2 = $string2;
/*$new_string = Username*/
/*$new_string = Password*/

echo $new_string;
echo $new_string2;
?>
</body>
</html>

Not sure where to go from here. I know I have to store the textarea form data into an array and parse it from there.

A:

$uAndPs = array();

foreach (explode("\n", $_POST['uandp']) as $value){
    list($username, $password) = explode(':', $value);
    $uAndPs[$username] = $password;
}

echo "Usernames:\n"
echo join("\n", array_keys($uAndPs));

echo "Passwords:\n"
echo join("\n", $uAndPs);


Q:

Azure WebApp FTP not updating

I've published a web app through FTP in Azure WebApps and it worked fine, but now when I open the FTP client in Windows Explorer and replace the index.html file and restart the web app, my changes are not reflected and the former version of index.html is still the one being presented.
Does Azure WebApp have a delay to reflect changes in wwwroot?
There is just one index.html file in wwwroot and it is also the first item in the Default Documents list in the Configure Tab.

A:

I've used web apps for some time now and never had the issue you are experiencing. Perhaps the best thing to do is intentionally break the site by removing the index.html file altogether, restart the site then navigate to it. Obviously it will fail (Well it should fail!). Then try uploading the new index.html file, restart the site and see what you get.


Q:

XHTML and code inside textareas

On a site of mine in which a textarea is used for submission, I have code that can appear something along the lines of the following:
<textarea>
text
</textarea>

When validating (XHTML 1.0 Transitional), this error arises,
line 88 column 50 - Error: document type does not allow element "p" here

If this is not a valid method, then what is expected?  I could do a workaround with an onload JavaScript event, but that seems needless.  Regardless this doesn't affect the output, but I'd rather my site validate.

A:

is there a reason you're trying to put a
 within <textarea>? as you found out it's not valid. if it's for display purposes (ie, showing code) it should be translated:
<textarea><p>text</p></textarea>

beyond validation issues, allowing arbitrary tags (which are not properly encoded as above) to display can be a huge security issue. it's paramount to make sure any user supplied input has been properly sanitized before it is displayed.

A:

Would a CDATA section be an option for you?
<textarea><![CDATA[

Blah

]]></textarea>


Q:

How to use an IP address to send mail usind sendmail

I am doing some testing with sendmail on my linux mail server.
I currently have 2 user accounts (excluding root) on the one server and wish to send emails from one to the other using the server IP address instead of localhost.
e.g.
[mary@mailserver]$ mail -s "Hello World" john@192.168.0.1

But when ever I try this I get a dead.letter reply, effectively saying the mail could not be delivered.
I tryed changing a few setting in sendmail.mc (sorry can't remember which ones), rebuild it and restarted the sendmail service. I also added the server IP address to the sendmail db, rebuilt it and restarted the sendmail service. Neither of which seemed to help.
I'm very unfamiliar with sendmail so any help would be great.
Thanks.

A:

IP adresses are not allowed by the RFC specification.


Q:

Python direct path file printing issue?

So I have a script that needs to print to a file in a different directory. I give that absolute path and python doesn't like it.
Here's where the file is located:
C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt
(I know, long path, but QT plotter makes the file names really long)
I typed:
textfile = open('C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt', 'w')

And I get this error:
IOError: [Errno 22] invalid mode ('w') or filename:

I've read that I can use relative paths, but I am unsure how to give it a relative path with so many directories to go through.
Thanks!

A:

The problem is that python is interpreting the backslashes in your path as escape sequences:
>>> 'C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'
'C:\\Users\\Owner\\Documents\\Senior_design\\QT_Library\x08uild-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'

Notice that both \b and \n get translated to something else.  Use a "raw" string instead:
>>> r'C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'
'C:\\Users\\Owner\\Documents\\Senior_design\\QT_Library\\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\\numbers.txt'


Q:

C - strcpy with malloc size less than argument's size

char* init_array()
{
    const int size = 5;
    char *p = (char*) malloc(size * sizeof(char));
    strcpy(p, "Hello, world! How are you?");

    return p;
}

with size = 5, malloc should get 5 free chars from memory, but given string does not fit into 5 chars, yet it works.
My question is why? First I thought the result would get truncated but p is the fully string, not just "Hello" or "Hell\0"
I'm using GCC on Linux. Is it related to the compiler or it is standard stuff?

A:

It's called undefined behavior, since it's undefined sometimes it works. Yes you can write past a memory block in c, but that's illegal because it invokes undefined behavior, the behavior is therefore not predictable and your program might or might not work.
What you expect from strcpy() doesn't happen because strcpy() copies as many characters as it finds before the '\0' terminating byte, it doesn't care if the destination buffer is large enough, that's something you must be responsible about.
If you want to copy an exact number of bytes (let's say 5) you can use
memcpy(p, "Hello, this string is very large but it doesn't matter", 5);

but beware that p is not a valid string after that, because it has no terminating '\0'.
You also have 2 other common bad practice that new c programmers do

You don't need to cast the return value from malloc().
You don't need to use sizeof(char) because it's 1 by definition.

So,
p = malloc(size);

should be enough to allocate space for a size - 1 characters string.


Q:

Find out if my dongle is AP capable

I'd like to turn my Raspberry PI into an access point.
I've read that my wifi dongle has to have an AP mode (here's my dongle:
https://www.modmypi.com/raspberry-pi-accessories/wireless-usb-1n-nano-adaptor-802.11N-wifi-dongle) and that typing from the console:
iw list

I should get the information but all I get is:
nl80211 not found
What can I do to fix this?

A:

By the picture, you have the same wifi dongle as I do.
Check this site. It is written to hostap, but i think will lead you to the right answer.
But in resume, the realtek has it own modules. You need to download it and install by hand.
I used it for hostap and it work, but i still don't have the iw command.


Q:

Mythologies with goddesses as the main deity?

In most mythologies, there is often a male god who is the chief god, like Zeus of Greek mythology and Ra of Egyptian mythology. As far as I know, the only mythology that has a female ruler of the universe is Ameteratsu, the Sun goddess of the Shinto pantheon/Japanese mythology. Are there any other mythologies that have goddesses as the main deity as well?

A:

Yes
I take this question to refer to the chief deity of the “day to day” pantheon. Many religions have primordial goddesses that are arguably older and more powerful than the deities that are the object of day-to-day worship, but were supplanted (like Gaea) or are rarely referenced (such as Nyx).1
Likely reflecting the male-dominated outlook of many cultures, most such chief deities are male. However, some are female. Besides your example of Ameteratsu, I can think of a few others:

In Odinani religion, the primary deity is Ala. The true supreme deity is Chinukwu, who generally seems to be genderless, but is not worshipped:

Chukwu is genderless and is reached through various spiritual
  forces mainly under the spirit class of Alusi who are incarnations of
  the high god; no sacrifices, however, are given to Chukwu and no
  shrines and altars are erected for him.

Ala is female, and chief of the gods who are actually worshipped:

Ala (meaning ‘earth’ and ‘land’ in Igbo, also Ájá-ànà) is the
  feminine earth spirit who is responsible for morality, fertility and
  the dead ancestors who are stored in the underworld in her womb. Ala
  is at the head of the Igbo pantheon, maintaining order and carrying
  out justice against wrongdoers. Ala is the most prominent and
  worshipped alusi, almost every Igbo village has a shrine dedicated
  to her called íhú Ala where major decisions are taken. Ala is
  believed to be involved in all aspects of human affairs including
  festivals and at offerings.

In fact, the very name Odinani appears to contain a derivative of “Ala.”
In Winti, Aisa is another supreme earth goddess:

Aisa(eye sah), mother god of the earth,  is the highest and is
  considered closest to Anana. Which is why at most Winti rituals or
  payers begin with an offering or odo(oh doh) to Aisa, hoping that she
  will intervene on your behalf regarding many issues, such as healing,
  protection, or general blessing.

There is also a supreme deity, who may be male or genderless, but (as with Ala) Aisa is the chief divinity of the pantheon.

1: That Nyx was of comparable power to Zeus, or greater than him, seems quite likely. In the Iliad, Hypnos makes reference to a previous instance in which he had aroused the wrath of Zeus, and fled to Nyx for shelter: “To her I came in my flight, and besought her, and Zeus refrained him, albeit he was wroth, for he had awe lest he do aught displeasing to swift Night.” She is also referred to as “Night that bends to her sway both gods and men.”

A:

I'd offer that the ancient Celtic Gods of the Tuatha dé Danaan were another.  From the wiki page:

"In Irish-Celtic mythology, the Tuatha Dé Danann ("People of the goddess Danu") are the Irish race of gods, founded by the goddess Danu. These gods, who originally lived on 'the islands in the west', had perfected the use of magic."


Q:

How to require a plugin in a phonegap app

I'm trying to make this example of phonegap barcode scanner plugin work. I've replaces all files in www folder, and also I've installed the plugin using CLI command
phonegap plugin add phonegap-plugin-barcodescanner

but pressing scan button, only the console.log('scanning') command in line 55 of index.js works. my questions are:

Does cordova in requirement in line 57 of index.js point to root of project (cause I don't have such a folder)?
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
Does barcodescanner.js file ship automatically (cause it's not it the example repo, and I can see it in plugins directory)?
After installation by CLI, the line
<gap:plugin name="com.phonegap.plugins.barcodescanner"/>

was not in config.xml. Do I need to add it manually?

A:

I don't know if this example works correctly cause all files of a complete project are not supplied in repository. I prefer to give a more detail, to cover the issue completely.
Let's check a few points you need to take care of for installing plugins:

Add platforms before installing plugin
Installing plugins using CLI is proffered
Plugins usually only work on real device as installed app, not on you browser nor in Phonegap scanner.
You don't need to add any line of code to config.xml and cordova will do it to the config inside platforms/{os} folder (The 3rd question).

Some plugins don't need any further manual file transfers of and kind of linking scripts to HTML pages, but some need. the barcodeScanner is one of those needing to:

Do not link barcodescanner.js to the index.html file Cordova will do it automatically (The 1st question).

Every plugin has a plugin.xml file. looking through it, there is js-module element which has at least one clobbers element. this element has a target attribute which indicated the global module that will be available globally. in this case, check if cordova.plugins.barcodeScanner is available by generating a debug apk or api file.

Normally you do not need to make requirements in your own code, because the build process will wrap the plugin in a cordova.require closure. about this plugin, simply use:
cordova.plugins.barcodeScanner.scan(function (result) {}, function (error) {});


Q:

How do I make a free city as the HRE in EU4?

I'm starting as Austria in EU4.  Where is the button (diplomacy option) that lets me make Friesland a free city in the Empire?  Where can I find which HRE members are already free cities?

A:

Edit: As mentioned in the comments, the Common Sense DLC is required to have these options.
The diplomacy option to create a Free City is under the Emperor Actions tab. Nations are only eligible to become a Free City if:

there are less than 8 Free Cities in the Empire
they have a single province, with at least 10 total development. If a Free City takes a second province, it loses its status.
they are a member of the Holy Roman Empire.
they are not a subject nation
they are not an Elector.
they are at peace.

You can view existing Free Cities using the Imperial Map Mode, where they show up blue. Members show up as green, electors as orange and the Emperor as purple. Provinces owned by non-members are hashed yellow.


Q:

Remove a word starting with x in a sentence

How to remove a word in java which is starting with the "http" in a sentence?
Input: Mag 4 earthquake in Liechtenstein. Buildings from Middle Ages said to do better in quakes than their modern friends. http://t.c\u2026;
Output: Mag 4 earthquake in Liechtenstein. Buildings from Middle Ages said to do better in quakes than their modern friends.

A:

i'm not sure of the code i write but you can find something like this:
String data="blah blah blah";
int index = data.indexOf("http");

String subString = str.substring(index, data.length()-1);


Q:

/var/www Directory not found

I do not have a /var/www directory in my ubuntu.
Isn't it a default directory which comes with os installation.
I am sorry if the question is silly or has already been asked. I ended up asking here after not getting any solution elsewhere.

A:

Shravya,
www directory is the web root for applications, you need to **install apache** on your ubuntu in order to get the www directory.
it in not there by default.


Q:

Combining string with text in telnetlib write command doesn't work if string has spaces in

I'm using the telnetlib to read a text file from a webserver and push out the lines to an LCDProc server rotating them every few seconds. Everything so far works ok unless there is a space in the imported line.  I've read the python documentation and searched but I'm not finding anything that helps, I'm very new to Python which doesn't help.
The 'widget_set G 1 1 1' specifies where the following text should go, after that I add in what I want to display, this works ok but I don't understand it.  The %s appears to insert a space which I am guessing is a command native to the LCDproc server not Python? '\n' is a new line? I don't see why I need one on a single line of the display.  However, the time is formatted with spaces in and this displays correctly:
tn.write("widget_set G 1 1 1 \" %s \"\n" % (cur))

The problem is on the second line of the display, I've tried various combinations of \" and " with mixed results but I can't get it to display lines with spaces in (they just come up blank) and sometimes it misses off the last line. What should I write here to make it send the 'line' string?  I did have it working at one point using '\"' somewhere but then changed some of the code and now can't get it to work again?
tn.write("widget_set G 2 1 2 " + line)

With enough patience I can normally Google until I find an answer but I'm pulling my hair out here!
If it has any bearing I removed the following line after every tn.write line because it appeared to be filling the data variable up with endless lines of data that wasn't being used for anything:
data += tn.read_until("\n");

Full code for reference:
#!/usr/bin/python

import telnetlib;
import time;
import urllib2;

host='127.0.0.1';
port='13666';

tn = telnetlib.Telnet(host, port)
tn.write("hello\r");

tn.write("screen_add G\n");

tn.write("widget_add G 1 string\n");

tn.write("widget_add G 2 string\n");

var = 1;
while var == 1 :

    file = urllib2.urlopen("http://192.168.100.17/test.txt")
    for line in file.readlines():
            time.ctime()
            cur = time.strftime('%l:%M:%S %p')
            tn.write("widget_set G 1 1 1 \" %s \"\n" % (cur))
            tn.write("widget_set G 2 1 2 " + line)
            time.sleep(1)

A:

So, you are saying that this line works correctly:
       tn.write("widget_set G 1 1 1 \" %s \"\n" % (cur))

And this line fails?
        tn.write("widget_set G 2 1 2 " + line)

So, do what the first line does. Try this:
        tn.write("widget_set G 2 1 2 \" %s \"\n" % (line))

If it is easier to read, the following line is equivalent. (Note how the stirng uses ' instead of ", so the interior "s don't have to be escaped):
        tn.write('widget_set G 2 1 2 " %s "\n' %(line))

Note that this will probably still fail if either cur or line have a quote character " embedded therein.


Q:

Undefined reference to class, common answers haven't resolved

I'm sure this is a common question, and I've been looking through similar questions; but i'm unable to get this resolved
C++11, CLion IDE
Error as follows:
undefined reference to `aBag::aBag()'

main.cpp is simple and has no logic as of yet
#include <iostream>
#include "aBag.h"
using namespace std;

int main() {

    aBag setA;

    return 0;
}

the following is header aBag.h, which i'm unable to edit
#ifndef BAG_
#define BAG_

#include <vector>

typedef int ItemType;
class aBag
{
private:
    static const int DEFAULT_BAG_SIZE = 100;
    ItemType items[DEFAULT_BAG_SIZE]; // array of bag items
   int itemCount;                    // current count of bag items
   int maxItems;                     // max capacity of the bag

   // Returns either the index of the element in the array items that
   // contains the given target or -1, if the array does not contain
   // the target.
   int getIndexOf(const ItemType& target) const;

public:
    aBag();
    int getCurrentSize() const;
    bool isEmpty() const;
    bool add(const ItemType& newEntry);
    bool remove(const ItemType& anEntry);
    void clear();
    bool contains(const ItemType& anEntry) const;
    int getFrequencyOf(const ItemType& anEntry) const;
};  // end Bag

#endif

constructor for aBag
#include "aBag.h"

aBag::aBag() : itemCount(0), maxItems(DEFAULT_BAG_SIZE)
{
}

cmakefile.txt
cmake_minimum_required(VERSION 3.12)
project(project2)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp  aBag.cpp)

add_executable(project2 main.cpp)

output for make V=1
$make V=1
g++ -c -g -std=c++11  main.cpp
g++ -c -g -std=c++11  aBag.cpp
g++ -o project2 main.o aBag.o

is it syntax somewhere? do i need to be adding aBag.cpp or .h as a source file or target somewhere? something else entirely?
send help

A:

It's your CmakeLists file, it doesn't add aBag.cpp to the executable sources:
cmake_minimum_required(VERSION 3.12)
project(project2)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp  aBag.cpp)

# this is the correct way to use SOURCE_FILES list
add_executable(project2 ${SOURCE_FILES})


Q:

Install PHP cURL on Amazon EC2 Micro Instance

I need to install PHP cURL on my Amazon EC2 Micro Instance.
I found a terminal code which should install PHP cURL through PuTTY.
sudo apt-get install php5-curl

But I get a lot of 403 Forbidden errors.
I'm not good with Linux so I didn't really understand what those errors mean.
This is a screenshot of all the errors.

A:

Please try installing PHP curl with below command (Ubuntu)
sudo apt-get install php-curl

For Amazon Linux
sudo yum install php-curl

A:

the 403 is from the source repository,
Try
sudo-apt-get update

before the install.  If that still doesn't fix it, add these lines to the /etc/apt/sources.list
deb http://us.archive.ubuntu.com/ubuntu lucid main multiverse universe
deb http://us.archive.ubuntu.com/ubuntu lucid-security main multiverse universe
deb http://us.archive.ubuntu.com/ubuntu lucid-updates main multiverse universe


Q:

How do I signup users using PFObject instead of PFUsers()

I have created a PFObject called UserDataTable which stores information like username, password, Name, emailID, age, city, state, etc. of the user.
I am not sure how to authenticate the user to server using PFObject but can do so using PFUsers(). I know that PFUsers is a sub-class of PFObject so there must be a way to access those properties using my PFObject.
Can anyone help me out with the same. I am using SWIFT for coding.
let UserDataBase = PFObject(className: "UserDataBase")
UserDataBase["userId"] = "aamirdbx"
UserDataBase["userName"] = "Aamir Bilal"
UserDataBase["userPassword"] = "pass"
UserDataBase["userEmailId"] = "aamirdbx@gmail.com"

I would like to Sign In using information in this UserDataBase which is a PFObject.
I know how we can do the same using PFUser() but I want to avoid using a bunch of different Objects.

A:

You should be using PFUser for this no matter what. PFUser already has all the built in authentication protocols, session tokens, security and ACL built in for you, which as someone who is just getting started is not something you want to try and manage yourself. You can add extra information to your Parse User class if you need to store additional information, or you can create another table, and have a pointer in your user class to the data in the other table, but for your sake and your user's sake, please don't try to handle this yourself.


Q:

EventKit in Universal app (OS3.2)

I made iPhone app with eventkit framework. However, i upgrade to universal app, app can't run in ipad. I got error message
dyld: Library not loaded: /System/Library/Frameworks/EventKit.framework/EventKit

Yes, event kit only work for iOS 4.0 or later. So, how to make it for universal.
I want to make , if iPad app, don't use event kit framework.
However, I can't add
#import <EventKit/EventKit.h>
#import <EventKitUI/EventKitUI.h>

in run time

A:

You need to do two things:

First, weak link against the EventKit framework. You do this in Target->Get Info->General.
Secondly, you need to decide at run time whether or not certain functionality is available:
Class someClass = NSClassFromString(@"SomeClass");
if(someClass) {
  // iOS4 code
}
else {
  // iOS3.2 code
}


Q:

Extend div to bottom of page (only HTML and CSS)

Its a very simple problem but I can't seem to find a suitable solution online. I want to have a list of elements in natural flow with the last element extended to the bottom of the page. So if I have

I need element bottom to extend from the bottom of top to the bottom of the page. Any solution that uses only html and css is welcome, and you can add container divs or anything, as long as I can get dynamic resizing of the bottom div
EDIT:
I don't want to hard-code any values for bottom, because I want bottom to adjust if top is resized
here's a fiddle for all your fiddling needs: http://jsfiddle.net/8QnLA/

A:

Solution: #1: css tables:
html, body {
  height: 100%;
  width: 100%;
}
body {
  display: table;
  margin: 0;
}
#top, #bottom {
  width: 100%;
  background: yellow;
  display: table-row;
}
#top {
  height: 50px;
}
#bottom {
  background: lightgrey;
  height: 100%;
}

html, body {
  height: 100%;
  width: 100%;
}
body {
  display: table;
  margin: 0;
}
#top, #bottom {
  width: 100%;
  background: yellow;
  display: table-row;
}
#top {
  height: 50px;
}
#bottom {
  background: lightgrey;
  height: 100%;
}

A header

The content area - extends to the bottom of the page

Codepen #1 (little content)
Codepen #2 (lots of content)
Solution #2: Using calc and viewport units
#top {
  height: 50px;
  background: yellow;
}
#bottom {
  background: lightgrey;
  min-height: calc(100vh - 50px);
}

body {
  margin: 0;
}
#top {
  height: 50px;
  background: yellow;
}
#bottom {
  background: lightgrey;
  min-height: calc(100vh - 50px);
}

Where `min-height: calc(100vh - 50px);` means:

'Let the height of the content div be **at least** 100% of the viewport height minus the 50px height of the header.'

A header

The content area - extends to the bottom of the page

Codepen #1 (little content)
Codepen #2 (lots of content)
Solution #3 - Flexbox
body {
  margin: 0;
  min-height: 100vh;
}
body {
  display: flex;
  flex-direction: column;
}
#top {
  height: 50px;
  background: yellow;
}
#bottom {
  background: lightgrey;
  flex: 1;
}

body {
  margin: 0;
  min-height: 100vh;
}
body {
  display: flex;
  flex-direction: column;
}
#top {
  height: 50px;
  background: yellow;
}
#bottom {
  background: lightgrey;
  flex: 1;
}

A header

The content area - extends to the bottom of the page

Codepen #1 - little content
Codepen #2 - lots of content

A:

Set the height of html, body to 100%.  Then, you can set the last
's height to 100% and it will be as tall as the window.  Since you probably don't want scrolling, you can set overflow: hidden on the html, body as well.
http://jsfiddle.net/GKbzx/


Q:

Set Button title in two different colors in iOS

I want to set title on Button in two colors.
Is it possible same as given image below ?

Any help will be appreciated.
Thanks in advance.

A:

This is what you need
  UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
  btn.frame = CGRectMake(5,10,300,20);
  [self.view addSubview:btn];

  NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"100 Photos"]];
  [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 3)];
  [btn setAttributedTitle:attrStr forState:UIControlStateNormal];

A:

In storyBoard : Follow the ScreenShot.

For Programmatically : There are already many answers posts over here for attributed text and If you want to put BackgroundImage for UIButton Set a button background image iPhone programmatically

A:

For swift 3:
let button = UIButton()
let mainTitle = "200"
let subtitle = "Members"

let attrText1 = NSMutableAttributedString(string: mainTitle)
attrText1.addAttribute(NSFontAttributeName, value: 15, range: NSMakeRange(0, attrText1.length))
attrText1.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: NSMakeRange(0, attrText1.length))

let attrText2 = NSMutableAttributedString(string: subtitle)
attrText2.addAttribute(NSFontAttributeName, value: 15, range: NSMakeRange(0, attrText2.length))
attrText2.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellow, range: NSMakeRange(0, attrText2.length))

let attributedText = NSMutableAttributedString()
attributedText.append(attrText1)
attributedText.append(attrText2)

//Center align
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center

attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0,attributedText.length))

button.setAttributedTitle(attributedText, for: .normal)


Q:

Battery drain when car is inactive

My 1990 Vanagon camper has an after market Kenwood radio NOT wired through the ignition circuit but instead wired directly to an auxiliary battery which also powers other domestic camping stuff like the sink water pump, reading lights, etc. This battery is charged by the alternator but we rarely use this vehicle unless we are on a camping trip so it remains inactive for long periods of time, during which I loose the charge on the battery because of the draw from the radio even when the radio is off.
So my question is this, if I change the set up so the radio is wired through the ignition system will there be significantly less drain on the battery when the van experiences long periods of inactivity than I experience now by just turning off the radio?
Thanks for your thoughts.
Dave.

A:

The battery will loose charge even if it has no loads connected. This happens due to the nature of the chemistry of lead acid type batteries. A fully charged battery will fully discharge in a few months. The older it is the faster it happens. Significant damage happens to a battery that is discharged while a charged battery has much less damage.
The optimum solution to batteries that are not used is to connect a battery maintainer and leave it connected whenever the battery in not in use for more that couple of weeks. These are available for less than half the price of a new battery.
When this solution is used it will not matter if the keep alive memory loads are left connected.


Q:

I attach, I am attaching, or I have attached

So I got into this discussion with my German colleague about what's the proper way to write a particular sentence in an internal work email. I would really appreciate it if you could explain why any particular approach is correct or incorrect.
Her email had two attachments. One with and one without mark-ups.
What she had initially written:

I attach a clean version and a mark-up of the document

What I thought was correct

I've attached a clean and a marked-up version of the document

What I also thought was correct

I'm attaching a clean and a marked-up version of the document

What she finally wrote

I've attached a clean version and a mark-up of the document

Here are my questions:

Which of these sentences are correct?
What's the appropriate tense when it comes to attachments? Attach/Attached/Attaching
Is "mark-up of the document" correct or is "marked-up version of the document" correct?
Can you please explain why?

A:

"I attach" seems an awkward construction. Many people (especially Indians) use "I am attaching" but I think the best option is "I have attached" because you have already attached it!  Both 'mark-up' and 'marked up version' mean the same though mark-up is simpler and 'marked up version' is more formal. In any case, even work related emails offer great flexibility of language, and the main intention is to make yourself understood clearly!


Q:

What is wrong with my trivial solution to finding a cubic polynomial with roots $\cos{2\pi/7}$, $\cos{4\pi/7}$, $\cos{6\pi/7}$?

I came across a problem in a book recently that asked to find a cubic polynomial with roots $\cos{2\pi/7}, \cos{4\pi/7}, \cos{6\pi/7}$. There were no extra conditions on the problem. It just asks you to find a cubic polynomial with those roots. It was marked as one of the harder problems, so I was kind of confused because it seems obvious that a polynomial like $$\left(x-\cos\frac{2\pi}{7}\right)\left(x-\cos\frac{4\pi}{7}\right)\left(x-\cos\frac{6\pi}{7}\right)$$
should work.
But when I looked up the solution in the solutions manual, it turns out that you can use an obscure trig identity for $\cos{7\theta}$ to eventually construct the polynomial $$8x^3+4x^2-4x-1$$
I'm really lost. What's wrong with my trivial example?

A:

Well if they didn't specify anything else your solution is correct. But typically people specify things like find a polynomial with rational (or equivalently integer) coefficients meeting the specific property.
My favorite example of when this happens is when people say $\pi$ is transcendental because it's not solution of a polynomial equation. I usually point out
$$x-\pi$$ is a polynomial and then preach the importance of correctly qualifying expressions.

A:

easiest is to take $\omega$ as a primitive seventh root of unity, any one of $$ e^{2 \pi i / 7} \; , \; \; e^{4 \pi i / 7} \; , \; \;e^{6 \pi i / 7} \; , \; \;  $$
so that $\omega^7 = 1$ but $\omega \neq 1,$ and
$$ \omega^6 + \omega^5 + \omega^4 + \omega^3 + \omega^2 + \omega + 1 = 0.  $$
Next, for any of the three, take
$$ x = \omega + \frac{1}{\omega}  $$
First,
$$  x^3 = \omega^3 + 3 \omega + \frac{3}{\omega} + \frac{1}{\omega^3} \; \; , \; \;  $$
$$  x^2 = \omega^2 + 2 + \frac{1}{\omega^2} \;    $$
$$  -2 x = -2 \omega - \frac{2}{\omega}  $$
$$   -1 = -1  \; \; .  $$
So
$$ x^3 +  x^2 - 2 x - 1  = \; \; \frac{\omega^6 + \omega^5 + \omega^4 + \omega^3 + \omega^2 + \omega + 1}{\omega^3}\; \; = \; 0 $$
In each case, we have $x = 2 \cos (2 k \pi i / 7),$ so taking $x = 2c$ we find
$8c^3 + 4 c^2 - 4 c - 1 = 0.$


Q:

Fail to start NET.Tcp Port Service

I can't start the following windows services on my Win 7 machine. When I try to start the service of Net.Tcp Port Sharing service, I got the error:

The Service on local computer started and then stopped ,Some services stop automatically if there are not in use by other services or programs

So I modified the SMSvcHost.exe.config file by the help.
I changed two files C:\Windows\Microsoft.NET\Framework\v4.0.30319\SMSvcHost.exe.config and C:\Windows\Microsoft.NET\Framework64\v4.0.30319\SMSvcHost.exe.config
The configuration file is:
<?xml version="1.0" encoding="utf-8"?>
<!-- The configuration file for SMSvcHost.exe -->
<configuration>
   <runtime>
    <gcConcurrent enabled="false" />
  </runtime>
 <system.serviceModel>
    <!-- SMSvcHost ETW traces are redirected by default to an etwProviderId different from WCF's default.
         To trace to the default provider, remove the etwProviderId attribute below. -->
    <diagnostics performanceCounters="Off" etwProviderId="{f18839f5-27ff-4e66-bd2d-639b768cf18b}"/>
</system.serviceModel>
<!-- Below are some sample config settings: -->
<system.serviceModel.activation>
    <net.tcp listenBacklog="10" maxPendingConnections="100" maxPendingAccepts="10" receiveTimeout="00:00:10" teredoEnabled="false">
        <allowAccounts>
            // LocalSystem account
            <add securityIdentifier="S-1-5-18"/>

            // LocalService account
            <add securityIdentifier="S-1-5-19"/>

            // Administrators account
            <add securityIdentifier="S-1-5-20"/>

            // Network Service account
            <add securityIdentifier="S-1-5-32-544" />

            // IIS_IUSRS account (Vista only)
            <add securityIdentifier="S-1-5-32-568"/>
        </allowAccounts>
    </net.tcp>
    <net.pipe maxPendingConnections="100" maxPendingAccepts="10" receiveTimeout="00:00:10">
        <allowAccounts>
            // LocalSystem account
            <add securityIdentifier="S-1-5-18"/>

            // LocalService account
            <add securityIdentifier="S-1-5-19"/>

            // Administrators account
            <add securityIdentifier="S-1-5-20"/>

            // Network Service account
            <add securityIdentifier="S-1-5-32-544" />

            // IIS_IUSRS account (Vista only)
            <add securityIdentifier="S-1-5-32-568"/>
        </allowAccounts>
    </net.pipe>
    <diagnostics performanceCountersEnabled="true" />
</system.serviceModel.activation>

Unfortunately the modification will not take effect even I restart the desktop machine.. I am sure that sure SMSvcHost.exe does not exist in Task Manager.

A:

Under some help, I got the solution.
There are two errors.

The configuration contains invalid values. Ex: // LocalService account. It should be <!-- LocalService account  -->.
Installed a NetFxRepairTool from here.

The main problem is that during install .net framework, something is missing.


Q:

Дополнительная панель с кнопками при редактировании таблицы, как в сообщениях на iOS

Я перерыл весь интернет, но так и не нашел ответа; в сообщениях при редактировании списка вылезает дополнительная панель с кнопками, см. картинку.

Не могу понять, это родной функционал UITableView? (скорее всего нет)
Или же это отдельный view, который приезжает поверх таблицы?
Подскажите, в правильную сторону хоть копаю. На Swift все делаю.

A:

Попробуй использовать UIToolbar
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50))
        toolbar.barStyle = UIBarStyle.default
        toolbar.items = [
            UIBarButtonItem(title: "Отмена", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelAction)),
            UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil),
            UIBarButtonItem(title: "Далее", style: UIBarButtonItemStyle.plain, target: self, action: #selector(nextAction))]
        toolbar.sizeToFit()

Для показа
view.addSubview(toolbar)

Для скрытия
toolbar.removeFromSuperView


Q:

php: modifing object properties with a matching array

I need to modify properties of an object (a Wordpress object) and I would like to do it by using a matching array of values.
Wordpress Object
array(9) {
  ["post"]=> object(stdClass)#120 (25) {
    ["labels"]=> object(stdClass)#123 (12) {
      ["name"]=> string(5) "Posts"
      ["singular_name"]=> string(4) "Post"
      ["add_new"]=> string(7) "Add New"
      ["add_new_item"]=> string(12) "Add New Post"
      ["edit_item"]=> string(9) "Edit Post"
      ["new_item"]=> string(8) "New Post"
      ["view_item"]=> string(9) "View Post"
      ["search_items"]=> string(12) "Search Posts"
      ["not_found"]=> string(15) "No posts found."
      ["not_found_in_trash"]=> string(24) "No posts found in Trash."
      ["parent_item_colon"]=> NULL
      ["menu_name"]=> string(5) "Posts"
    }
    ["description"]=> string(0) ""
    ["publicly_queryable"]=> bool(true)
    ["exclude_from_search"]=> bool(false)
    ["capability_type"]=> string(4) "post"
    ["map_meta_cap"]=> bool(true)
    ["_builtin"]=> bool(true)
    ["_edit_link"]=> string(16) "post.php?post=%d"
    ["hierarchical"]=> bool(false)
    ["public"]=> bool(true)
    ["rewrite"]=> bool(false)
    ["has_archive"]=> bool(false)
    ["query_var"]=> bool(false)
    ["register_meta_box_cb"]=> NULL
    ["taxonomies"]=> array(0) {
    }
    ["show_ui"]=> bool(true)
    ["menu_position"]=> NULL
    ["menu_icon"]=> NULL
    ["permalink_epmask"]=> int(1)
    ["can_export"]=> bool(true)
    ["show_in_nav_menus"]=> bool(true)
    ["show_in_menu"]=> bool(true)
    ["name"]=> string(4) "post"
    ["cap"]=> object(stdClass)#122 (14) {
      ["edit_post"]=> string(9) "edit_post"
      ["read_post"]=> string(9) "read_post"
      ["delete_post"]=> string(11) "delete_post"
      ["edit_posts"]=> string(10) "edit_posts"
      ["edit_others_posts"]=> string(17) "edit_others_posts"
      ["publish_posts"]=> string(13) "publish_posts"
      ["read_private_posts"]=> string(18) "read_private_posts"
      ["read"]=> string(4) "read"
      ["delete_posts"]=> string(12) "delete_posts"
      ["delete_private_posts"]=> string(20) "delete_private_posts"
      ["delete_published_posts"]=> string(22) "delete_published_posts"
      ["delete_others_posts"]=> string(19) "delete_others_posts"
      ["edit_private_posts"]=> string(18) "edit_private_posts"
      ["edit_published_posts"]=> string(20) "edit_published_posts"
    }
    ["label"]=> string(5) "Posts"
  }
etc...,
etc...,
}

Array of values to be changed
$newpost = array(
   'post' => array (
      'labels' => array(
         'name' => 'News',
         'singular_name' => 'News',
         'add_new' => 'Add New',
         'add_new_item' => 'Add New News',
         'edit_item' => 'Edit News',
         'new_item' => 'New News',
         'view_item' => 'View News',
         'search_items' => 'Search News',
         'not_found' =>  'No news found',
         'not_found_in_trash' => 'No news found in Trash',
         'parent_item_colon' => '',
         'menu_name' => 'News'
      ),
   'menu_icon' => get_bloginfo( 'template_url' ).'/template/cup.png',
   )
);

Is this possible?

A:

A quick&dirty solution came to my mind:
I use json_decode and encode because casting the original object to an array using (array)$wordpressObject won't convert nested objects to arrays
$wordpressArray = json_decode(json_encode($wordpressObject), true);

$modifiedArray = array_merge($wordpressArray, $newpost);

json serialization is used again to convert between array and object recursively
$modifiedWordpressObject = json_decode(json_encode($modifiedArray));

I just wrote an example on codepad
It would be a cleaner solution to write a recursive algorithm to convert arrays to objects, and the other way around, but it is the first thing that came to my mind.


Q:

At least how many children should a family have so that, with probability 0.95, the family has at least 1 boy and at least 1 girl

At least how many children should a family have so that, with probability 0.95, the family has at least 1 boy and at least 1 girl (boys and girls are equally likely).
What my teacher told me:
$$1-\{(1/2)^n +(1/2)^n\}> 0.95$$
Why can't we do it like this:
$$1-\sum_{k=n}^{\infty}\{(1/2)^k +(1/2)^k\} = 0.95$$ (where $n$ is required answer)
I am not able to identify the bug, or I think I have not understand the question completely.
Please help me.

A:

$(1/2)^n+(1/2)^n$ is the probability of getting all boys are all girls if they have $n$ children. Your teacher is looking for the smallest $n$ for which this is less than $0.05$, so that the probability of having at least one child of each sex is greater than $0.95$. (The inequality should be non-strict: the smallest $n$ such that $(1/2)^n+(1/2)^n\le0.05$.)
Your $$\sum_{k\ge n}\left(\left(\frac12\right)^k+\left(\frac12\right)^k\right)$$
is hard to interpret at all. You’re adding the probability that all of the kids are of the same sex if they have $n$ kids, the probability that all are of the same sex if they have $n+1$ kids, and so on, but this sum of conditional probabilities has no obvious meaning. It’s not the probability that all of their kids are of the same sex if they have at least $n$ kids, if that’s what you were thinking: to get that, you’d have to have a probability distribution of number of kids, and you’d have to weight the $k$ term by the probability that they have $k$ kids. We have no such probability distribution, and indeed there can’t be one here, because they’re choosing the number of kids on the basis of what happanes if they have that many.


Q:

Plot very small values with matplotlib in jupyter

I am trying to plot some extremely small values with matplotlib in jupyter notebook (on a macbook pro). However, regardless if I set the y-axis limits, all I get is a flat line. What I am after is something like the example (png) below with regard to y-axis notation. I also tried the same example outside of jupyter and I still get the same results. Here's the code suggested by Andrew Walker on my previous question:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(13,6))
ax = fig.add_subplot(111)
plt.hold(True)

xs = np.linspace(0, 1, 101)
ys = 1e-300 * np.exp(-(xs-0.5)**2/0.01)

ax.plot(xs, ys, marker='.')

Here's what I get:

And here's what I'm after:

A:

The easiest thing to do is to just plot your values multiplied by 10^300, and then change the y-axis label:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(13,6))
ax = fig.add_subplot(111)
plt.hold(True)

xs = np.linspace(0, 1, 101)
ys = np.exp(-(xs-0.5)**2/0.01)

ax.plot(xs, ys, marker='.')

ax.set_ylabel(r'Value [x 10^{-300}]')


Q:

pretrained fasterrcnn_resnet50_fpn: "forward() takes 2 positional arguments but 5 were given" on single image test

I am receving an error when executing the code below:
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision.models.detection import fasterrcnn_resnet50_fpn
import PIL.Image as Image

device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')

model = fasterrcnn_resnet50_fpn(pretrained=True)
model.roi_heads = nn.Sequential()
model.to(device)

img = Image.open('frame_00001.jpg')
transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                                    std=[0.229, 0.224, 0.225])])
img = transform(img).unsqueeze(0).to(device)

model.eval()
output = model(img)

The last line causes a "TypeError: forward() takes 2 positional arguments but 5 were given."
The size of img is [1, 3, 960, 1280].
If I add square brackets around img before passing into the model (output = model([img])), I get a "ValueError: images is expected to be a list of 3d tensors of shape [C, H, W], got torch.Size([1, 3, 960, 1280])." Then, if I use "img.view(3, 960, 1280)," I get the original error again.
What is the solution to this problem? Thank you.

A:

I'm not sure what you're trying to do with the line:

model.roi_heads = nn.Sequential()

This line is causing the problem, I ran you're code excerpt without this line and it worked as expected (minus a few warnings about deprecation coming from the model being used, but the output looks reasonable)


Q:

What kinds of production issues should I anticipate when deploying a Flex app?

My company has been working on a Flex dashboard that displays realtime financial information. It will be deployed over a corporate WAN to perhaps a few dozen users.
This is our first Flex project, and while development has been very pleasant, we're a little concerned about what production issues might come up (users not having the right Flash player installed, long download times,BlazeDS performance, etc).
Our stack is RDBMS/Spring/BlazeDS (remoting and messaging)/Flex.
Does anyone with experience deploying a commercial Flex app have any words of advice?

A:

Your biggest problems are likely to be:

your users not having the correct version of the flash player
your users having locked-down desktops and either not being able to download the right version of the player or not being allowed to use the player at all
download speeds of the swf if you have a big app
intermittent loss of connection to your back-end due to either bugs in your code or unavailable network connection
restrictive browser policies

None of these are insurmountable, but you are likely to encounter all of them in the first few months.
I am presuming that you have tested your app for performance under reasonable load and will have fixed those scalability issues already :-)
HTH


Q:

Is the circuit a Parallel RLC if there is a voltage source in between capacitor and inductor?

simulate this circuit – Schematic created using CircuitLab

As the schematic shows, there is a voltage source in between capacitor and inductor. Is it a valid Parallel RLC circuit. For example: can we say that we can use the standard equations like:

Alpha = 1 / ( 2 * R * C)
W0^2 = 1 / (L * C)

A:

In comments, you say you'll apply a stimulus at the location of V1. In that case, you can redraw the circuit like this:

simulate this circuit – Schematic created using CircuitLab
You can see that as far as this stimulus is concerned, the L and C elements are not in parallel. Nor are they strictly in series, since not all current through the C element also flows through the L element.
You can also see immediately that this circuit has some behavior that doesn't match either a parallel or series RLC circuit. For example, the impedance goes to inifinity (like a series RLC circuit) at \$\omega=0\$, but it goes to R (instead of to infinity again) in the limit as \$\omega\to\infty\$.
Short answer: This circuit does not behave like either a series or parallel RLC circuit.