问:
Signature of the body and declaration in a method implementation do not match
I want to implement an interface at runtime, however when i execute

```<code>return Activator.CreateInstance(typeBuilder.CreateTypeInfo().AsType(), new RPCRequestProxy());
</code>```

in RPCClientFactory.cs it throws

System.TypeLoadException: Signature of the body and declaration in a
  method implementation do not match.

I use dotnet core 1.0.4.

The entry point Program.cs :

```<code>namespace RPC
{
    interface IRCPClient
    {
        Task Foo([UrlParam]int b, [UrlParam]string a, [UrlParam] DateTime c);
    }

    class Program
    {
        static void Main(string[] args)
        {
            var factory = new RPCClientFactory();
            factory.Register<IRCPClient>();

            var cli = factory.GetClient<IRCPClient>();
            cli.Foo(1, "HelloWorld", DateTime.Now);

            Console.ReadKey();
        }
    }
}
</code>```

The RPCClientFactory.cs:

```<code>    public class RPCClientFactory
    {
        private readonly ConcurrentDictionary<Type, object> _clients = new ConcurrentDictionary<Type, object>();

        public void Register<ClientType>()
        {
            Register(typeof(ClientType));
        }

        public void Register(Type type)
        {
            if (!_clients.TryAdd(type, CreateImplInstance(type)))
                throw new InvalidOperationException($"bad type{type}");
        }

        public object CreateImplInstance(Type type)
        {
            var typeBuilder = CreateTypeBuilder(type);
            var methods = type.GetMethods();

            var field = CreateFiled(typeBuilder);
            CreateCotr(typeBuilder, field);
            CreateMethods(typeBuilder, methods, field);

            typeBuilder.AddInterfaceImplementation(type);

            return Activator.CreateInstance(typeBuilder.CreateTypeInfo().AsType(), new RPCRequestProxy());
        }

        private static TypeBuilder CreateTypeBuilder(Type type)
        {
            var typeSignature = "MyDynamicType";
            var an = new AssemblyName(typeSignature);
            var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
            TypeBuilder tb = moduleBuilder.DefineType(typeSignature,
                    TypeAttributes.Public |
                    TypeAttributes.Class |
                    TypeAttributes.AutoClass |
                    TypeAttributes.AnsiClass |
                    TypeAttributes.BeforeFieldInit |
                    TypeAttributes.AutoLayout,
                    null);

            return tb;
        }

        private static FieldInfo CreateFiled(TypeBuilder typeBuilder)
        {
            return typeBuilder.DefineField("_proxy", typeof(RPCRequestProxy), FieldAttributes.Private);
        }

        private static void CreateCotr(TypeBuilder typeBuilder, FieldInfo proxyField)
        {
            var ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public
                , CallingConventions.Standard
                , new[] { typeof(RPCRequestProxy) });

            var il = ctorBuilder.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[0]));
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Stfld, proxyField);
            il.Emit(OpCodes.Ret);
        }

        public void CreateMethods(TypeBuilder typeBuilder, MethodInfo[] methods, FieldInfo field)
        {
            foreach (var method in methods)
            {
                CreateMethod(typeBuilder, method, field);
            }
        }

        private static void CreateMethod(TypeBuilder typeBuilder, MethodInfo method, FieldInfo proxyFiled)
        {
            var paramters = method.GetParameters();

            var methodBuilder = typeBuilder.DefineMethod(method.Name,
                MethodAttributes.Public,
                CallingConventions.Standard,
                method.ReturnType,
                paramters.Select(x => x.GetType()).ToArray());

            var il = methodBuilder.GetILGenerator();

            il.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(new Type[0]));
            il.Emit(OpCodes.Stloc_0);

            for (var i = 0; i < paramters.Length; ++i)
            {
                var param = paramters[i];

                if (param.GetCustomAttribute<BodyParamAttribute>() != null) continue;

                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Ldstr, param.Name);
                il.Emit(OpCodes.Ldarg, i + 1);

                if (param.ParameterType.GetTypeInfo().IsValueType)
                {
                    il.Emit(OpCodes.Box, param.GetType());
                }

                il.Emit(OpCodes.Callvirt, typeof(Dictionary<string, object>).GetMethod("Add"));
            }

            var proxyMethod = typeof(RPCRequestProxy)
                .GetMethods()
                .First(x => x.Name == "PostAsync" && x.GetParameters().Length == 2);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, proxyFiled);
            il.Emit(OpCodes.Ldstr, "xxx.xxx.xxx");
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Callvirt, proxyMethod);
            il.Emit(OpCodes.Stloc_1);
            il.Emit(OpCodes.Ldloc_1);
            il.Emit(OpCodes.Ret);

            typeBuilder.DefineMethodOverride(methodBuilder, method);
        }

        public ClientType GetClient<ClientType>() where ClientType : class
        {
            _clients.TryGetValue(typeof(ClientType), out object cli);
            return cli as ClientType;
        }

        public ClientType GetRequiredClient<ClientType>() where ClientType : class
        {
            var cli = GetClient<ClientType>();

            if (cli == null) throw new InvalidOperationException($"bad type{typeof(ClientType)}");

            return cli;
        }
    }
</code>```

The RPCRequestProxy.cs:

```<code>    public class RPCRequestProxy
    {
        public RPCRequestProxy()
        {

        }

        public async Task PostAsync(string url, IDictionary<string, object> urlParams)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("URL:"  + url);

                Console.WriteLine("QueryString:");
                foreach (var kv in urlParams)
                {
                    Console.WriteLine($"{kv.Key}={kv.Value}");
                }

            });
        }
    }
</code>```

After register IRCPClient, i hope it generates a class like this:

```<code>    class RCPClient : IRCPClient
    {
        private readonly RPCRequestProxy _proxy;

        public RCPClient(RPCRequestProxy proxy)
        {
            _proxy = proxy;
        }

        public Task Foo([UrlParam] int b, [UrlParam] string a, [UrlParam] DateTime c)
        {
            var urlParams = new Dictionary<string, object>();

            urlParams.Add(nameof(b), b);
            urlParams.Add(nameof(a), a);
            urlParams.Add(nameof(c), c);

            return _proxy.PostAsync("xxx.xxx.xxx", urlParams);
        }
    }
</code>```

答:
Finally, i worked it out:

1: We must DeclareLocal before we use a local value.

2: Change paramters.Select(x => x.GetType()).ToArray() to paramters.Select(x => x.ParameterType).ToArray()

This is my final CreateMethod method of RPCClientFactory.cs

```<code>        private static void CreateMethod(TypeBuilder typeBuilder, MethodInfo method, FieldInfo proxyFiled)
        {
            var paramters = method.GetParameters();

            var methodBuilder = typeBuilder.DefineMethod(method.Name,
                MethodAttributes.Public
                | MethodAttributes.Virtual
                | MethodAttributes.HideBySig
                | MethodAttributes.SpecialName,
                CallingConventions.Standard,
                method.ReturnType,
                paramters.Select(x => x.ParameterType).ToArray()); // change this line

            var il = methodBuilder.GetILGenerator();

            il.DeclareLocal(typeof(Dictionary<string, object>)); // add this line
            il.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(new Type[0]));
            il.Emit(OpCodes.Stloc_0);

            for (short i = 0; i < paramters.Length; ++i)
            {
                var param = paramters[i];

                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Ldstr, param.Name);
                il.Emit(OpCodes.Ldarg, (short)(i +1));

                if (param.ParameterType.GetTypeInfo().IsValueType)
                {
                    il.Emit(OpCodes.Box, param.ParameterType);
                }

                il.Emit(OpCodes.Callvirt, typeof(Dictionary<string, object>).GetMethod("Add"));
            }

            var proxyMethod = typeof(RPCRequestProxy)
                .GetMethods()
                .First(x => x.Name == "PostAsync" && x.GetParameters().Length == 2);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, proxyFiled);
            il.Emit(OpCodes.Ldstr, "xxx.xxx.xxx");
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Callvirt, proxyMethod);
            il.Emit(OpCodes.Ret);
        }
</code>```

Body:
I want to implement an interface at runtime, however when i execute

return Activator.CreateInstance(typeBuilder.CreateTypeInfo().AsType(), new RPCRequestProxy());

in RPCClientFactory.cs it throws

System.TypeLoadException: Signature of the body and declaration in a
  method implementation do not match.

I use dotnet core 1.0.4.

The entry point Program.cs :

namespace RPC
{
    interface IRCPClient
    {
        Task Foo([UrlParam]int b, [UrlParam]string a, [UrlParam] DateTime c);
    }

    class Program
    {
        static void Main(string[] args)
        {
            var factory = new RPCClientFactory();
            factory.Register<IRCPClient>();

            var cli = factory.GetClient<IRCPClient>();
            cli.Foo(1, "HelloWorld", DateTime.Now);

            Console.ReadKey();
        }
    }
}

The RPCClientFactory.cs:

    public class RPCClientFactory
    {
        private readonly ConcurrentDictionary<Type, object> _clients = new ConcurrentDictionary<Type, object>();

        public void Register<ClientType>()
        {
            Register(typeof(ClientType));
        }

        public void Register(Type type)
        {
            if (!_clients.TryAdd(type, CreateImplInstance(type)))
                throw new InvalidOperationException($"bad type{type}");
        }

        public object CreateImplInstance(Type type)
        {
            var typeBuilder = CreateTypeBuilder(type);
            var methods = type.GetMethods();

            var field = CreateFiled(typeBuilder);
            CreateCotr(typeBuilder, field);
            CreateMethods(typeBuilder, methods, field);

            typeBuilder.AddInterfaceImplementation(type);

            return Activator.CreateInstance(typeBuilder.CreateTypeInfo().AsType(), new RPCRequestProxy());
        }

        private static TypeBuilder CreateTypeBuilder(Type type)
        {
            var typeSignature = "MyDynamicType";
            var an = new AssemblyName(typeSignature);
            var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
            TypeBuilder tb = moduleBuilder.DefineType(typeSignature,
                    TypeAttributes.Public |
                    TypeAttributes.Class |
                    TypeAttributes.AutoClass |
                    TypeAttributes.AnsiClass |
                    TypeAttributes.BeforeFieldInit |
                    TypeAttributes.AutoLayout,
                    null);

            return tb;
        }

        private static FieldInfo CreateFiled(TypeBuilder typeBuilder)
        {
            return typeBuilder.DefineField("_proxy", typeof(RPCRequestProxy), FieldAttributes.Private);
        }

        private static void CreateCotr(TypeBuilder typeBuilder, FieldInfo proxyField)
        {
            var ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public
                , CallingConventions.Standard
                , new[] { typeof(RPCRequestProxy) });

            var il = ctorBuilder.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[0]));
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Stfld, proxyField);
            il.Emit(OpCodes.Ret);
        }

        public void CreateMethods(TypeBuilder typeBuilder, MethodInfo[] methods, FieldInfo field)
        {
            foreach (var method in methods)
            {
                CreateMethod(typeBuilder, method, field);
            }
        }

        private static void CreateMethod(TypeBuilder typeBuilder, MethodInfo method, FieldInfo proxyFiled)
        {
            var paramters = method.GetParameters();

            var methodBuilder = typeBuilder.DefineMethod(method.Name,
                MethodAttributes.Public,
                CallingConventions.Standard,
                method.ReturnType,
                paramters.Select(x => x.GetType()).ToArray());

            var il = methodBuilder.GetILGenerator();

            il.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(new Type[0]));
            il.Emit(OpCodes.Stloc_0);

            for (var i = 0; i < paramters.Length; ++i)
            {
                var param = paramters[i];

                if (param.GetCustomAttribute<BodyParamAttribute>() != null) continue;

                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Ldstr, param.Name);
                il.Emit(OpCodes.Ldarg, i + 1);

                if (param.ParameterType.GetTypeInfo().IsValueType)
                {
                    il.Emit(OpCodes.Box, param.GetType());
                }

                il.Emit(OpCodes.Callvirt, typeof(Dictionary<string, object>).GetMethod("Add"));
            }

            var proxyMethod = typeof(RPCRequestProxy)
                .GetMethods()
                .First(x => x.Name == "PostAsync" && x.GetParameters().Length == 2);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, proxyFiled);
            il.Emit(OpCodes.Ldstr, "xxx.xxx.xxx");
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Callvirt, proxyMethod);
            il.Emit(OpCodes.Stloc_1);
            il.Emit(OpCodes.Ldloc_1);
            il.Emit(OpCodes.Ret);

            typeBuilder.DefineMethodOverride(methodBuilder, method);
        }

        public ClientType GetClient<ClientType>() where ClientType : class
        {
            _clients.TryGetValue(typeof(ClientType), out object cli);
            return cli as ClientType;
        }

        public ClientType GetRequiredClient<ClientType>() where ClientType : class
        {
            var cli = GetClient<ClientType>();

            if (cli == null) throw new InvalidOperationException($"bad type{typeof(ClientType)}");

            return cli;
        }
    }

The RPCRequestProxy.cs:

    public class RPCRequestProxy
    {
        public RPCRequestProxy()
        {

        }

        public async Task PostAsync(string url, IDictionary<string, object> urlParams)
        {
            await Task.Run(() =>
            {
                Console.WriteLine("URL:"  + url);

                Console.WriteLine("QueryString:");
                foreach (var kv in urlParams)
                {
                    Console.WriteLine($"{kv.Key}={kv.Value}");
                }

            });
        }
    }

After register IRCPClient, i hope it generates a class like this:

    class RCPClient : IRCPClient
    {
        private readonly RPCRequestProxy _proxy;

        public RCPClient(RPCRequestProxy proxy)
        {
            _proxy = proxy;
        }

        public Task Foo([UrlParam] int b, [UrlParam] string a, [UrlParam] DateTime c)
        {
            var urlParams = new Dictionary<string, object>();

            urlParams.Add(nameof(b), b);
            urlParams.Add(nameof(a), a);
            urlParams.Add(nameof(c), c);

            return _proxy.PostAsync("xxx.xxx.xxx", urlParams);
        }
    }

Body:
Finally, i worked it out:

1: We must DeclareLocal before we use a local value.

2: Change paramters.Select(x => x.GetType()).ToArray() to paramters.Select(x => x.ParameterType).ToArray()

This is my final CreateMethod method of RPCClientFactory.cs

        private static void CreateMethod(TypeBuilder typeBuilder, MethodInfo method, FieldInfo proxyFiled)
        {
            var paramters = method.GetParameters();

            var methodBuilder = typeBuilder.DefineMethod(method.Name,
                MethodAttributes.Public
                | MethodAttributes.Virtual
                | MethodAttributes.HideBySig
                | MethodAttributes.SpecialName,
                CallingConventions.Standard,
                method.ReturnType,
                paramters.Select(x => x.ParameterType).ToArray()); // change this line

            var il = methodBuilder.GetILGenerator();

            il.DeclareLocal(typeof(Dictionary<string, object>)); // add this line
            il.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(new Type[0]));
            il.Emit(OpCodes.Stloc_0);

            for (short i = 0; i < paramters.Length; ++i)
            {
                var param = paramters[i];

                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Ldstr, param.Name);
                il.Emit(OpCodes.Ldarg, (short)(i +1));

                if (param.ParameterType.GetTypeInfo().IsValueType)
                {
                    il.Emit(OpCodes.Box, param.ParameterType);
                }

                il.Emit(OpCodes.Callvirt, typeof(Dictionary<string, object>).GetMethod("Add"));
            }

            var proxyMethod = typeof(RPCRequestProxy)
                .GetMethods()
                .First(x => x.Name == "PostAsync" && x.GetParameters().Length == 2);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, proxyFiled);
            il.Emit(OpCodes.Ldstr, "xxx.xxx.xxx");
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Callvirt, proxyMethod);
            il.Emit(OpCodes.Ret);
        }


来源: stackexchange

问:
Using angular 1 simple with express js
I have used node js with handlebars and now want to move towards the proper MEAN stack. I have learned angular1 and using it with single page node js apps.
But when it comes to express, after doing "express project-name" I start my server by "npm start" and in the "views" lies my html and angular code. How will by angular app there will interact or will run with my nodejs, I have scratched my head all over youtube videos and questions here but didn't find a satisfactory answer. What I want to work in angular is:-

```<code>$http.get('/users/signup',function(res){
console.log(res.data);
}
</code>```

and in nodejs users.js route resides this:-

```<code>router.get('/signup',function(req,res,next){
res.send("req recieved here");
}
</code>```

How will the req from angular be made to the server running using npm start??

答:
Try this:-</p>

```<code>router.get('/signup',function(req,res){
    res.send("Any data");
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using angular 1 simple with express js

Body:
I have used node js with handlebars and now want to move towards the proper MEAN stack. I have learned angular1 and using it with single page node js apps.
But when it comes to express, after doing "express project-name" I start my server by "npm start" and in the "views" lies my html and angular code. How will by angular app there will interact or will run with my nodejs, I have scratched my head all over youtube videos and questions here but didn't find a satisfactory answer. What I want to work in angular is:-

$http.get('/users/signup',function(res){
console.log(res.data);
}

and in nodejs users.js route resides this:-

router.get('/signup',function(req,res,next){
res.send("req recieved here");
}

How will the req from angular be made to the server running using npm start??

Body:
Try this:-

router.get('/signup',function(req,res){
    res.send("Any data");
});


问:
How does & bit operator work here?
In Java Collection classes, I have noticed very often codes like below

```<code>  //ArrayDeque
    public E pollFirst() {
    int h = head;
    @SuppressWarnings("unchecked")
    E result = (E) elements[h];
    // Element is null if deque empty
    if (result == null)
        return null;
    elements[h] = null;     // Must null out slot
    head = (h + 1) & (elements.length - 1);
    return result;
}
</code>```

What does head = (h + 1) & (elements.length - 1); do ?
   Why is & operator used here and what purpose does it serve.

My Question is not how & works, but what's its use here.

Can anyone explain it ?

答:
That & operation is not a true equivalent for %, think negative numbers. It's not the case here, but there are other places where this matters (like HashMap), where this is done via :

```<code>(n - 1) & hash // n - current capacity, hash - hashcode
</code>```

Since hashcodes are int values - they can be negative numbers. Using % instead of & would result in a negative number, which simply can't happen for HashMap (since that is the bucket number).

Title: How does & bit operator work here?

Body:
In Java Collection classes, I have noticed very often codes like below

  //ArrayDeque
    public E pollFirst() {
    int h = head;
    @SuppressWarnings("unchecked")
    E result = (E) elements[h];
    // Element is null if deque empty
    if (result == null)
        return null;
    elements[h] = null;     // Must null out slot
    head = (h + 1) & (elements.length - 1);
    return result;
}

What does head = (h + 1) & (elements.length - 1); do ?
   Why is & operator used here and what purpose does it serve.

My Question is not how & works, but what's its use here.

Can anyone explain it ?

Body:
That & operation is not a true equivalent for %, think negative numbers. It's not the case here, but there are other places where this matters (like HashMap), where this is done via :

(n - 1) & hash // n - current capacity, hash - hashcode

Since hashcodes are int values - they can be negative numbers. Using % instead of & would result in a negative number, which simply can't happen for HashMap (since that is the bucket number).


问:
how to parse json into php
i have a json data retrieved from data base i.e```<code>$result=array();
$query="SELECT * FROM fish";
$result1 = mysql_query($query, $conn);
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){
   $result[]=$table;
}
   echo json_encode($result);</code>```
and this give me the result ```[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]```

but from another page when i call this json data i.e```$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json->fish_id;```

it give me the error

```Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0```

答: try echo $json['fish_id']; i might suspect it convert it to an array

ContentLicense: CC BY-SA 2.5

Title: how to parse json into php

Body:
i have a json data retrieved from data base i.e
$result=array();
$query="SELECT * FROM fish";
$result1 = mysql_query($query, $conn);
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){
   $result[]=$table;
}
   echo json_encode($result);

and this give me the result
[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]

but from another page when i call this json data i.e
$input = file_get_contents("http://localhost/fish/fish-json.php");
$json=json_decode($input);
echo $json->fish_id;

it give me the error

Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0


问:
How Sinon stubs works under the hood?
In the last months I've been working with JavaScript and using SinonJS to stub some behaviours. I've manage to make it work, I've stubbed lots of methods and everything works great.

But I still have some questions about how Sinon works under the table. I guess I'm saying Sinon, but this question might apply to every other library designed to mock/stub/spy.

The language I've worked most in the past years was Java. In Java, I've used Mockito to mock/stub the dependencies and dependency injection. I used to import the Class, annotate the field with @Mock and pass this mock as param to the class under test. It's easy to me to see what I'm doing: mocking a class and passing the mock as param.

When I first start working with SinonJS, I saw something like this:

moduleUnderTest.spec.js

```<code>const request = require('request')

describe('Some tests', () => {
  let requestStub

  beforeEach(() => {
    requestStub = sinon.stub(request, 'get')
  })

  afterEach(() => {
    request.get.restore()
  })

  it('A test case', (done) => {
    const err = undefined
    const res = { statusCode: 200 }
    const body = undefined
    requestStub
      .withArgs("some_url")
      .yields(err, res, body)

    const moduleUnderTest = moduleUnderTest.someFunction()

    // some assertions
    })
})
</code>```

moduleUnderTest.js

```<code>const request = require('request')
// some code
  request
    .get("some_url", requestParams, onResponse)
</code>```

And it works. When we run the tests, the request inside the implementation moduleUnderTest.js calls the stubbed version of request module.

My question is: why this works?

When the test calls the implementation execution, the implementation requires and uses the request module. How Sinon (and other mock/stub/spy libraries) manage to make the implementation call the stub if we are not passing the stubbed object as param (injecting it)? Sinon replaces the whole request module (or part of it) during the test execution, making the stub available via require('request') and then restore it after the tests are finished?

I've tried to follow the logic in stub.js code in Sinon repo, but I'm not very familiar with JavaScript yet.
Sorry the long post and sorry if this is a dummy question. :)

答:
How Sinon (and other mock/stub/spy libraries) manage to make the implementation call the stub if we are not passing the stubbed object as param (injecting it)?

Let's write our own simple stubbing util, shall we?

For brevity it is very limited, provides no stubbing API and only returns 42 every time. But this should be enough to show how Sinon works.

```<code>function stub(obj, methodName) {
    // Get a reference to the original method by accessing
    // the property in obj named by methodName.
    var originalMethod = obj[methodName];

    // This is actually called on obj.methodName();
    function replacement() {
        // Always returns this value
        return 42;

        // Note that in this scope, we are able to call the
        // orignal method too, so that we'd be able to
        // provide callThrough();
    }

    // Remember reference to the original method to be able
    // to unstub (this is *one*, actually a little bit dirty
    // way to reference the original function)
    replacement.originalMethod = originalMethod;

    // Assign the property named by methodName to obj to
    // replace the method with the stub replacement
    obj[methodName] = replacement;

    return {
        // Provide the stub API here
    };
}

// We want to stub bar() away
var foo = {
    bar: function(x) { return x * 2; }
};

function underTest(x) {
    return foo.bar(x);
}

stub(foo, "bar");
// bar is now the function "replacement"
// foo.bar.originalMethod references the original method

underTest(3);
</code>```

Sinon replaces the whole request module (or part of it) during the test execution, making the stub available via require('request') and then restore it after the tests are finished?

require('request') will return the same (object) reference, that was created inside the "request" module, every time it's called.

See the NodeJS documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If it has not become clear yet: it replaces only a single method of the object reference returned from the "requested" module, it does not replace the module.

This is why you do not call

```<code>stub(obj.method)
</code>```

since this would only pass a reference to the function method. Sinon would be unable to change the object obj.

The documentation further says:

If you want to have a module execute code multiple times, then export a function, and call that function.

That means, if a module looks like this:

foo.js

```<code>module.exports = function() {
    return {
        // New object everytime the required "factory" is called
    };
};
</code>```

main.js

```<code>        // The function returned by require("foo") does not change
const   moduleFactory = require("./foo"),
        // This will change on every call
        newFooEveryTime = moduleFactory();
</code>```

Such module factory functions cannot be stubbed since you can't replace what was exported by require() from within the module.

In Java, I've used Mockito to mock/stub the dependencies and dependency injection. I used to import the Class, annotate the field with @Mock and pass this mock as param to the class under test. It's easy to me to see what I'm doing: mocking a class and passing the mock as param.

In Java, where you (nothing) can not reassign a method to a new value, this cannot be done. Instead new bytecode is generated that makes a mock provide the same interface like the mocked class. In contrast to Sinon, with Mockito all methods are mocked and should be explictly instructed to call the real method.

Mockito will effectively call mock() and finally assign the result to the annotated field.

But you'd still need to replace/assign the mock to a field in the class under test or pass it to a tested method since that mock on its own is not helpful.

```<code>@Mock
Type field;
</code>```

or

```<code>Type field = mock(Type.class)
</code>```

Is actually equivalent to Sinons mocks

```<code>var myAPI = { method: function () {} };
var mock = sinon.mock(myAPI);

mock.expects("method").once().throws();
</code>```

The method is first replaced with the expects() call:

```<code>wrapMethod(this.object, method, function () {
    return mockObject.invokeMethod(method, this, arguments);
});
</code>```

Title: How Sinon stubs works under the hood?

Body:
In the last months I've been working with JavaScript and using SinonJS to stub some behaviours. I've manage to make it work, I've stubbed lots of methods and everything works great.

But I still have some questions about how Sinon works under the table. I guess I'm saying Sinon, but this question might apply to every other library designed to mock/stub/spy.

The language I've worked most in the past years was Java. In Java, I've used Mockito to mock/stub the dependencies and dependency injection. I used to import the Class, annotate the field with @Mock and pass this mock as param to the class under test. It's easy to me to see what I'm doing: mocking a class and passing the mock as param.

When I first start working with SinonJS, I saw something like this:

moduleUnderTest.spec.js

const request = require('request')

describe('Some tests', () => {
  let requestStub

  beforeEach(() => {
    requestStub = sinon.stub(request, 'get')
  })

  afterEach(() => {
    request.get.restore()
  })

  it('A test case', (done) => {
    const err = undefined
    const res = { statusCode: 200 }
    const body = undefined
    requestStub
      .withArgs("some_url")
      .yields(err, res, body)

    const moduleUnderTest = moduleUnderTest.someFunction()

    // some assertions
    })
})

moduleUnderTest.js

const request = require('request')
// some code
  request
    .get("some_url", requestParams, onResponse)

And it works. When we run the tests, the request inside the implementation moduleUnderTest.js calls the stubbed version of request module.

My question is: why this works?

When the test calls the implementation execution, the implementation requires and uses the request module. How Sinon (and other mock/stub/spy libraries) manage to make the implementation call the stub if we are not passing the stubbed object as param (injecting it)? Sinon replaces the whole request module (or part of it) during the test execution, making the stub available via require('request') and then restore it after the tests are finished?

I've tried to follow the logic in stub.js code in Sinon repo, but I'm not very familiar with JavaScript yet.
Sorry the long post and sorry if this is a dummy question. :)

Body:
How Sinon (and other mock/stub/spy libraries) manage to make the implementation call the stub if we are not passing the stubbed object as param (injecting it)?

Let's write our own simple stubbing util, shall we?

For brevity it is very limited, provides no stubbing API and only returns 42 every time. But this should be enough to show how Sinon works.

function stub(obj, methodName) {
    // Get a reference to the original method by accessing
    // the property in obj named by methodName.
    var originalMethod = obj[methodName];

    // This is actually called on obj.methodName();
    function replacement() {
        // Always returns this value
        return 42;

        // Note that in this scope, we are able to call the
        // orignal method too, so that we'd be able to
        // provide callThrough();
    }

    // Remember reference to the original method to be able
    // to unstub (this is *one*, actually a little bit dirty
    // way to reference the original function)
    replacement.originalMethod = originalMethod;

    // Assign the property named by methodName to obj to
    // replace the method with the stub replacement
    obj[methodName] = replacement;

    return {
        // Provide the stub API here
    };
}

// We want to stub bar() away
var foo = {
    bar: function(x) { return x * 2; }
};

function underTest(x) {
    return foo.bar(x);
}

stub(foo, "bar");
// bar is now the function "replacement"
// foo.bar.originalMethod references the original method

underTest(3);

Sinon replaces the whole request module (or part of it) during the test execution, making the stub available via require('request') and then restore it after the tests are finished?

require('request') will return the same (object) reference, that was created inside the "request" module, every time it's called.

See the NodeJS documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If it has not become clear yet: it replaces only a single method of the object reference returned from the "requested" module, it does not replace the module.

This is why you do not call

stub(obj.method)

since this would only pass a reference to the function method. Sinon would be unable to change the object obj.

The documentation further says:

If you want to have a module execute code multiple times, then export a function, and call that function.

That means, if a module looks like this:

foo.js

module.exports = function() {
    return {
        // New object everytime the required "factory" is called
    };
};

main.js

        // The function returned by require("foo") does not change
const   moduleFactory = require("./foo"),
        // This will change on every call
        newFooEveryTime = moduleFactory();

Such module factory functions cannot be stubbed since you can't replace what was exported by require() from within the module.

In Java, I've used Mockito to mock/stub the dependencies and dependency injection. I used to import the Class, annotate the field with @Mock and pass this mock as param to the class under test. It's easy to me to see what I'm doing: mocking a class and passing the mock as param.

In Java, where you (nothing) can not reassign a method to a new value, this cannot be done. Instead new bytecode is generated that makes a mock provide the same interface like the mocked class. In contrast to Sinon, with Mockito all methods are mocked and should be explictly instructed to call the real method.

Mockito will effectively call mock() and finally assign the result to the annotated field.

But you'd still need to replace/assign the mock to a field in the class under test or pass it to a tested method since that mock on its own is not helpful.

@Mock
Type field;

or

Type field = mock(Type.class)

Is actually equivalent to Sinons mocks

var myAPI = { method: function () {} };
var mock = sinon.mock(myAPI);

mock.expects("method").once().throws();

The method is first replaced with the expects() call:

wrapMethod(this.object, method, function () {
    return mockObject.invokeMethod(method, this, arguments);
});


问:
Cannot understand the Output of this Code
```<code>void abc(int n) {
    if (n <= 10) {
        abc(++n);
        printf("%d\n", n);
    }
}

void main() {
    int m = 5;
    abc(m);
}
</code>```

The output shows:

```<code>11
10
9
8
7
6
</code>```

I cannot understand the output. Please explain. I am a novice code lover.

答:
The sequence of events is this:

main calls abc(5).

abc(5): n is <= 10, hence n is incremented to 6, calling abc(6).

abc(6): n is <= 10, hence n is incremented to 7, calling abc(7).

abc(7): n is <= 10, hence n is incremented to 8, calling abc(8).

abc(8): n is <= 10, hence n is incremented to 9, calling abc(9).

abc(9): n is <= 10, hence n is incremented to 10, calling abc(10).

abc(10): n is <= 10, hence n is incremented to 11, calling abc(11).

abc(11): n is not <= 10, function returns without any output.

back to abc(10): its own n variable is still 11, printf prints 11, function returns.

back to abc(9): its own n variable is still 10, printf prints 10, function returns.

back to abc(8): its own n variable is still 9, printf prints 9, function returns.

back to abc(7): its own n variable is still 8, printf prints 8, function returns.

back to abc(6): its own n variable is still 7, printf prints 7, function returns.

back to abc(5): its own n variable is still 6, printf prints 6, function returns.

main returns

Complete output:

```<code>11
10
9
8
7
6
</code>```

Each instance of abc() has its own value for local variable n, which explains why the values printed by the different instances are different.

Note that you should also:

include <stdio.h>

define main with this prototype: int main(void)

for good style, add a return 0; statement at the end of main.

Body:
void abc(int n) {
    if (n <= 10) {
        abc(++n);
        printf("%d\n", n);
    }
}

void main() {
    int m = 5;
    abc(m);
}

The output shows:

11
10
9
8
7
6

I cannot understand the output. Please explain. I am a novice code lover.

Body:
The sequence of events is this:

main calls abc(5).

abc(5): n is <= 10, hence n is incremented to 6, calling abc(6).

abc(6): n is <= 10, hence n is incremented to 7, calling abc(7).

abc(7): n is <= 10, hence n is incremented to 8, calling abc(8).

abc(8): n is <= 10, hence n is incremented to 9, calling abc(9).

abc(9): n is <= 10, hence n is incremented to 10, calling abc(10).

abc(10): n is <= 10, hence n is incremented to 11, calling abc(11).

abc(11): n is not <= 10, function returns without any output.

back to abc(10): its own n variable is still 11, printf prints 11, function returns.

back to abc(9): its own n variable is still 10, printf prints 10, function returns.

back to abc(8): its own n variable is still 9, printf prints 9, function returns.

back to abc(7): its own n variable is still 8, printf prints 8, function returns.

back to abc(6): its own n variable is still 7, printf prints 7, function returns.

back to abc(5): its own n variable is still 6, printf prints 6, function returns.

main returns

Complete output:

11
10
9
8
7
6

Each instance of abc() has its own value for local variable n, which explains why the values printed by the different instances are different.

Note that you should also:

include <stdio.h>

define main with this prototype: int main(void)

for good style, add a return 0; statement at the end of main.


问:
View doesn't return anything in Laravel
I just started to learn the laravel framework and have a strange situation here.

First of all in my web.php I have code like:

```<code><?php
Route::get('/', function () {
    return view('welcome');
});

Route::get('users', ['uses' => 'UsersController@index']);
</code>```

In my UsersController.php file I have code like:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function index(){
        return view('users.index');
    }
}
</code>```

I have a file named index.blade.php in directory views/users that has the same content as the default welcome.blade.php. But when I try to return view('users.index'); there is no result (no error, or text) but when I try to return view('welcome'); it works just fine.

The directory and the file truly exists.
I'm using Macbook Pro.

welcome.blade.php and the /users/index.blade.php content (default welcome page):

```<code><!doctype html>
<html lang="{{ config('app.locale') }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Raleway', sans-serif;
                font-weight: 100;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 12px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @if (Auth::check())
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ url('/login') }}">Login</a>
                        <a href="{{ url('/register') }}">Register</a>
                    @endif
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    Laravel
                </div>

                <div class="links">
                    <a href="https://laravel.com/docs">Documentation</a>
                    <a href="https://laracasts.com">Laracasts</a>
                    <a href="https://laravel-news.com">News</a>
                    <a href="https://forge.laravel.com">Forge</a>
                    <a href="https://github.com/laravel/laravel">GitHub</a>
                </div>
            </div>
        </div>
    </body>
</html>
</code>```

答:
The problem was with file permissions. Change all the files to readable and writeable and it will be okay.

On macbook you can do it by entering this command in terminal:

```<code>chmod -R 777 /way/to/the/path/*
</code>```

Title: View doesn't return anything in Laravel

Body:
I just started to learn the laravel framework and have a strange situation here.

First of all in my web.php I have code like:

<?php
Route::get('/', function () {
    return view('welcome');
});

Route::get('users', ['uses' => 'UsersController@index']);

In my UsersController.php file I have code like:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function index(){
        return view('users.index');
    }
}

I have a file named index.blade.php in directory views/users that has the same content as the default welcome.blade.php. But when I try to return view('users.index'); there is no result (no error, or text) but when I try to return view('welcome'); it works just fine.

The directory and the file truly exists.
I'm using Macbook Pro.

welcome.blade.php and the /users/index.blade.php content (default welcome page):

<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">

            @if (Route::has('login'))

                    @if (Auth::check())
                        Home
                    @else
                        Login
                        Register
                    @endif

            @endif

                    Laravel

                    Documentation
                    Laracasts
                    News
                    Forge
                    GitHub

Body:
The problem was with file permissions. Change all the files to readable and writeable and it will be okay.

On macbook you can do it by entering this command in terminal:

chmod -R 777 /way/to/the/path/*


问:
How to count the total number of relations in neo4j?
I am trying the following query,

start n=node(*) match (n)-[r]->(m) return count(r)

I am not sure if this query is fine.

答:
You should use this query : MATCH ()-[r]->() RETURN count(*)

Cheers.

PS: The start, match query form should be only used for legacy index.


问:
Largest submatrix that is an identity matrix
I am trying to find the largest submatrix that is an identity matrix. I have no idea how to run through all the possible submatrices. I have however, managed to come up with a function that determines if a matrix is identity:

```<code>function isIdentityMatrix(matrix) {

  for (var i = 0; i < matrix.length; i++) {
    for (var j = 0; j < matrix.length; j++) {
      if (matrix[i][j] !== 1 && i === j || matrix[i][j] && i !== j) {
        return false;
      }
    }
  }
  return true;
}
</code>```

Any help in looping through all submatrices would be greatly appreciated. Keep in mind that I am a newbie to javascript.

答:
You can try something like this. This program

-Finds a sub-matrix
 -Returns true if that martrix is identity or not

Note: This works for nxn matrix only but can be easily tweaked to work with nxm matrix.

```<code>   let arr=[

[1,1,1,0,0],
[0,1,1,0,0],
[0,0,1,0,0],
[1,0,1,1,0],
[0,0,0,1,1]

];

let finalValue=0;
 let n=arr.length;

 let N=2;//size of submatrices

 function subMatrix(k,n,N,arr)
{

    let max_k_x=n-N+1;// per row max value of k
    let row=Math.floor(k/max_k_x);
    let col=k%max_k_x;

    /*
      k=6,n=4,N=2
      max_k=(4-2+1)*(4-2+1)=9
      max_k_x=3
      row=2(starting from zero)
      col=0
    */

let matrix=new Array();

for(let i=row;i<row+N;i++){
  for(let j=col;j<col+N;j++){

    matrix.push(arr[i][j]);

  }
}

return matrix;
}

 function doSomethingWithMatrix(matrix,N){

for(let i=0;i<matrix.length;i++){

        if((matrix[i] && (i%(N+1)!==0))||(matrix[i]!==1 && (i%(N+1))===0)){

     return false;

    }

    }

 return true;
}

 for(let k=0;k<(n-N+1)*(n-N+1);k++){//k can vary from 0 to (((n-N+1)^2)-1)

     let matrix=new Array();
  matrix=subMatrix(k,n,N,arr);
 // console.log(doSomethingWithMatrix(matrix,N));
   //  console.log("   ");
if(doSomethingWithMatrix(matrix,N)){

        finalValue=N;
         N++;
         k=0;
         if(N===n){
             N--;
             break;
         }

     }
     if(k===(n-N+1)*(n-N+1)-1){
         N++;
     }
     matrix=[];

}
console.log("final N: "+finalValue);
</code>```

You can change the value N inside the loop to check for NxN sub-matrices.

Body:
I am trying to find the largest submatrix that is an identity matrix. I have no idea how to run through all the possible submatrices. I have however, managed to come up with a function that determines if a matrix is identity:

function isIdentityMatrix(matrix) {

  for (var i = 0; i < matrix.length; i++) {
    for (var j = 0; j < matrix.length; j++) {
      if (matrix[i][j] !== 1 && i === j || matrix[i][j] && i !== j) {
        return false;
      }
    }
  }
  return true;
}

Any help in looping through all submatrices would be greatly appreciated. Keep in mind that I am a newbie to javascript.

Body:
You can try something like this. This program

-Finds a sub-matrix
 -Returns true if that martrix is identity or not

Note: This works for nxn matrix only but can be easily tweaked to work with nxm matrix.

   let arr=[

[1,1,1,0,0],
[0,1,1,0,0],
[0,0,1,0,0],
[1,0,1,1,0],
[0,0,0,1,1]

];

let finalValue=0;
 let n=arr.length;

 let N=2;//size of submatrices

 function subMatrix(k,n,N,arr)
{

    let max_k_x=n-N+1;// per row max value of k
    let row=Math.floor(k/max_k_x);
    let col=k%max_k_x;

    /*
      k=6,n=4,N=2
      max_k=(4-2+1)*(4-2+1)=9
      max_k_x=3
      row=2(starting from zero)
      col=0
    */

let matrix=new Array();

for(let i=row;i<row+N;i++){
  for(let j=col;j<col+N;j++){

    matrix.push(arr[i][j]);

  }
}

return matrix;
}

 function doSomethingWithMatrix(matrix,N){

for(let i=0;i<matrix.length;i++){

        if((matrix[i] && (i%(N+1)!==0))||(matrix[i]!==1 && (i%(N+1))===0)){

     return false;

    }

    }

 return true;
}

 for(let k=0;k<(n-N+1)*(n-N+1);k++){//k can vary from 0 to (((n-N+1)^2)-1)

     let matrix=new Array();
  matrix=subMatrix(k,n,N,arr);
 // console.log(doSomethingWithMatrix(matrix,N));
   //  console.log("   ");
if(doSomethingWithMatrix(matrix,N)){

        finalValue=N;
         N++;
         k=0;
         if(N===n){
             N--;
             break;
         }

     }
     if(k===(n-N+1)*(n-N+1)-1){
         N++;
     }
     matrix=[];

}
console.log("final N: "+finalValue);

You can change the value N inside the loop to check for NxN sub-matrices.


问:
Intellij - create custom setter for immutable objects
I'm trying to write a setter template in Intellij that will generate conventional immutable setters, those that create and return a new object instance upon setting a member.
e.g.

```<code>Person setName(String name) {
  return new Person(age, name);
}
</code>```

Has anyone been here before?

答:
A non answer: don't call this a setter.

By convention, a setter changes the instance you call it on.

So rather call it createCloneWithName() or something alike.

I guess you might be able to provide special templates to IntelliJ for such clone methods. But don't try to misuse setter generation for your purpose.

Body:
I'm trying to write a setter template in Intellij that will generate conventional immutable setters, those that create and return a new object instance upon setting a member.
e.g.

Person setName(String name) {
  return new Person(age, name);
}

Has anyone been here before?


问:
php - displaying error message based on uploading file size not working
I am making basic uploading file code. User is only allowed to upload two types of files, word and excel, and the file size limit to upload is 2MB.

I try to upload the word file and is 1MB, it has successfully uploaded to the database. When I test the code, the error message based on the incorrect file format is displayed, so it works.

Now here is the problem. When i try to test it by uploading the file 5MB, that is above the limit 2MB, it displayed the message "Contract Form Sucessfully Submitted!", but the file is not uploaded to the database. It works but it displayed the message wrong when it supposed to be "Sorry. Your file is too large. Only 2MB is allowed.".

So what is going on here?

PHP:

```<code>if ($_FILES['upload']['size'] != 0 ){

    $filename = mysqli_real_escape_string($con,$_FILES['upload']['name']);
    $filedata= mysqli_real_escape_string($con,file_get_contents($_FILES['upload']['tmp_name']));
    $filetype = mysqli_real_escape_string($con,$_FILES['upload']['type']);
    $filesize = intval($_FILES['upload']['size']);

    $created = date("Y-m-d H:i:s");

    $allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
    $ext = pathinfo($filename, PATHINFO_EXTENSION);

    if(in_array($ext, $allowed)){

        if($filesize < 2097152) {

            $query = "INSERT INTO contracts( `filename`,`filedata`,`filetype`,`filesize`,`created`)
                            VALUES (?,?,?,?,?)";
            $stmt = $con->prepare($query);
            $null = NULL;
            $stmt->bind_param("sbsis", $filename, $filedata, $filetype,$filesize,$created);
            $fp = fopen($_FILES['upload']['tmp_name'], "r");

                while (!feof($fp)) {
                $stmt->send_long_data(18, fread($fp,$filesize));
                }
                fclose($fp);
            $stmt->execute();

                if ($stmt->errno){
                    echo "ERROR!!! " . $stmt->error;
                    } else {
                    $successMsg = "Contract Form Sucessfully Submitted!";
                    }
            $stmt->close();

        } else {
            $errorMsg = "Sorry. Your file is too large. Only 2MB is allowed.";
        }
    } else {
        $errorMsg = "Sorry. Only zip, rar, pdf, doc & docx are allowed.";
    }
} else {
        $created = date("Y-m-d H:i:s");
        $query = "INSERT INTO contracts(`created`)
                        VALUES (?)" ;

        $stmt = $con->prepare($query);
        $stmt->bind_param("s", $created);
        $stmt->execute();

        if ($stmt->errno){
        echo "ERROR!!! " . $stmt->error;

        } else {
       $successMsg = "Contract Form Sucessfully Submitted!";
        }
        $stmt->close();
    }
}

$con->close();

?>
</code>```

HTML FORM:

```<code><html>
<body>

<form role="form" method="post" action="" enctype="multipart/form-data">
                <?php
                if(isset($errorMsg)){
                ?>
                <?php echo $errorMsg; ?>

                <?php
                } else if(isset($successMsg)){
                ?>

                 <?php echo $successMsg; ?>

                <?php
                }
                ?>

<label>Upload File</label>
                    <input type="file" name="upload" />

                <button type="submit" class="btn btn-primary btn-md" name="submit">
                    <span class="glyphicon glyphicon-plus"></span> Submit New Contract
                    </button>
</form>
</body>
</html>
</code>```

答:
Check upload_max_filesize and post_max_size in php.ini.and set them something like this

```<code>memory_limit = 32M
upload_max_filesize = 24M
post_max_size = 32M
</code>```

then restart your web server and php

you can see them with

```<code><?php
phpinfo();
</code>```

also

Body:
I am making basic uploading file code. User is only allowed to upload two types of files, word and excel, and the file size limit to upload is 2MB.

I try to upload the word file and is 1MB, it has successfully uploaded to the database. When I test the code, the error message based on the incorrect file format is displayed, so it works.

Now here is the problem. When i try to test it by uploading the file 5MB, that is above the limit 2MB, it displayed the message "Contract Form Sucessfully Submitted!", but the file is not uploaded to the database. It works but it displayed the message wrong when it supposed to be "Sorry. Your file is too large. Only 2MB is allowed.".

So what is going on here?

PHP:

if ($_FILES['upload']['size'] != 0 ){

    $filename = mysqli_real_escape_string($con,$_FILES['upload']['name']);
    $filedata= mysqli_real_escape_string($con,file_get_contents($_FILES['upload']['tmp_name']));
    $filetype = mysqli_real_escape_string($con,$_FILES['upload']['type']);
    $filesize = intval($_FILES['upload']['size']);

    $created = date("Y-m-d H:i:s");

    $allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
    $ext = pathinfo($filename, PATHINFO_EXTENSION);

    if(in_array($ext, $allowed)){

        if($filesize < 2097152) {

            $query = "INSERT INTO contracts( `filename`,`filedata`,`filetype`,`filesize`,`created`)
                            VALUES (?,?,?,?,?)";
            $stmt = $con->prepare($query);
            $null = NULL;
            $stmt->bind_param("sbsis", $filename, $filedata, $filetype,$filesize,$created);
            $fp = fopen($_FILES['upload']['tmp_name'], "r");

                while (!feof($fp)) {
                $stmt->send_long_data(18, fread($fp,$filesize));
                }
                fclose($fp);
            $stmt->execute();

                if ($stmt->errno){
                    echo "ERROR!!! " . $stmt->error;
                    } else {
                    $successMsg = "Contract Form Sucessfully Submitted!";
                    }
            $stmt->close();

        } else {
            $errorMsg = "Sorry. Your file is too large. Only 2MB is allowed.";
        }
    } else {
        $errorMsg = "Sorry. Only zip, rar, pdf, doc & docx are allowed.";
    }
} else {
        $created = date("Y-m-d H:i:s");
        $query = "INSERT INTO contracts(`created`)
                        VALUES (?)" ;

        $stmt = $con->prepare($query);
        $stmt->bind_param("s", $created);
        $stmt->execute();

        if ($stmt->errno){
        echo "ERROR!!! " . $stmt->error;

        } else {
       $successMsg = "Contract Form Sucessfully Submitted!";
        }
        $stmt->close();
    }
}

$con->close();

?>

HTML FORM:

<form role="form" method="post" action="" enctype="multipart/form-data">
                <?php
                if(isset($errorMsg)){
                ?>
                <?php echo $errorMsg; ?>

                <?php
                } else if(isset($successMsg)){
                ?>

                 <?php echo $successMsg; ?>

                <?php
                }
                ?>

Upload File
                    <input type="file" name="upload" />

                <button type="submit" class="btn btn-primary btn-md" name="submit">
                     Submit New Contract
                    </button>
</form>

Body:
Check upload_max_filesize and post_max_size in php.ini.and set them something like this

memory_limit = 32M
upload_max_filesize = 24M
post_max_size = 32M

then restart your web server and php

you can see them with

<?php
phpinfo();

also


问:
compare two generic list containing class objects
How do i compare two generic list(of cSystem) in my cSystemCatalog class? I wanna know if one of the list contains more or fewer class objects, I also want to compare _systemKey and _systemName</p>

```<code>Public Class cSystemCatalog
    Private _systems As List(Of cSystem)

Public Class cSystem
    Private _systemKey As Int32
    Private _systemName As String
</code>```

答:
```<code>If _systems1.Count = _systems2.Count AndAlso _
_systems1.All(Function(s1) _systems2.Any(Function(s2) _
s2._systemKey = s1._systemKey AndAlso s2._systemName = s1._systemName)) Then
</code>```

Provided you can use LINQ:

```<code>Imports System.LINQ
</code>```

Body:
How do i compare two generic list(of cSystem) in my cSystemCatalog class? I wanna know if one of the list contains more or fewer class objects, I also want to compare _systemKey and _systemName

Public Class cSystemCatalog
    Private _systems As List(Of cSystem)

Public Class cSystem
    Private _systemKey As Int32
    Private _systemName As String

Body:
If _systems1.Count = _systems2.Count AndAlso _
_systems1.All(Function(s1) _systems2.Any(Function(s2) _
s2._systemKey = s1._systemKey AndAlso s2._systemName = s1._systemName)) Then

Provided you can use LINQ:

Imports System.LINQ


问:
Why evaluate test data in a loop in tensorflow?
A few models implemented in TensorFlow posted on Github have their 'evaluation' function run a while loop, such as resnet (in resnet_main.py), etc.

I wonder why we need to evaluate the test data more than once.

答: You don't evaluate the test data more than once. You evaluate disjunct subsets of the test set in order to obtain the evaluation of the union of those subsets (that whole test set)</p>


问:
Dynamically create and update json using bash
In my hypothetical folder /hd/log/, I have 2 dozens Folder and each folder has log files in this format foldername.2017.07.09.log. I have a crontab that gzips the last log file every night, so there is a new log file with new log name every day.

I am trying to create a dynamic json file whose out put looks like this:

```<code>[
    {
        "Foldername": "foldername",
        "lastmodifiedfile": "/hd/log/foldername/foldername.2017.07.09.log"
    },
    {
        "Foldername": "foldername2",
        "lastmodifiedfile": "/hd/log/foldername2/foldername2.2017.07.09.log"
    }
]
</code>```

The bash script should be able to dynamically create array for each subfolder name (in case more folder are added or names are changed) and also give direct link to the last modified file.

I already php program to parse json file, but no sane way to crease this json file dynamically.

Any help or pointers is appreciated.

答:
```<code>printf "%s" "["
for var in $(find /hd/log -type d)
do
   path=$("ls -1t $var" | head -1)
   echo $var"/"$path | awk -F\/ '{ printf "%s","\n\t{\n\t\t\"Foldername\":\""$(NF-1)"\",\n\t\tlastmodifiedfile\":\""$0"\"\n\t},"}'
done
printf "%s" "]"
</code>```

Here we find all directories in /hd/log in a loop taking each directory in turn and then using ls -1t | head -1 to get the last modified file in the directory. The path and file is then parsed through awk to get the desired output. We first set the delimiter for awk as / with the -F flag. Then we then print the json syntax as required using the last but one / delimited piece of data for the directory (NF -1 - number field -1) and the complete line for the last modified file ($0).

Body:
In my hypothetical folder /hd/log/, I have 2 dozens Folder and each folder has log files in this format foldername.2017.07.09.log. I have a crontab that gzips the last log file every night, so there is a new log file with new log name every day.

I am trying to create a dynamic json file whose out put looks like this:

[
    {
        "Foldername": "foldername",
        "lastmodifiedfile": "/hd/log/foldername/foldername.2017.07.09.log"
    },
    {
        "Foldername": "foldername2",
        "lastmodifiedfile": "/hd/log/foldername2/foldername2.2017.07.09.log"
    }
]

The bash script should be able to dynamically create array for each subfolder name (in case more folder are added or names are changed) and also give direct link to the last modified file.

I already php program to parse json file, but no sane way to crease this json file dynamically.

Any help or pointers is appreciated.

Body:
printf "%s" "["
for var in $(find /hd/log -type d)
do
   path=$("ls -1t $var" | head -1)
   echo $var"/"$path | awk -F\/ '{ printf "%s","\n\t{\n\t\t\"Foldername\":\""$(NF-1)"\",\n\t\tlastmodifiedfile\":\""$0"\"\n\t},"}'
done
printf "%s" "]"

Here we find all directories in /hd/log in a loop taking each directory in turn and then using ls -1t | head -1 to get the last modified file in the directory. The path and file is then parsed through awk to get the desired output. We first set the delimiter for awk as / with the -F flag. Then we then print the json syntax as required using the last but one / delimited piece of data for the directory (NF -1 - number field -1) and the complete line for the last modified file ($0).


问:
list of tables without indexes in sql 2008
How do I list tables without indexes in my SQL 2008 database?

Edit

I want the Schema name and the Table name.

答:
Here's an example:</p>

```<code>select SCHEMA_NAME(schema_id), name from sys.tables
where OBJECTPROPERTY(object_id, 'IsIndexed')= 0
</code>```

Body:
Here's an example:

select SCHEMA_NAME(schema_id), name from sys.tables
where OBJECTPROPERTY(object_id, 'IsIndexed')= 0


问:
Mongoose Model populate callback is not called when there are references
I am trying to use Mongoose's Model.populate() to convert a user ID into a User, within a substructure of a document which has been fetched through an aggregation and an unwind. I'm guessing there's either something wrong with my schema or the perhaps unwind is breaking the connection to the sub-schema.

The problem is: when there is a valid reference, the populate callback simply isn't called. When there is no substructure the callback is called, with the original document unchanged.

Structure:

I have Articles which can have none or many ArticleRatings each by a User.

I'm using two references in the ArticleRating, to relate to the Article and the User who made the rating.

Process:

The process is actually exporting the articles to a (legacy) CSV format and flattening the structure, into duplicate article rows with their user-specific ratings. Unwind is perfect for this operation, and preserve nulls retains articles with no ratings.

Debugging:

I've tried stepping deep into the Model.populate code. It gets pretty complex with all the promises and callback wrappers, but I can see that the underlying populate call isn't calling the internal callbacks either. I'm not using the promise variant - but not 100% sure if I should be? (the Mongoose docs are a bit vague on the use-cases between callbacks and promises).

I've double checked my schema, tried explicitly adding the model to the populate call (which shouldn't be needed as it's in the schema). There are no errors or exceptions, it doesn't crash.

Stepping through the code in the Chrome debugger shows the model just as I'd expect: the first few Articles have a rating.userId with a valid ObjectId, but in those cases the populate callback simply doesn't get called. The next hundred Articles have no "rating" set, and the callback gets called reliably for all of them.

So I'm guessing something I'm doing wrong is leading Model.populate down a path where it's not erroring properly?

Note: I know I could rewrite the code to use aggregate $lookup or other embedding structures rather than the foreign reference, but I'm at the final piece of a feature jigsaw and would like to get this working as-is.

This is the simplified schema:

```<code>const ArticleRatingSchema = new Schema({
    articleId: {type: Schema.Types.ObjectId, ref:'Article'},
    userId: {type: Schema.Types.ObjectId, ref:'User'},
    rating: String,
    comment: String,
});

const ArticleSchema = new Schema({
    title: String,
    rating: ArticleRatingSchema,
});
</code>```

And this is the lookup

```<code>    // Find all articles relating to this project, and their ratings.
    // Unwind does the duplicate per-user, and preserve keeps un-rated articles.
    articleModel.aggregate([
            {$match: {projectId: projectId}},
            {$lookup:{from:'articleratings', localField:'_id', foreignField:'articleId', as:'rating' }},
            {$unwind: {path:'$rating', preserveNullAndEmptyArrays:true}}
        ], (err, models) =>
    {
        if (!err) {

            models.map((article) => {

                articleModel.populate(article, {path:'rating.userId', model:'User'}, (err, article)=> {
                    // Process the article...
                    // this callback only gets called where there is NO rating in the article.
                });

            });
        }
</code>```

答:
I realised it's because I'm processing the set in a synchronous map() loop, and the two cases must be different in that the non-matching populate is a synchronous callback whereas the matching replacements callback later.

If I console.log() in the callback, I find that the the four matching cases are processed last after the CSV has already been formatted and downloaded.

So the answer is: populate IS being called, but asynchronously.

I need to rework the map() loop to accomodate the usual async pattern.

Body:
I am trying to use Mongoose's Model.populate() to convert a user ID into a User, within a substructure of a document which has been fetched through an aggregation and an unwind. I'm guessing there's either something wrong with my schema or the perhaps unwind is breaking the connection to the sub-schema.

The problem is: when there is a valid reference, the populate callback simply isn't called. When there is no substructure the callback is called, with the original document unchanged.

Structure:

I have Articles which can have none or many ArticleRatings each by a User.

I'm using two references in the ArticleRating, to relate to the Article and the User who made the rating.

Process:

The process is actually exporting the articles to a (legacy) CSV format and flattening the structure, into duplicate article rows with their user-specific ratings. Unwind is perfect for this operation, and preserve nulls retains articles with no ratings.

Debugging:

I've tried stepping deep into the Model.populate code. It gets pretty complex with all the promises and callback wrappers, but I can see that the underlying populate call isn't calling the internal callbacks either. I'm not using the promise variant - but not 100% sure if I should be? (the Mongoose docs are a bit vague on the use-cases between callbacks and promises).

I've double checked my schema, tried explicitly adding the model to the populate call (which shouldn't be needed as it's in the schema). There are no errors or exceptions, it doesn't crash.

Stepping through the code in the Chrome debugger shows the model just as I'd expect: the first few Articles have a rating.userId with a valid ObjectId, but in those cases the populate callback simply doesn't get called. The next hundred Articles have no "rating" set, and the callback gets called reliably for all of them.

So I'm guessing something I'm doing wrong is leading Model.populate down a path where it's not erroring properly?

Note: I know I could rewrite the code to use aggregate $lookup or other embedding structures rather than the foreign reference, but I'm at the final piece of a feature jigsaw and would like to get this working as-is.

This is the simplified schema:

const ArticleRatingSchema = new Schema({
    articleId: {type: Schema.Types.ObjectId, ref:'Article'},
    userId: {type: Schema.Types.ObjectId, ref:'User'},
    rating: String,
    comment: String,
});

const ArticleSchema = new Schema({
    title: String,
    rating: ArticleRatingSchema,
});

And this is the lookup

    // Find all articles relating to this project, and their ratings.
    // Unwind does the duplicate per-user, and preserve keeps un-rated articles.
    articleModel.aggregate([
            {$match: {projectId: projectId}},
            {$lookup:{from:'articleratings', localField:'_id', foreignField:'articleId', as:'rating' }},
            {$unwind: {path:'$rating', preserveNullAndEmptyArrays:true}}
        ], (err, models) =>
    {
        if (!err) {

            models.map((article) => {

                articleModel.populate(article, {path:'rating.userId', model:'User'}, (err, article)=> {
                    // Process the article...
                    // this callback only gets called where there is NO rating in the article.
                });

            });
        }


问:
Found an unexpected Mach-O header code: 0x72613c21 on submitting to App Store
I know there are a lot of possible solutions but none of them have worked for me so far. I am using a framework called Alamofire.framework and Kingfisher.framework. I built an iOS App which I would like to submit to AppStore. I archived it and then I come in the Archives window and click "Upload to App Store".

The following error occurs: "Found an unexpected Mach-O header code:
  0x72613c21" with the following logs:

IDEDistribution.critical.log

2016-01-08 06:00:47 +0000 [MT] Failed to generate distribution items
  with error: Error Domain=DVTMachOErrorDomain Code=0 "Found an
  unexpected Mach-O header code: 0x72613c21"
  UserInfo={NSLocalizedDescription=Found an unexpected Mach-O header
  code: 0x72613c21, NSLocalizedRecoverySuggestion=} 2016-01-08 06:00:47
  +0000 [MT] Presenting: Error Domain=DVTMachOErrorDomain Code=0 "Found an unexpected Mach-O header code: 0x72613c21"
  UserInfo={NSLocalizedDescription=Found an unexpected Mach-O header
  code: 0x72613c21, NSLocalizedRecoverySuggestion=}

IDEDistribution.standard.log

2016-01-08 06:00:47 +0000 [MT] Beginning distribution assistant for
  archive: UCDA, task: Validate 2016-01-08 06:00:47 +0000 [MT]
  Automatically selecting the only availaable distribution method

  2016-01-08 06:00:47 +0000 [MT] [OPTIONAL] Didn't find archived user
  entitlements for
  :
  Error Domain=NSCocoaErrorDomain Code=4 "Item at
  "/Users/chikitin/Library/Developer/Xcode/Archives/2016-01-07/UCDA
  1-7-16, 11.59
  PM.xcarchive/Products/Applications/UCDA.app/Frameworks/FBSDKLoginKit.framework"
  did not contain a "archived-expanded-entitlements.xcent" resource."
  UserInfo={NSLocalizedDescription=Item at
  "/Users/chikitin/Library/Developer/Xcode/Archives/2016-01-07/UCDA
  1-7-16, 11.59
  PM.xcarchive/Products/Applications/UCDA.app/Frameworks/FBSDKLoginKit.framework"
  did not contain a "archived-expanded-entitlements.xcent" resource.}
  2016-01-08 06:05:27 +0000 [MT] Canceled distribution assistant

IDEDistribution.verbose.log

2016-01-08 06:00:47 +0000 [MT] IDEDistributionItem init

I hope someone could help me with this.

Thanks a lot!

答: You need to remove any Frameworks’ related files in the "Copy Bundle Resources” in the build phases. Please see https://kobkrit.com/how-to-fix-found-an-unexpected-mach-o-header-code-0x72613c21-on-submitting-to-app-store-7d5b8ec180c</p>


问:
How to play video .avi or mp4 in ionic
I have some files in format .avi and mp4, but I need to play those video in ionic.

How to play those files?

答:
Read through this: https://www.w3schools.com/html/html5_video.asp

It is the same concept however I have not yet found out how to play video in background on both IOS and native so if you figure this out let me know.

Title: How to play video .avi or mp4 in ionic


问:
Split an Integer into its digits c++
I'm trying to learn c++ on my own and I've hit a bit of a road block.  The problem is I need to take an integer,split it into its digits and get the sum of the digits and display them.

Example:

input number: 123456

digits in the integer: 1 2 3 4 5 6

sum: 21

I have it all done, but when I rip the integer, into digits I can't display it correctly. It displays in reverse order.

So in the program below I enter 1234 and it spits out 4 3 2 1.  I know why, I just don't know how to fix it.

Here is my code so far:

```<code>#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <math.h>

int countDigitsInInteger(int n)
{
    int count =0;
    while(n>0)
    {
       count++;
       n=n/10;
    }
    return count;
}

using namespace std;

int main(int argc, char *argv[])
{
    int intLength =0;
    int number;
    int digit;
    int sum = 0;
    string s;
    cout << "Please enter an integer ";
    cin >>number;
    cout << "Orginal Number = "<<number <<endl;
    //make the number positive
    if (number<0)
    number = -number;
    intLength = countDigitsInInteger(number);
    //break apart the integer into digits
    while(number>0)
    {
        digit = number % 10;
        number = number / 10;
        cout <<digit << " ";
        sum = sum+digit;
    }
    cout <<endl <<"Sum of the digits is: "<<sum<<endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}
</code>```

Here is my solution

can't see :)

答:
A simple solution:

```<code>int n = 12345;
vector<int> digits;
while (n != 0) {
    digits.insert(digits.begin(), n%10);
    n /= 10;
}
for(auto & i : digits)
    cout << i << " ";
</code>```

output:
1 2 3 4 5

Title: Split an Integer into its digits c++

Body:
I'm trying to learn c++ on my own and I've hit a bit of a road block.  The problem is I need to take an integer,split it into its digits and get the sum of the digits and display them.

Example:

input number: 123456

digits in the integer: 1 2 3 4 5 6

sum: 21

I have it all done, but when I rip the integer, into digits I can't display it correctly. It displays in reverse order.

So in the program below I enter 1234 and it spits out 4 3 2 1.  I know why, I just don't know how to fix it.

Here is my code so far:

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <math.h>

int countDigitsInInteger(int n)
{
    int count =0;
    while(n>0)
    {
       count++;
       n=n/10;
    }
    return count;
}

using namespace std;

int main(int argc, char *argv[])
{
    int intLength =0;
    int number;
    int digit;
    int sum = 0;
    string s;
    cout << "Please enter an integer ";
    cin >>number;
    cout << "Orginal Number = "<<number <<endl;
    //make the number positive
    if (number<0)
    number = -number;
    intLength = countDigitsInInteger(number);
    //break apart the integer into digits
    while(number>0)
    {
        digit = number % 10;
        number = number / 10;
        cout <<digit << " ";
        sum = sum+digit;
    }
    cout <<endl <<"Sum of the digits is: "<<sum<<endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}

Here is my solution

can't see :)

Body:
A simple solution:

int n = 12345;
vector<int> digits;
while (n != 0) {
    digits.insert(digits.begin(), n%10);
    n /= 10;
}
for(auto & i : digits)
    cout << i << " ";

output:
1 2 3 4 5

ContentLicense: CC BY-SA 4.0


问:
IN() Function not returning results using percentage sign
It's short and simple.

I'm using this query:

```<code>SELECT * FROM TABLE_NAME WHERE COL_NAME IN('%VALUE1%', '%VALUE2%')
</code>```

However it doesn't seem to work, I've used LIKE for both values combined using OR and it returns results, so I'm certain that there's rows in the table with these values.. am I missing something here?

Does MYSQL IN() function accept percentage sign? What is the right way to do it?

Thanks in advance!

答:
```<code>SELECT * FROM TABLE_NAME WHERE COL_NAME LIKE '%VALUE1%' OR COL_NAME LIKE '%VALUE2%'
</code>```

Body:
It's short and simple.

I'm using this query:

SELECT * FROM TABLE_NAME WHERE COL_NAME IN('%VALUE1%', '%VALUE2%')

However it doesn't seem to work, I've used LIKE for both values combined using OR and it returns results, so I'm certain that there's rows in the table with these values.. am I missing something here?

Does MYSQL IN() function accept percentage sign? What is the right way to do it?

Thanks in advance!


问:
React: How do I handle routing for language selection
React beginner here. I want to implement language selection in my new website. Users can select a particular country from a drop-down menu. Based upon the chosen language, the URL should update as /:country/about and the contents of the entire page should update accordingly.

Off the top of my mind, I could try one of the following options.

Define language in most parent app component state which when changes, re-renders the whole app (all children) with new language and settings.

Use location.href to load new URL containing the country code which would implement a full-reload with new language and settings.

index.js

```<code>ReactDOM.render
(
    <Provider store={store}>
        <BrowserRouter>
            <Switch>
                <Route path="/:country/about" component={AboutPage} />
                <Route path="/:country" component={HomePage} />
                <Route path="/" component={HomePage} />
            </Switch>
        </BrowserRouter>
    </Provider>,
    document.getElementById('app')
);
</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <title>Site Title</title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
  <div id="app"></div>
  <script src="assets/js/scripts.js"></script>
  <script src="/bundle.js"></script>

</body>
</html>
</code>```

Navigation Links

```<code><li>
    <Link to="/">Home</Link>
</li>
<li>
    <Link to="/:country/all-restaurants">All Restaurants</Link>
</li>
<li>
    <Link to="/:country/how-it-works">How It Works</Link>
</li>
<li>
    <Link to="/:country/about">About Us</Link>
</li>
<li>
    <Link to="/:country/restaurant">Lallo Pizzeria</Link>
</li>
</code>```

Note that with the new url, the path to all the images change with it. For eg, urls pointing to assets/img/image.jpg will be broken as the url changes.

```<code>Current: http://localhost:8080/assets/images/main-logo.png
New: http://localhost:8080/us/assets/images/main-logo.png
</code>```

I have little idea of what to next from here. What is the best way to handle this problem?

答:
It's enough that you change image URLs to proper ones starting with a slash like </p>

```<code>/assets/img/image.jpg
</code>```

<p>and they will point to </p>

```<code>http://localhost:8080/assets/img/image.jpg
</code>```

Body:
React beginner here. I want to implement language selection in my new website. Users can select a particular country from a drop-down menu. Based upon the chosen language, the URL should update as /:country/about and the contents of the entire page should update accordingly.

Off the top of my mind, I could try one of the following options.

Define language in most parent app component state which when changes, re-renders the whole app (all children) with new language and settings.

Use location.href to load new URL containing the country code which would implement a full-reload with new language and settings.

index.js

ReactDOM.render
(
    <Provider store={store}>
        <BrowserRouter>
            <Switch>
                <Route path="/:country/about" component={AboutPage} />
                <Route path="/:country" component={HomePage} />
                <Route path="/" component={HomePage} />
            </Switch>
        </BrowserRouter>
    </Provider>,
    document.getElementById('app')
);

index.html

<!DOCTYPE html>

    <title>Site Title</title>
    <link rel="stylesheet" href="assets/css/style.css">

Navigation Links

    <Link to="/">Home</Link>

    <Link to="/:country/all-restaurants">All Restaurants</Link>

    <Link to="/:country/how-it-works">How It Works</Link>

    <Link to="/:country/about">About Us</Link>

    <Link to="/:country/restaurant">Lallo Pizzeria</Link>

Note that with the new url, the path to all the images change with it. For eg, urls pointing to assets/img/image.jpg will be broken as the url changes.

Current: http://localhost:8080/assets/images/main-logo.png
New: http://localhost:8080/us/assets/images/main-logo.png

I have little idea of what to next from here. What is the best way to handle this problem?

Body:
It's enough that you change image URLs to proper ones starting with a slash like

/assets/img/image.jpg

and they will point to

http://localhost:8080/assets/img/image.jpg


问:
Full screen mode in php
I developed online exam for education company.I want to make my exam open on full screen mode.I tried several codes but don't work.Any help?
I disabled right click and f12. </p>

答:
You will need to use Javascript.
You can add a button or link that calls goFS() in it's href to trigger fullscreen in browser.</p>

```<code><script>
function goFS(){
        if (fs.requestFullscreen) {
            fs.requestFullscreen();
        } else if (fs.webkitRequestFullscreen) {
            fs.webkitRequestFullscreen();
        } else if (fs.mozRequestFullScreen) {
            fs.mozRequestFullScreen();
        } else if (fs.msRequestFullscreen) {
            fs.msRequestFullscreen();
        }
    }
</script>
</code>```

Title: Full screen mode in php

Body:
You will need to use Javascript.
You can add a button or link that calls goFS() in it's href to trigger fullscreen in browser.

<script>
function goFS(){
        if (fs.requestFullscreen) {
            fs.requestFullscreen();
        } else if (fs.webkitRequestFullscreen) {
            fs.webkitRequestFullscreen();
        } else if (fs.mozRequestFullScreen) {
            fs.mozRequestFullScreen();
        } else if (fs.msRequestFullscreen) {
            fs.msRequestFullscreen();
        }
    }
</script>


问:
When using range function to populate list why do I get list formatting error when printing with %d?
I'm learning python and I'm a bit puzzled by some behavior of lists when I create one using the range function. Hopefully someone can help me wrap my head around this? Here is a block of code I wrote:

```<code>elements = []
elements.append(range(1, 6))
for number in elements:
    print "Line %d" % number
</code>```

When I run this, I get the error for line 4:

TypeError: %d format: a number is required, not list

If I re-write the code as such:

```<code>elements = []
for i in range(1, 6):
    elements.append(i)
for number in elements:
    print "Line %d" % number
</code>```

it runs how I expected the first block would.

If I replace the %d with a %r, it prints the list as

Line [1, 2, 3, 4, 5]

instead of printing each number on its own line.

When I directly append the range to the elements list is it somehow making a list of a list instead of iterated values like it does when using the for?
With a little testing I got this:

```<code>>>> print range(1, 6)
[1, 2, 3, 4, 5]
>>> elements = []
>>> elements.append(range(1, 6))
>>> print elements
[[1, 2, 3, 4, 5]]
</code>```

Is this why it won't let me print the numbers using the %d formatter? How would I un-nest this list or access the contents of it? I'd be very grateful if someone could walk me through this. Thanks!

答:
What's happening when you append a list to another list is that you'll get a nested list. Initially you had elements = []. In that list you appended another list (range(1, 6)) which makes it a list of a list.

```<code>>>> elements = []
>>> elements
[]
>>> elements.append(range(1, 6))
>>> elements
[[1, 2, 3, 4, 5]]
</code>```

What you can do here is concatenate instead of appending by using the + operator (i.e. elements + range(1, 6).

```<code>>>> elements = []
>>> elements
[]
>>> elements + range(1, 6)
[1, 2, 3, 4, 5]
</code>```

Body:
I'm learning python and I'm a bit puzzled by some behavior of lists when I create one using the range function. Hopefully someone can help me wrap my head around this? Here is a block of code I wrote:

elements = []
elements.append(range(1, 6))
for number in elements:
    print "Line %d" % number

When I run this, I get the error for line 4:

TypeError: %d format: a number is required, not list

If I re-write the code as such:

elements = []
for i in range(1, 6):
    elements.append(i)
for number in elements:
    print "Line %d" % number

it runs how I expected the first block would.

If I replace the %d with a %r, it prints the list as

Line [1, 2, 3, 4, 5]

instead of printing each number on its own line.

When I directly append the range to the elements list is it somehow making a list of a list instead of iterated values like it does when using the for?
With a little testing I got this:

>>> print range(1, 6)
[1, 2, 3, 4, 5]
>>> elements = []
>>> elements.append(range(1, 6))
>>> print elements
[[1, 2, 3, 4, 5]]

Is this why it won't let me print the numbers using the %d formatter? How would I un-nest this list or access the contents of it? I'd be very grateful if someone could walk me through this. Thanks!

Body:
What's happening when you append a list to another list is that you'll get a nested list. Initially you had elements = []. In that list you appended another list (range(1, 6)) which makes it a list of a list.

>>> elements = []
>>> elements
[]
>>> elements.append(range(1, 6))
>>> elements
[[1, 2, 3, 4, 5]]

What you can do here is concatenate instead of appending by using the + operator (i.e. elements + range(1, 6).

>>> elements = []
>>> elements
[]
>>> elements + range(1, 6)
[1, 2, 3, 4, 5]


问:
Why color changes after redrawing again on canvas using javascript?
Here a sample of code that product the effect on color.

The question is "why rectangles (rect 1 and rect 2) are not the same color ?

```<code>    <!DOCTYPE html>
    <html>
    <body>
    <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>

    <script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");

    ctx.strokeRect(5, 5, 25, 15); //rect 1

    ctx.strokeRect(55, 5, 25, 15); // rect 2
    ctx.strokeRect(55, 5, 25, 15); // rect 2 again
    </script>
    </body>
    </html>
</code>```

答:
because you are drawing two rectangles in the same place and that make the color of canvas that way.

Test this one.

```<code>    <!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.strokeRect(5, 5, 25, 15); //rect 1

ctx.strokeRect(55, 5, 25, 15); // rect 2
ctx.strokeRect(75, 5, 25, 15); // rect 2 again
</script>
</body>
</html>
</code>```

Body:
Here a sample of code that product the effect on color.

The question is "why rectangles (rect 1 and rect 2) are not the same color ?

    <!DOCTYPE html>

    <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>

Body:
because you are drawing two rectangles in the same place and that make the color of canvas that way.

Test this one.

    <!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.strokeRect(5, 5, 25, 15); //rect 1

ctx.strokeRect(55, 5, 25, 15); // rect 2
ctx.strokeRect(75, 5, 25, 15); // rect 2 again
</script>
</body>
</html>